Repository navigation
Expand file tree
/
Copy pathch33.html
More file actions
2604 lines (2264 loc) · 103 KB
/
Copy pathch33.html
File metadata and controls
2604 lines (2264 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>第三十三章:MCP模型上下文协议 - AI学习笔记</title>
<meta name="description" content="AI学习笔记第三十三章:MCP模型上下文协议 - 理解MCP协议架构、核心概念、传输机制、服务端与客户端开发,以及安全最佳实践。">
<meta name="keywords" content="MCP, 模型上下文协议, Model Context Protocol, LLM工具集成, API标准化, AI Agent, 工具调用">
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<!-- KaTeX -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<!-- Prism.js -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
<!-- AI-Notes共享样式 -->
<link rel="stylesheet" href="assets/ai-notes.css">
</head>
<body>
<!-- ==================== 导航栏 ==================== -->
<nav class="ai-nav">
<a href="../index.html" class="ai-nav-brand">
<i class="fas fa-brain"></i> AI学习笔记
</a>
<button class="ai-nav-toggle" id="navbarToggle">
<i class="fas fa-bars"></i>
</button>
<ul class="ai-nav-links" id="navbarLinks">
<li><a href="../index.html"><i class="fas fa-home"></i> 首页</a></li>
<li><a href="index.html"><i class="fas fa-list"></i> 目录</a></li>
<li><a href="ch32.html"><i class="fas fa-arrow-left"></i> 上一章</a></li>
<li><a href="appendix-g.html"><i class="fas fa-arrow-right"></i> 下一章</a></li>
</ul>
</nav>
<!-- ==================== 主要内容 ==================== -->
<div class="content-wrapper">
<main class="main-content">
<!-- 章节标题 -->
<h1 style="font-size: 2.2rem; color: #1a365d; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.75rem;">
<i class="fas fa-plug" style="color: #4299e1;"></i>
第三十三章:MCP模型上下文协议
</h1>
<p style="color: #718096; font-size: 1.05rem; margin-bottom: 2rem;">Model Context Protocol —— 让AI与外部世界对话的标准化接口</p>
<!-- 学习目标 -->
<div class="ai-box ai-box--objectives">
<h4><i class="fas fa-bullseye"></i> 学习目标</h4>
<ul>
<li>理解MCP协议的设计动机与核心价值</li>
<li>掌握MCP的三层架构:Host、Client、Server</li>
<li>理解Resources、Tools、Prompts、Sampling四大原语</li>
<li>掌握基于JSON-RPC 2.0的协议规范</li>
<li>能够使用Python和TypeScript开发MCP Server</li>
<li>了解MCP的安全机制与最佳实践</li>
</ul>
</div>
<!-- 前置要求 -->
<div class="ai-box ai-box--prereq">
<h4><i class="fas fa-graduation-cap"></i> 前置知识</h4>
<ul>
<li>了解大语言模型的基本工作原理(第1-15章)</li>
<li>熟悉REST API与JSON-RPC协议基础</li>
<li>具备Python或TypeScript编程基础</li>
<li>了解AI Agent的概念(第二十九章)</li>
</ul>
</div>
<figure class="ai-figure">
<img src="https://trae-api-cn.mchost.guru/api/ide/v1/text_to_image?prompt=MCP%20Model%20Context%20Protocol%20architecture%2C%20host%20client%20server%20three%20layers%2C%20resources%20tools%20prompts%20sampling%20primitives%2C%20JSON-RPC%20communication%20flow%2C%20clean%20educational%20infographic%20style%2C%20flat%20design%2C%20white%20background&image_size=landscape_4_3" alt="MCP模型上下文协议架构图" loading="lazy">
<figcaption><strong>图33-1</strong> MCP协议架构:Host、Client、Server三层结构与四大核心原语</figcaption>
</figure>
<!-- ==================== 第一节:MCP简介 ==================== -->
<div class="concept-section" id="sec1">
<h2 class="ai-section-title">
<i class="fas fa-info-circle"></i>
一、MCP简介:为什么需要模型上下文协议
</h2>
<p style="margin-bottom: 1rem;">
在大语言模型快速发展的今天,每个AI应用都需要与外部数据源、工具和服务进行交互。然而,如果没有统一的标准,每个集成都需要从头开发,导致了大量重复劳动和碎片化问题。MCP(Model Context Protocol)正是为了解决这个问题而诞生的开放标准协议。
</p>
<div class="concept-box">
<h4><i class="fas fa-lightbulb"></i> MCP是什么</h4>
<p>
MCP是由Anthropic于2024年底发布的开源协议,全称为Model Context Protocol(模型上下文协议)。它定义了一种标准化的方式,让AI模型能够安全、高效地与外部世界进行交互——包括读取数据、执行操作、访问工具等。
</p>
<ul>
<li><strong>标准化接口</strong>:就像USB-C统一了设备连接方式,MCP统一了AI与外部服务的连接方式</li>
<li><strong>可复用组件</strong>:一个MCP Server可以被任何支持MCP的AI应用复用</li>
<li><strong>安全隔离</strong>:通过明确定义的权限边界,确保数据访问的安全性</li>
<li><strong>跨平台兼容</strong>:不依赖特定的LLM提供商或应用框架</li>
</ul>
</div>
<div class="ai-tip">
<strong>MCP的核心价值</strong>
<p>
在MCP出现之前,如果你想让AI助手访问数据库、文件系统或API,通常需要为每个集成编写定制代码。MCP让这变成"插拔式"的:编写一次MCP Server,所有支持MCP的AI应用都能使用。
</p>
</div>
<h3 class="ai-section-subtitle">
<i class="fas fa-code-branch"></i>
MCP与函数调用的区别
</h3>
<p style="margin-bottom: 1rem;">
很多开发者会混淆MCP与LLM的Function Calling。实际上,Function Calling是LLM内部的能力,而MCP是外部的标准化通信协议。两者是互补的关系,而非替代关系。
</p>
<table class="comparison-table">
<thead>
<tr>
<th>维度</th>
<th>Function Calling</th>
<th>MCP</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>性质</strong></td>
<td>LLM内部能力</td>
<td>外部标准化协议</td>
</tr>
<tr>
<td><strong>定义位置</strong></td>
<td>应用代码中</td>
<td>独立的MCP Server</td>
</tr>
<tr>
<td><strong>复用性</strong></td>
<td>每个应用独立实现</td>
<td>跨应用复用</td>
</tr>
<tr>
<td><strong>协议规范</strong></td>
<td>各厂商各自定义</td>
<td>统一标准(JSON-RPC 2.0)</td>
</tr>
<tr>
<td><strong>安全边界</strong></td>
<td>由应用控制</td>
<td>协议层内置权限控制</td>
</tr>
</tbody>
</table>
<div class="ai-usage">
<strong>类比理解:</strong> Function Calling 像是"车里的方向盘",MCP 像是"道路标准"——方向盘让你能操控车,而道路标准让不同品牌的车都能在同一条路上行驶。
</div>
</div>
<!-- ==================== 第二节:架构设计 ==================== -->
<div class="concept-section" id="sec2">
<h2 class="ai-section-title">
<i class="fas fa-sitemap"></i>
二、架构设计:Host、Client、Server
</h2>
<p style="margin-bottom: 1rem;">
MCP采用分层架构,包含三个核心角色:Host(宿主)、Client(客户端)和Server(服务端)。这种分层设计使得协议既灵活又安全。
</p>
<div class="concept-box">
<h4><i class="fas fa-server"></i> 三层架构概览</h4>
<ul>
<li><strong>Host(宿主)</strong>:用户直接交互的AI应用,如Claude Desktop、IDE插件或自定义聊天应用。Host负责管理整体的用户体验和会话状态。</li>
<li><strong>Client(客户端)</strong>:嵌入在Host中的MCP客户端组件,负责与MCP Server建立连接、协商能力并处理消息。每个Client维护与一个Server的1:1连接。</li>
<li><strong>Server(服务端)</strong>:独立运行的服务,通过MCP协议暴露Resources、Tools、Prompts等能力。Server可以是本地进程或远程服务。</li>
</ul>
</div>
<p style="margin-bottom: 1rem;">
一个Host可以同时连接多个Client,每个Client对应一个Server。这种设计使得Host能够聚合来自不同Server的能力,同时保持清晰的权限边界。
</p>
<figure style="margin:2rem 0;">
<iframe src="assets/images/mcp-architecture.html" style="width:100%;height:360px;border:none;background:var(--bg-color,#f8f9fa);border-radius:8px;"></iframe>
<figcaption style="text-align:center;font-size:0.9rem;color:#718096;margin-top:0.5rem;">MCP协议架构:模型上下文协议的三层结构</figcaption>
</figure>
<h3 class="ai-section-subtitle">
<i class="fas fa-handshake"></i>
连接生命周期
</h3>
<p style="margin-bottom: 1rem;">
MCP Client与Server之间的连接遵循标准的生命周期管理流程:
</p>
<div class="concept-box">
<h4><i class="fas fa-exchange-alt"></i> 连接三阶段</h4>
<ul>
<li><strong>1. 初始化(Initialize)</strong>:Client发送initialize请求,包含自身支持的协议版本和能力。Server返回自己的协议版本和能力。双方据此协商出共同支持的功能子集。</li>
<li><strong>2. 运行(Operate)</strong>:连接建立后,Client和Server可以自由交换请求和通知。Server可以提供Resources、Tools和Prompts,Client可以调用这些能力。</li>
<li><strong>3. 关闭(Shutdown)</strong>:任一方可以优雅地关闭连接。Client在关闭前应确保所有进行中的操作已完成。</li>
</ul>
</div>
<p style="margin-bottom: 1rem;">
这种设计确保了连接的可靠性和可预测性,使得错误处理和资源清理变得更加容易。
</p>
<h3 class="ai-section-subtitle">
<i class="fas fa-arrows-alt-h"></i>
消息流动模式
</h3>
<p style="margin-bottom: 1rem;">
MCP中的消息流动遵循严格的请求-响应和通知两种模式。理解这些模式对于正确实现协议至关重要。
</p>
<div class="concept-box">
<h4><i class="fas fa-exchange-alt"></i> 请求-响应模式</h4>
<p>
Client发送一个请求(带有id字段),Server处理后返回对应的响应(带有相同id)。这是MCP中最常见的通信模式。例如:Client调用Tool、读取Resource等。
</p>
<ul>
<li><strong>同步语义</strong>:虽然底层传输可能是异步的,但协议层面保证每个请求最多对应一个响应</li>
<li><strong>超时处理</strong>:Client应为每个请求设置合理的超时时间,超时后应终止等待并清理资源</li>
<li><strong>错误响应</strong>:Server可以返回错误响应(error字段),Client应根据错误码决定重试或报错</li>
</ul>
</div>
<div class="concept-box">
<h4><i class="fas fa-bell"></i> 通知模式</h4>
<p>
通知是没有id字段的消息,发送方不期望收到响应。通知常用于进度更新、状态变化等不需要回复的场景。
</p>
<ul>
<li><strong>进度更新</strong>:Server在处理耗时操作时发送进度通知</li>
<li><strong>资源变更</strong>:Server通知Client某个资源已更新</li>
<li><strong>日志消息</strong>:Server发送调试或信息日志</li>
</ul>
</div>
<span class="code-label">JSON - 通知示例</span>
<pre><code class="language-json">// Server → Client: 进度通知
{
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"progressToken": "abc-123",
"progress": 50,
"total": 100,
"message": "正在处理第50条记录..."
}
}
// Server → Client: 资源变更通知
{
"jsonrpc": "2.0",
"method": "notifications/resources/updated",
"params": {
"uri": "file:///data/report.csv"
}
}
</code></pre>
<div class="ai-warning">
<strong>通知不可靠性</strong>
<p>
通知是"发后即忘"的,不保证送达。如果Client需要可靠的进度更新,应使用带有进度token的请求,通过progressNotification跟踪进度。对于关键状态变更,应使用请求-响应模式。
</p>
</div>
<h3 class="ai-section-subtitle">
<i class="fas fa-project-diagram"></i>
多Server聚合模式
</h3>
<p style="margin-bottom: 1rem;">
在实际应用中,一个Host可能需要连接多个Server来聚合不同的能力。MCP的架构设计天然支持这种多Server聚合模式。
</p>
<div class="concept-box">
<h4><i class="fas fa-layer-group"></i> 聚合架构</h4>
<ul>
<li><strong>扁平聚合</strong>:Host直接管理多个Client,每个Client对应一个Server。适用于Server数量较少的场景。</li>
<li><strong>层级聚合</strong>:引入Aggregator Server,它本身也是一个MCP Server,同时作为Client连接多个下游Server。适用于需要统一入口的场景。</li>
<li><strong>混合模式</strong>:结合扁平和层级模式,关键Server直接连接,辅助Server通过Aggregator聚合。</li>
</ul>
</div>
<span class="code-label">Python - 多Server管理</span>
<pre><code class="language-python">"""
多Server管理示例
展示如何在Host中管理多个MCP Server
"""
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
class MultiServerHost:
def __init__(self):
self.sessions: dict[str, ClientSession] = {}
async def add_server(self, name: str, params: StdioServerParameters):
"""添加并连接一个新的MCP Server"""
read, write = await stdio_client(params).__aenter__()
session = ClientSession(read, write)
await session.__aenter__()
await session.initialize()
self.sessions[name] = session
print(f"已连接到Server: {name}")
# 列出该Server提供的能力
tools = await session.list_tools()
print(f" 工具: {[t.name for t in tools.tools]}")
resources = await session.list_resources()
print(f" 资源: {[r.uri for r in resources.resources]}")
async def call_tool(self, server_name: str, tool_name: str, args: dict):
"""调用指定Server上的工具"""
if server_name not in self.sessions:
raise ValueError(f"Server未连接: {server_name}")
session = self.sessions[server_name]
result = await session.call_tool(tool_name, args)
return result.content[0].text
async def search_tools(self, query: str):
"""在所有Server中搜索工具"""
results = []
for name, session in self.sessions.items():
tools = await session.list_tools()
for tool in tools.tools:
if query.lower() in tool.name.lower() or \
query.lower() in tool.description.lower():
results.append({
"server": name,
"tool": tool.name,
"description": tool.description
})
return results
async def disconnect_all(self):
"""断开所有Server连接"""
for name, session in self.sessions.items():
await session.close()
print(f"已断开Server: {name}")
self.sessions.clear()
async def main():
host = MultiServerHost()
# 连接文件系统Server
await host.add_server("filesystem", StdioServerParameters(
command="python",
args=["filesystem_server.py"]
))
# 连接数据库Server
await host.add_server("database", StdioServerParameters(
command="python",
args=["database_server.py"]
))
# 搜索所有包含"read"的工具
read_tools = await host.search_tools("read")
print(f"\n包含'read'的工具:")
for t in read_tools:
print(f" [{t['server']}] {t['tool']}: {t['description']}")
# 调用文件系统Server的read_file工具
content = await host.call_tool(
"filesystem", "read_file",
{"path": "config.json"}
)
print(f"\n文件内容:\n{content}")
await host.disconnect_all()
if __name__ == "__main__":
asyncio.run(main())
</code></pre>
<div class="ai-info">
<strong>聚合模式选择</strong>
<p>
对于桌面应用(如Claude Desktop),通常使用扁平聚合,直接管理所有Server连接。对于Web应用或微服务架构,层级聚合更合适,通过一个网关Server统一对外暴露接口。选择哪种模式取决于应用的部署架构和安全需求。
</p>
</div>
</div>
<!-- ==================== 第三节:核心概念 ==================== -->
<div class="concept-section" id="sec3">
<h2 class="ai-section-title">
<i class="fas fa-cubes"></i>
三、核心概念:四大原语
</h2>
<p style="margin-bottom: 1rem;">
MCP定义了四种核心原语(Primitives),它们是Server向Client暴露能力的基本方式。理解这四种原语是掌握MCP的关键。
</p>
<h3 class="ai-section-subtitle">
<i class="fas fa-file-alt"></i>
3.1 Resources:数据资源
</h3>
<p style="margin-bottom: 1rem;">
Resources代表Server可以提供的数据内容,类似于REST API中的GET端点。Resources是只读的,由应用程序或用户控制是否包含在LLM上下文中。
</p>
<div class="concept-box">
<h4><i class="fas fa-database"></i> Resource的类型</h4>
<ul>
<li><strong>文件内容</strong>:本地文件、配置文件、文档等</li>
<li><strong>数据库记录</strong>:特定表、查询结果或记录</li>
<li><strong>API响应</strong>:外部API返回的数据</li>
<li><strong>实时信息</strong>:系统状态、监控数据等</li>
</ul>
</div>
<span class="code-label">Python</span>
<pre><code class="language-python">from mcp.server import Server
from mcp.types import Resource, ResourceContents
server = Server("my-server")
# 定义一个文件资源
@server.resource("file:///logs/{date}")
async def get_log_file(date: str) -> ResourceContents:
"""读取指定日期的日志文件"""
file_path = f"/var/log/app/{date}.log"
content = await read_file(file_path)
return ResourceContents(
uri=f"file:///logs/{date}",
mimeType="text/plain",
text=content
)
# 定义一个动态资源
@server.resource("db://users/{user_id}")
async def get_user(user_id: str) -> ResourceContents:
"""获取用户信息"""
user = await db.get_user(user_id)
return ResourceContents(
uri=f"db://users/{user_id}",
mimeType="application/json",
text=json.dumps(user)
)
</code></pre>
<h3 class="ai-section-subtitle">
<i class="fas fa-wrench"></i>
3.2 Tools:可执行工具
</h3>
<p style="margin-bottom: 1rem;">
Tools代表Server可以执行的操作,由模型控制(LLM决定何时调用)。Tools类似于函数,接受输入参数并返回执行结果。与Resources不同,Tools是有副作用的。
</p>
<div class="concept-box">
<h4><i class="fas fa-cog"></i> Tool的特征</h4>
<ul>
<li><strong>模型控制</strong>:由LLM根据上下文决定是否调用</li>
<li><strong>有副作用</strong>:可能修改外部状态(如发送邮件、更新数据库)</li>
<li><strong>参数化</strong>:通过JSON Schema定义输入参数</li>
<li><strong>结果返回</strong>:执行后返回文本或结构化数据</li>
</ul>
</div>
<span class="code-label">Python</span>
<pre><code class="language-python">from mcp.server import Server
from mcp.types import Tool, ToolResult
from pydantic import BaseModel
server = Server("my-server")
# 定义工具的输入参数
class SendEmailArgs(BaseModel):
to: str
subject: str
body: str
# 注册邮件发送工具
@server.tool()
async def send_email(args: SendEmailArgs) -> ToolResult:
"""发送邮件到指定地址"""
await email_service.send(
to=args.to,
subject=args.subject,
body=args.body
)
return ToolResult(
content=f"邮件已发送至 {args.to}",
isError=False
)
# 注册数据库查询工具
@server.tool()
async def query_database(sql: str) -> ToolResult:
"""执行SQL查询"""
try:
results = await db.execute(sql)
return ToolResult(
content=json.dumps(results),
isError=False
)
except Exception as e:
return ToolResult(
content=f"查询失败: {str(e)}",
isError=True
)
</code></pre>
<h3 class="ai-section-subtitle">
<i class="fas fa-comments"></i>
3.3 Prompts:提示模板
</h3>
<p style="margin-bottom: 1rem;">
Prompts是Server提供的预定义提示模板,由用户控制(用户选择是否使用)。Prompts可以将上下文和指令封装为可复用的模板,简化复杂的交互流程。
</p>
<span class="code-label">Python</span>
<pre><code class="language-python">from mcp.server import Server
from mcp.types import Prompt, PromptMessage, Role
server = Server("my-server")
@server.prompt()
async def code_review_prompt(
repository: str,
pull_request: int
) -> list[PromptMessage]:
"""代码审查提示模板"""
# 获取PR信息
pr_info = await github.get_pr(repository, pull_request)
diff = await github.get_diff(repository, pull_request)
return [
PromptMessage(
role=Role.USER,
content=f"请审查以下Pull Request:\n\n"
f"标题: {pr_info['title']}\n"
f"描述: {pr_info['body']}\n\n"
f"代码变更:\n{diff}"
)
]
</code></pre>
<h3 class="ai-section-subtitle">
<i class="fas fa-robot"></i>
3.4 Sampling:模型采样
</h3>
<p style="margin-bottom: 1rem;">
Sampling是MCP最独特的原语,它允许Server请求LLM进行文本生成。这使得Server可以利用AI能力完成复杂任务,同时Host保持对采样过程的完全控制。
</p>
<div class="concept-box">
<h4><i class="fas fa-brain"></i> Sampling工作流</h4>
<ul>
<li>1. Server向Client发送sampling/createMessage请求</li>
<li>2. Client(通常由Host)可以审查和修改请求</li>
<li>3. 请求被发送到LLM进行推理</li>
<li>4. 响应返回给Server</li>
</ul>
</div>
<div class="ai-warning">
<strong>Sampling安全原则</strong>
<p>
Sampling赋予了Server调用LLM的能力,因此必须严格控制。Host应该:(1) 对所有采样请求进行人类审批;(2) 限制采样可以使用的模型范围;(3) 记录所有采样活动以供审计。
</p>
</div>
</div>
<!-- ==================== 第四节:协议规范 ==================== -->
<div class="concept-section" id="sec4">
<h2 class="ai-section-title">
<i class="fas fa-file-code"></i>
四、协议规范:JSON-RPC 2.0
</h2>
<p style="margin-bottom: 1rem;">
MCP基于JSON-RPC 2.0构建,这是一种轻量级的远程过程调用协议。JSON-RPC使用JSON作为数据格式,支持请求-响应和通知两种消息模式。
</p>
<div class="concept-box">
<h4><i class="fas fa-exchange-alt"></i> 消息类型</h4>
<ul>
<li><strong>Request(请求)</strong>:带有id字段,期望收到Response。例如:tools/call、resources/read</li>
<li><strong>Response(响应)</strong>:包含result或error字段,与请求的id对应</li>
<li><strong>Notification(通知)</strong>:没有id字段,不期望响应。例如:进度更新、日志消息</li>
</ul>
</div>
<h3 class="ai-section-subtitle">
<i class="fas fa-plug"></i>
初始化握手
</h3>
<p style="margin-bottom: 1rem;">
连接建立时,Client和Server通过初始化消息交换能力信息:
</p>
<span class="code-label">JSON</span>
<pre><code class="language-json">// Client → Server: 初始化请求
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": { "listChanged": true },
"sampling": {}
},
"clientInfo": {
"name": "MyAIApp",
"version": "1.0.0"
}
}
}
// Server → Client: 初始化响应
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"resources": { "subscribe": true },
"tools": { "listChanged": true },
"prompts": {}
},
"serverInfo": {
"name": "DatabaseServer",
"version": "1.0.0"
}
}
}
</code></pre>
<h3 class="ai-section-subtitle">
<i class="fas fa-list"></i>
能力发现
</h3>
<p style="margin-bottom: 1rem;">
初始化完成后,Client可以通过列表请求发现Server提供的所有能力:
</p>
<span class="code-label">JSON</span>
<pre><code class="language-json">// Client → Server: 列出所有工具
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}
// Server → Client: 返回工具列表
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"tools": [
{
"name": "query_database",
"description": "执行SQL查询",
"inputSchema": {
"type": "object",
"properties": {
"sql": {
"type": "string",
"description": "SQL查询语句"
}
},
"required": ["sql"]
}
},
{
"name": "send_email",
"description": "发送邮件",
"inputSchema": {
"type": "object",
"properties": {
"to": { "type": "string" },
"subject": { "type": "string" },
"body": { "type": "string" }
},
"required": ["to", "subject", "body"]
}
}
]
}
}
</code></pre>
<div class="ai-info">
<strong>能力协商机制</strong>
<p>
MCP的初始化阶段使用协商机制:Client和Server各自声明自己支持的能力版本,最终以双方都支持的最高版本为准。这确保了协议的向后兼容性,使得不同版本的Client和Server可以互相通信。
</p>
</div>
<h3 class="ai-section-subtitle">
<i class="fas fa-exclamation-circle"></i>
错误处理机制
</h3>
<p style="margin-bottom: 1rem;">
MCP定义了一套标准的错误码体系,用于处理各种异常情况。正确的错误处理对于构建健壮的MCP应用至关重要。
</p>
<div class="concept-box">
<h4><i class="fas fa-bug"></i> 标准错误码</h4>
<ul>
<li><strong>-32700</strong> Parse Error:JSON解析失败,Server收到的不是有效的JSON</li>
<li><strong>-32600</strong> Invalid Request:请求格式正确但语义无效</li>
<li><strong>-32601</strong> Method Not Found:请求的方法不存在或未实现</li>
<li><strong>-32602</strong> Invalid Params:参数验证失败,缺少必填参数或参数类型错误</li>
<li><strong>-32603</strong> Internal Error:Server内部错误,如未捕获的异常</li>
</ul>
</div>
<span class="code-label">JSON - 错误响应示例</span>
<pre><code class="language-json">// 参数验证错误
{
"jsonrpc": "2.0",
"id": 3,
"error": {
"code": -32602,
"message": "Invalid parameters",
"data": {
"field": "path",
"reason": "Path must be a non-empty string"
}
}
}
// 工具执行错误
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"content": [{
"type": "text",
"text": "文件不存在: /nonexistent/file.txt"
}],
"isError": true
}
}
</code></pre>
<div class="ai-tip">
<strong>错误处理最佳实践</strong>
<p>
Server应尽量返回有意义的错误信息,而不是抛出原始异常。在ToolResult中,使用isError=True标记错误结果,并在content中包含用户友好的错误描述。对于可重试的错误(如网络超时),Client可以自动重试;对于永久性错误(如文件不存在),应向用户报告。
</p>
</div>
<h3 class="ai-section-subtitle">
<i class="fas fa-sync-alt"></i>
取消与超时
</h3>
<p style="margin-bottom: 1rem;">
在实际使用中,某些操作可能耗时较长或被用户主动取消。MCP提供了标准化的取消机制来处理这些场景。
</p>
<div class="concept-box">
<h4><i class="fas fa-stop-circle"></i> 取消机制</h4>
<ul>
<li><strong>请求取消</strong>:Client可以发送notifications/cancelled通知来取消一个进行中的请求</li>
<li><strong>进度token</strong>:请求可以包含progressToken,用于跟踪和取消特定操作</li>
<li><strong>优雅降级</strong>:Server收到取消通知后应尽快停止处理,并返回部分结果(如果可能)</li>
</ul>
</div>
<span class="code-label">JSON - 取消操作</span>
<pre><code class="language-json">// Client → Server: 取消进行中的请求
{
"jsonrpc": "2.0",
"method": "notifications/cancelled",
"params": {
"requestId": 5,
"reason": "用户取消操作"
}
}
</code></pre>
<p style="margin-bottom: 1rem;">
超时是另一个重要的考虑因素。Client应该为每个请求设置合理的超时时间,避免无限等待。MCP规范建议使用30秒作为默认超时时间,对于长时间运行的操作(如文件上传),可以通过进度通知来延长超时。
</p>
</div>
<!-- ==================== 第五节:传输机制 ==================== -->
<div class="concept-section" id="sec5">
<h2 class="ai-section-title">
<i class="fas fa-network-wired"></i>
五、传输机制
</h2>
<p style="margin-bottom: 1rem;">
MCP的传输层负责消息的序列化和通信。协议本身与传输方式解耦,当前支持两种主要的传输机制:标准输入/输出(stdio)和HTTP Server-Sent Events(SSE)。
</p>
<h3 class="ai-section-subtitle">
<i class="fas fa-terminal"></i>
5.1 标准输入/输出(stdio)
</h3>
<p style="margin-bottom: 1rem;">
stdio是最简单的传输方式,适用于本地进程间通信。Server作为子进程启动,通过stdin/stdout交换JSON消息。这种方式无需网络配置,安全性由操作系统进程隔离保证。
</p>
<div class="concept-box">
<h4><i class="fas fa-check-circle"></i> stdio适用场景</h4>
<ul>
<li>本地工具集成(文件系统、Git、数据库等)</li>
<li>CLI工具封装为MCP Server</li>
<li>开发和测试环境</li>
<li>单用户场景</li>
</ul>
</div>
<span class="code-label">Python - stdio传输</span>
<pre><code class="language-python">import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server
server = Server("local-tools")
@server.tool()
async def read_file(path: str) -> str:
"""读取本地文件"""
with open(path, 'r') as f:
return f.read()
async def main():
# 启动stdio传输
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
server.create_initialization_options()
)
if __name__ == "__main__":
asyncio.run(main())
</code></pre>
<h3 class="ai-section-subtitle">
<i class="fas fa-globe"></i>
5.2 HTTP SSE(Server-Sent Events)
</h3>
<p style="margin-bottom: 1rem;">
SSE传输适用于远程Server部署场景。Server作为HTTP服务运行,Client通过POST请求发送消息,Server通过SSE流返回响应和通知。这种方式支持多Client并发连接,适合生产环境部署。
</p>
<div class="concept-box">
<h4><i class="fas fa-server"></i> SSE传输特点</h4>
<ul>
<li><strong>HTTP兼容</strong>:使用标准HTTP,便于通过负载均衡器和代理</li>
<li><strong>流式响应</strong>:通过SSE实现服务端到客户端的消息推送</li>
<li><strong>多客户端支持</strong>:一个Server可同时服务多个Client</li>
<li><strong>远程部署</strong>:Server可以部署在云端,Client通过网络访问</li>
</ul>
</div>
<span class="code-label">Python - SSE传输</span>
<pre><code class="language-python">import uvicorn
from mcp.server import Server
from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.routing import Route, Mount
server = Server("remote-server")
@server.resource("config://app")
async def get_config() -> str:
"""获取应用配置"""
return json.dumps({"version": "1.0", "debug": False})
# SSE传输实例
sse = SseServerTransport("/messages/")
async def handle_sse(request):
"""处理SSE连接"""
async with sse.connect_sse(
request.scope, request.receive, request._send
) as streams:
await server.run(
streams[0], streams[1],
server.create_initialization_options()
)
# 创建Starlette应用
app = Starlette(
routes=[
Route("/sse", endpoint=handle_sse),
Mount("/messages/", app=sse.handle_post_message),
]
)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
</code></pre>
<table class="comparison-table">
<thead>
<tr>
<th>传输方式</th>
<th>适用场景</th>
<th>连接方式</th>
<th>部署方式</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>stdio</strong></td>
<td>本地集成、CLI工具</td>
<td>进程stdin/stdout</td>
<td>作为子进程启动</td>
</tr>
<tr>
<td><strong>SSE</strong></td>
<td>远程服务、生产环境</td>
<td>HTTP POST + SSE</td>
<td>独立HTTP服务</td>
</tr>
</tbody>
</table>
</div>
<!-- ==================== 第六节:服务端开发 ==================== -->
<div class="concept-section" id="sec6">
<h2 class="ai-section-title">
<i class="fas fa-code"></i>
六、服务端开发实战
</h2>
<p style="margin-bottom: 1rem;">
本节通过完整示例展示如何开发一个实用的MCP Server。我们将构建一个文件系统MCP Server,它能够读写文件、列出目录并执行基本的文件操作。
</p>
<h3 class="ai-section-subtitle">
<i class="fab fa-python"></i>
6.1 Python实现
</h3>
<p style="margin-bottom: 1rem;">
以下是使用Python MCP SDK实现的文件系统Server完整代码:
</p>
<span class="code-label">Python - 文件系统MCP Server</span>
<pre><code class="language-python">"""
文件系统MCP Server
提供文件读写、目录列表等功能
"""
import os
import json
import asyncio
from pathlib import Path
from typing import Optional
from mcp.server import Server
from mcp.types import (
Tool, Resource, ResourceContents,
ToolResult, Prompt, PromptMessage, Role
)
from pydantic import BaseModel
# 创建Server实例
server = Server("filesystem-server")
# 工具参数模型
class ReadFileArgs(BaseModel):
path: str
class WriteFileArgs(BaseModel):
path: str
content: str
class ListDirArgs(BaseModel):
path: str = "."