




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
浅谈模型上下文协定MCP应用开发
2025/5/23Aganda•
Why
MCP?•MCP
Server•
Remote
MCPServer•MCPClient•
Roadmap前情提要:LLM-basedAgent一个使用
LLM大模型的AI元件:
它可以根据目标指令,决定步骤、不断呼叫工具
,直到完成任务•
LLM
就像一位被关在房间里的天才•
无法主动学习或操作世界,也没办法存取实时信息或使用计算机•
需要透过工具,由外部系统帮它执行,或是存取长期记忆•
LLM
会输出一段
“工具执行指令”
,由外部系统执行后把结果送回来,让
它不断决定下一步,直到完成任务AgentisLLMusingtoolsina
loopAgentisLLMusingtoolsina
loopinstructions=
"目标任务描述"tools
=
[工具1,
工具2,
工具3....]messages
=
[]#
记录目前messages
状态whileTrue
:response=model.run(instructions,tools,
messages)#
呼叫LLM
大模型,请问下一步if
response.tool_calls:tool__result=tools.run(response.tool_calls)#
执行工具messages.append(tool__result)#更新狀態else
:print(response.final_answer)#不需要執行工具,回傳最後答案break可参考我之前的浅谈LLM-based
AI
Agents
应用开发分享https://ihower.tw/blog/archives/12586Rawintelligence≠Intelligentsoftwaresystems•
大模型的「原始智力」不等于「智慧软件系统」•
大模型LLM
的「智力」只是基石,要把它转化成真正有效的智慧系统,还需要两个关键
:•
工具整合:
让模型能实际操作、查资料、记忆与回应•
正确上下文(context):依照任务动态提供模型需要知道的信息•
这就是所谓的Context
Engineering,动态处理「LLM在当前任务中所需要的所有信息和工具」Model
ContextProtocol模型如何取得Context
的标准化协议
包括Tools、Resources和
Prompts•
Clientapp
包括:•
本机Claude
DesktopApp、ChatWise、Cursor、Windsurf
Editor等等GUI
应用和
编辑器•
云端ClaudeWeb、Dify
等等服务•
你自行开发的Agent程序•
More:https://modelcontextprotocol.io/clients•
搭配安装不同MCPservers
扩充•
一组MCP
server
就包含很多functions工具,是以场景和使用案例为中心,而非只安装一个function工具•
例如安装Slack
MCPserver,就会一次安装八个
functions
在你的client
app
上:常见使用场景:让
App能够更方便安装第三方的工具扩充slack_list_channels,slack_post_message,slack_reply_to_thread,slack_add_reaction,
slack_get_channel_history,slack_get_thread_replies,slack_get_users,slack_get_user_profileBeforeMCP•
针对每个外部应用的每一个API•
需要撰写functionschema
和实作让Agent可以使用•
绿色属于App
的开发责任,蓝色是工具厂商AfterMCP(启动时)•
MCPClient在app
启动时,透过
MCP
标准操作
list_tools()去问MCPServers
获得functionschema•
将functionschema放入Agent定义AfterMCP(执行时)•
回LLM根据function
schema
挑选工具•
透过MCPclient标准操作call_tool(function_name)
来执行工具•
绿色属于App
的开发责任,蓝色是工具厂商•
MCPServer变成是工具厂商的责任,包括提供
function
schema
和实作•
盘
对AIapp
开发者来说:衔接任何MCPserver
工具超简单•
对工具厂商来说:建构MCPserver
一次,所有
MCPclient客户都可以使用•
对AIapp
的用户来说:app具有扩充能力
,可以安装任意
MCPservers•
对企业来说:清楚区隔负责“Agent”
的team和负责
“Tool”
的team,可以分工协作MCP标准化的好处MCPecosystem
发展迅速•
AI应用从
IDEs
到Agents•
外部和企业内部陆续采用•
ofOpenSource
社群活跃•
工具厂商积极支援进一步细看MCPserver提供哪些context•
提供了•
Tools:提供functions
函式工具给模型•
Resources:
提供资料给client
app•
Prompts
提供提⽰词样板给
client
app
的用户•
不过实际上只有Tools最有用
,另两个还好,主要要看
ClientApp
如何使用•
不同Client
App
使用
Tool
的方式很一致,都是让LLM
搭配function
calling
去使用•
但是Resources
跟
Prompts
就不一定了,更依赖于各Client
App
的实作方式,有些可能完全忽略•
提供工具function
的schema和实作•
Tools是设计给LLM用的,实务上就是用
function
calling
来运作•
让模型根据function
schema
挑选要呼叫哪一个function•
这里code
范例使用
官方
Python
SDK:•frommcp.server.fastmcp
import
FastMCPmcp=
FastMCP("Demo")@mcp.tool()defgenerate__random_integer(a
:
int,
b
:
int)->int
:"""产生介于a
和b
之间的随机整数"""import
randomreturn
random.randint(a,b)MCPserver提供Tool能力Claude
app使用范例•
提供资料给
Client
App
from
mcp.server.fastmcp
import
FastMCP•
可以回传任意资料:string,JSON,binary都可以(mime_type)
mcp
=
FastMCP("Demo")•
就像
HTTP
server
的
GET
request
,让
app
向
server
索取资料
@mcp.resource
("config://app")
defget_config()
->
str
:•
Resources是设计给app用的,但要怎么用
,全看
app设计
"""Staticconfiguration
data"""return"This
isApp
configuration"•
例如在Claude
Desktopapp里面
,就是一个选单用用户选了加到
prompt
里面•
也可以让模型决定是否加入context,
看app
怎么设计•
?
那为什么不直接用
Tool
来提供资料?•
Tool是直接提供给模型,而这个Resources
是提供给ClientApp
使用的,
用途和整合方式不同•
MCP
的精神不只是提供模型Context,而是设计一个给整个ClientApp应用的标准协议MCPserver提供Resources•
提供预先设计好的高质量prompttemplate给clientapp,让
用户可以挑选来用•
例如复杂任务或高质量提问场景,例如资料分析、摘要生成等•
如何让用户操作?全看
Client
app
如何设计frommcp.server.fastmcp
import
FastMCPmcp=
FastMCP("Demo")@mcp.prompt()def
review
code(code
:
str)->
str
:returnf"Please
review
this
code:\n\n{code}"•
例如在ClaudeApp是用下拉选单,然后会跳出一个小表单让你填参数•
例如在zed
IDE
中,可在对话中设计快捷键//来选templateMCPserver提供PromptsClaude
app使用范例用户挑选resource
跟prompt
templateClaude
app使用范例然后就加入prompt
输入里面•
本机MCPserver,采用
①
stdio
标准输入输出•
目前绝大部分的MCPservers范例都是用
stdio
实作的•
远端
MCP
server
则是•
②HTTP+SSE(Server
Sent
Events)
协议版本2024-11-05•
③Streamable
HTTP协议版本2025-03-26(这新出的取代旧的SSE)•
讯息本身使用
JSON-RPC定义•MCPTransports实作MCPclient和server
实际是如何传讯息的?
目前有三种实作①本机:标准IO(stdio)•
在App启动时,会依据MCPserver
设定(例如
ClaudeDesktop
App
的claude_desktop_config.json)启动对应的
MCPserver•
MCPserver是透过child
process
启动,并使用
标准输
入输出(stdio)来与主程序沟通•
stdio是一种简单的资料通道,让parentprocess
和
child
process
透过:•
stdin(标准输入)
和
stdout
(标准输出)来双向交换资料,是目前MCPServer最常见的做法•
但这种方式有好有坏:需要本机环境可以正确执行
MCPserver程序,常见是由JavaScript或
Python撰写。如果这没问题,那跑起来很容易,也可以用本机资源(例如开浏览器),也不用担心
HTTPserver占
⽤
Port
。Client跟Server都在本机app
的
process
之内②远端:HTTP+SSEStatefulconnection(持续用
SSE连线)•
MCPServer
是个独立的
HTTPServer
,有两个端点
:•
SSE
Endpoint:Client建立连线后,用于接收Server传来的事件,通常是GET/sse•
HTTP
POST
Endpoint:Client用来送出讯息给Server,通常是
POST/messages③远端:StreamableHTTP可以是Stateless
也可以是Stateful
connection•
不一定需要持续保持SSE
连线,对于后端部署更为容易•
MCPServer是个独立的HTTPServer
,只有一个端点,通常是/mcp•
HTTP
POST:client传送JSON-RPC
讯息•
每笔JSON-RPC请求为一个
POST•
Server
回应可为JSON或直接开启SSEstream(根据客户端HTTP
Header
Accept:application/json
and/or
text/event-stream
判断)•
HTTPGET:由
client主动开启
SSE
stream
接收server
推播•
/modelcontextprotocol/inspector•
单独启动指令npx@modelcontextprotocol/inspector•
以everything
MCP
server
为例•
Command⽤
npx•
Arguments⽤
@modelcontextprotocol/server-everything•
点Connect
就执行这个程序成为child-processMCPInspector协助debugging
MCPserver
的开发者工具(就是一种clientapp)
更多MCPservers推荐•
官方范例https://github.com/modelcontextprotocol/servers/tree/main•
https://github.com/modelcontextprotocol/servers/tree/main/src/everything•
https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem(这个只能你指定的特定目录)•
/modelcontextprotocol/servers/tree/main/src/fetch•
https://github.com/modelcontextprotocol/servers/tree/main/src/slack•
推荐几个MCP
servers:•
https://github.com/wonderwhy-er/DesktopCommanderMCP•
/modelcontextprotocol/servers/tree/main/src/sequentialthinking•
Browser相关•
https://g/microsoft/playwright-mcp•
https://github.com/browserbase/mcp-server-browserbase/tree/main/browserbase(SaaS)•
WebSearch
相关•
https://github.com/tavily-ai/tavily-mcp(SaaS)•
https://github.com/mendableai/firecrawl-mcp-server(SaaS)•
Code
Interpreter•
https://github.com/e2b-dev/mcp-server(SaaS)•
https://ai.pydantic.dev/mcp/run-python/(free)MCPclient开发•
Python
SDK
https://github.com/modelcontextprotocol/python-sdk•
GeminiAPI文件中有串接functioncalling
的范例•
https://ai.google.dev/gemini-api/docs/function-calling?
example=meeting#use_model_context_protocol_mcp•
推荐OpenAIAgentsSDK有内建支援
(2025/3/27)•
https://openai.github.io/openai-agents-python/mcp/•
Demo范例:使用
filesystem
MCPserver管理目录•
https://github.com/ihower/ihower-llm-workshop/blob/main/mcp-client-example1.py•
Demo范例:使用
tavily和filesystem
MCPserver进行搜寻和存成csv
档案•
https://github.com/ihower/ihower-llm-workshop/blob/main/mcp-client-example2.py#Gettoolsfrom
MCP
session
and
convert
to
Gemini
Tool
objectsmcp_tools=await
session.list_tools()tools
=
[types.Tool(function_declarations=[{"name"
:
tool.name,"description"
:tool.description,"parameters"
:
{k
:
vfork,
v
in
tool.inputSchema.items()ifk
not
in
["additionalProperties",
"$schema"]},}])fortool
in
mcp_tools.tools]tools=tools,将工具schema插入function
calling参数%m-%d
')}?"MCPclient使用范例:
启动时查询tools#Promptto
get
theweather
for
the
current
day
in
London.prompt=f"What
istheweather
in
London
in
{datetime.now().strftime(
'%Y-#Initializethe
connection
between
client
and
serverawaitsession.initialize()#Send
requesttothe
model
with
MCP
function
declarationsresponse=client.models.generate_content(model="gemini-2.0-flash",contents=prompt,config=types.GenerateContentConfig(temperature=0,async
def
run():asyncwithstdio_client(server_params)as
(read,write):asyncwithClientSession(read,write)as
session
:),)fork,
v
in
tool.inputSchema.items()ifk
not
in
["additionalProperties",
"$schema"]},}])fortool
in
mcp_tools.tools]#Send
requesttothe
model
with
MCP
function
declarationsresponse=client.models.generate_content(model="gemini-2.0-flash",contents=prompt,config=types.GenerateContentConfig(temperature=0,tools=tools,),)print#Check
for
a
function
callif
response.candidates[0].content.parts[0].function_call:function_call=
response.candidates[0].content.parts[0].function_call(function
call)print(result.content
[0].text)#Callthe
MCP
serverwith
the
predicted
toolresult=await
session.call_tool(function_call.name,arguments=function_call.args
)#Continueas
shown
in
step4
of
"How
Function
Calling
Works"
#and
create
a
user
friendly
responseelse
:print("Nofunction
call
found
inthe
response.")print(response.text)#Startthe
asyncio
event
loop
and
run
the
main
functionasyncio.run(run())MCPclient使用范例:呼叫call_tool
执行_OpenAIAgentsSDKhttps://openai.github.io/openai-agents-python/mcp/传入mcp_servers就会带入toolsagent=Agent(name="Assistant",instructions="Usethetools
to
achieve
the
task",tools=[WebSearchTool(),your_function_1,your_function_2],mcp_servers=[mcp_server_1,mcp_server_2])•
A
MCP
只是protocol,不代表广泛可用•
绝大部分各家的MCPserver
目前仍都是本机stdio版本•
若是用第三方工具应用需要授权,你需要手动获得工具厂商的APIkey
写在设定档里面才会动•
少部分有做remote
MCPserver厂商,
目前也都是只做SSE版本,还不是新的
Streamable
HTTP版本•
ClientApp不一定支援,例如本机的Claude
Desktopapp就不支援•
就算支援,也不一定支援最新的Streamable
HTTP
喔•
ClaudeWeb版有支援安装MCPserverSSE
(需买
Max
Plan),但似乎还不支援streamable
HTTP•
有趣的是Web设定好,会同步让你本机的也可以用
XD•
OpenAI
ResponsesAPI
在2025/5/22都支援了
•
https://platform.openai.com/docs/guides/tools-remote-mcp•
PythonSDK在5/9才做好Streamable
HTTPserver
支援•
https://github.com/modelcontextprotocol/python-sdk/releases/tag/v1.8.0•
如果MCPclient不支援远端,但
MCPserver
是远端?•
Cloudflare有出一个本机的proxy
MCPserver可以绕,推荐•
https://www.npmjs.com/package/mcp-remote•
https://developers.cloudflare.com/agents/guides/remote-mcp-server/RemoteMCPServer踩坑经验(2025/5/23)•
ClaudeWeb版支援SSE有OAuth,但似乎不支援Streamable
HTTP•
X其他Client例如ChatWise虽有支援SSE和Streamable
HTTP,但不支援OAuth•
PythonSDK•
Server
端在2025/5/11才做好OAuth•
/modelcontextprotocol/python-sdk/pull/255•
范例/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth•
Client
端5/20才做好https://github.com/modelcontextprotocol/python-sdk/pull/751•
MCP
Inspector0.12有bug
不能跑
OAuth
,记得用最新版•
要降级到0.11才能跑SSE
OAuth•
但Streamable
HTTP
跑OAuth
仍有bug:
不会跳转授权/modelcontextprotocol/inspector/issues/390•
MCP
Inspector0.13(2025/5/22)都修好惹!!!
•
OpenAI
Responses
API
能让帮你传HTTPAuth
header,但不会帮你跑
OAuth流程喔•
j
然后Spec
关于OAuth2规格还在改•/modelcontextprotocol/modelcontextprotocol/pull/338目前Remote的
Auth是一团糟
(2025/5/23)简单的HTTP
header
bearer
方式•
MCP
Inspector
有支援,但Python
SDK
没实作server-side:https://github.com/modelcontextprotocol/python-sdk/issues/431
从Spec2025-03-26
开始支援OAuth2认证:https://modelcontextprotocol.io/specification/2025-03-26/changeloghttps://blog.christianposta.com/the-updated-mcp-oauth-spec-is-a-mess/••MCP的Sampling功能•
MCP
Server
可以请求Client
进行
LLM
inference
推论•
Server
发送sampling/createMessage
请求•
Client
可让使用者审阅/修改prompt
(人类审核机制)•
Client
执行推论,回传回应•
MCP
Server
继续后续工具执行流程•
Why•
外部
MCP
server
若需要用到
LLM
能力
,则
MCP
server
本身就不需要自备
LLM
能力
,可以沿用
Client
的
LLM•
安全隐私:对Client
app
来说,使用的
MCP
server
就不会把资料又传给外部
LLM
服务,而是都用我自家的
LLM•
有趣,但目前没有什么app
和library
实作这个
(2025/05)•
一个实用场景可能是在Agents
as
Tools
架构(下述)复习:多代理人架构之AgentsasTools可将Agent
当作工具来使用
,一样用
functioncallingOpenAIAgentsSDK
有支援这个功能https://openai.github.io/openai-agents-python/tools/
AgentsasTools+MCP组合
Agent
B/C可被包装成MCPServer,安装在
AgentA
上
这其实就是Google
A2A
Protocol
在做的事:让AgentA可以跟Agent
B/C远端沟通,用
MCP就可以办到A2A只是
MCP
的一种使用特例
AgentsasTools+MCP多重组合
Agent
B
同时是:AgentA
的MCP
ServerAgentX/Y
的MCP
Client 再搭配Sampling功能:所有Agents
的LLM推论需求可都交给AgentA
的LLM处理
AgentasMCPserver一个跟Agent
对谈的MCP
Serverfrommcp.server.fastmcp
import
FastMCPfromagents
importAgent,
Runnermcp=
FastMCP(name="ihowerMCPServer")@mcp.tool()asyncdeftalk
to
ihower(query
:
str,previous
response
id
:
str
=
None)
->
int
:"""Talkto
ihower
chatbotArgs:query:Thequery
to
ask
the
ihower
chatbotprevious
response
id:TheIDofthe
last
response.
If
this
is
the
first
query,
do
not
pass
this
parameter.“""if
previous
response
id==
""
:previous
response
id=Noneagent=Agent(name=“Assistant",instructions="""Youareaconversationalagent
representing
"张文钿"Wen-Tien
Chang
(ihower)
.....(ihower生平事略).....请用繁体中文回答使用者的问题""",model="gpt-4.1-mini")result=awaitRunner.run(agent,input=query,
previous
response
id=previous
response
id)return{"output"
:
result.final
output,"previous
response
id"
:
result.last
response
id
}if
name
==
"
main
"
:mcp.run(transport="sse")//如果是不支援
remote
的
client
app
例如//Claude
Desktop
,可以用
cloudflare
的proxy
MCP
server
绕一下,例如
:"mcpServers"
:
{"proxy-ihower"
:
{"command"
:
"npx","args"
:
["mcp-remote",“https://mcp.aihao.tw/sse”]}}然后安装这个remote
MCP
server:到Claude
或
ChatWise
里使用范例
MCP
server:https://mcp.aihao.tw/sse对谈过程:https://claude.ai/share/7ed64d08-0705-4edc-91b7-
c35ce91189ccOpenAIResponsesAPI5/21pm11:30支援remoteMCPserverAnthropicAPI支援MCPconnector2025/5/23am
12:30(13小时之前)•
https://docs.anthropic.com/en/docs/
agents-and-tools/mcp-connector•
安全性风险•
程序执行攻击:大多MCPservers是透过本机stdio执行
,若从不明来源下载安装,可能被执行恶意程序码•
命名攻击:使用与常见工具名称极为相似的MCPserver名称,冒充合法工具以取得信任与执行机会•
MCP
工具中毒:恶意将prompt
Injection
放在tool
description
里面•
更多延伸讨论•
MCP:
Flash
in
the
Pan
or
Future
Standard?https://www.facebook.com/ihower/posts
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 珠海保税区光联通讯技术有限公司光联保开厂房4F5F扩产项目环境影响报告表
- 草船借箭读后感感想作文(15篇)
- 2025年四级公共营养师考试试题(附答案)
- 2025年营养健康教育专业知识考试卷及答案
- 工业废气深度净化技术产业链上下游协同发展报告
- 部门安全级培训课件
- 新质生产力的主要优势解读
- 企业邮箱使用协议
- 2025年固态电池在智能电网建设中的渗透率预测报告
- 工艺染织品制作工上岗考核试卷及答案
- 2025年疫苗上岗证考试题及答案
- 2025中国载人eVTOL行业白皮书
- 2025中国人民抗日战争纪念馆招聘4人考试模拟试题及答案解析
- 2025-2026粤教粤科版(2024)科学三年级上册教学设计(附目录)
- 《建筑基坑工程监测技术标准》(50497-2019)
- 数字经济学导论-全套课件
- 城乡融合发展的做法和经验乡村振兴培训课件
- 最新肛肠科临床诊疗指南
- 供应商分级的管理制度管理办法
- 义务教育《语文》课程标准(2022年版)
- T∕CTWPDA 06-2019 橡胶木指接拼板
评论
0/150
提交评论