




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
淺談模型上下文協(xié)定MCP應用開發(fā)
2025/5/23Aganda?
Why
MCP??MCP
Server?
Remote
MCPServer?MCPClient?
Roadmap前情提要:LLM-basedAgent一個使用
LLM大模型的AI元件:
它可以根據(jù)目標指令,決定步驟、不斷呼叫工具
,直到完成任務?
LLM
就像一位被關(guān)在房間里的天才?
無法主動學習或操作世界,也沒辦法存取實時信息或使用計算機?
需要透過工具,由外部系統(tǒng)幫它執(zhí)行,或是存取長期記憶?
LLM
會輸出一段
“工具執(zhí)行指令”
,由外部系統(tǒng)執(zhí)行后把結(jié)果送回來,讓
它不斷決定下一步,直到完成任務AgentisLLMusingtoolsina
loopAgentisLLMusingtoolsina
loopinstructions=
"目標任務描述"tools
=
[工具1,
工具2,
工具3....]messages
=
[]#
記錄目前messages
狀態(tài)whileTrue
:response=model.run(instructions,tools,
messages)#
呼叫LLM
大模型,請問下一步if
response.tool_calls:tool__result=tools.run(response.tool_calls)#
執(zhí)行工具messages.append(tool__result)#更新狀態(tài)else
:print(response.final_answer)#不需要執(zhí)行工具,回傳最後答案break可參考我之前的淺談LLM-based
AI
Agents
應用開發(fā)分享https://ihower.tw/blog/archives/12586Rawintelligence≠Intelligentsoftwaresystems?
大模型的「原始智力」不等于「智慧軟件系統(tǒng)」?
大模型LLM
的「智力」只是基石,要把它轉(zhuǎn)化成真正有效的智慧系統(tǒng),還需要兩個關(guān)鍵
:?
工具整合:
讓模型能實際操作、查資料、記憶與回應?
正確上下文(context):依照任務動態(tài)提供模型需要知道的信息?
這就是所謂的Context
Engineering,動態(tài)處理「LLM在當前任務中所需要的所有信息和工具」Model
ContextProtocol模型如何取得Context
的標準化協(xié)議
包括Tools、Resources和
Prompts?
Clientapp
包括:?
本機Claude
DesktopApp、ChatWise、Cursor、Windsurf
Editor等等GUI
應用和
編輯器?
云端ClaudeWeb、Dify
等等服務?
你自行開發(fā)的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_pro?leBeforeMCP?
針對每個外部應用的每一個API?
需要撰寫functionschema
和實作讓Agent可以使用?
綠色屬于App
的開發(fā)責任,藍色是工具廠商AfterMCP(啟動時)?
MCPClient在app
啟動時,透過
MCP
標準操作
list_tools()去問MCPServers
獲得functionschema?
將functionschema放入Agent定義AfterMCP(執(zhí)行時)?
回LLM根據(jù)function
schema
挑選工具?
透過MCPclient標準操作call_tool(function_name)
來執(zhí)行工具?
綠色屬于App
的開發(fā)責任,藍色是工具廠商?
MCPServer變成是工具廠商的責任,包括提供
function
schema
和實作?
盤
對AIapp
開發(fā)者來說:銜接任何MCPserver
工具超簡單?
對工具廠商來說:建構(gòu)MCPserver
一次,所有
MCPclient客戶都可以使用?
對AIapp
的用戶來說:app具有擴充能力
,可以安裝任意
MCPservers?
對企業(yè)來說:清楚區(qū)隔負責“Agent”
的team和負責
“Tool”
的team,可以分工協(xié)作MCP標準化的好處MCPecosystem
發(fā)展迅速?
AI應用從
IDEs
到Agents?
外部和企業(yè)內(nèi)部陸續(xù)采用?
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是設(shè)計給LLM用的,實務上就是用
function
calling
來運作?
讓模型根據(jù)function
schema
挑選要呼叫哪一個function?
這里code
范例使用
官方
Python
SDK:?frommcp.server.fastmcp
import
FastMCPmcp=
FastMCP("Demo")@mcp.tool()defgenerate__random_integer(a
:
int,
b
:
int)->int
:"""產(chǎn)生介于a
和b
之間的隨機整數(shù)"""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是設(shè)計給app用的,但要怎么用
,全看
app設(shè)計
"""Staticconfiguration
data"""return"This
isApp
configuration"?
例如在Claude
Desktopapp里面
,就是一個選單用用戶選了加到
prompt
里面?
也可以讓模型決定是否加入context,
看app
怎么設(shè)計?
?
那為什么不直接用
Tool
來提供資料??
Tool是直接提供給模型,而這個Resources
是提供給ClientApp
使用的,
用途和整合方式不同?
MCP
的精神不只是提供模型Context,而是設(shè)計一個給整個ClientApp應用的標準協(xié)議MCPserver提供Resources?
提供預先設(shè)計好的高質(zhì)量prompttemplate給clientapp,讓
用戶可以挑選來用?
例如復雜任務或高質(zhì)量提問場景,例如資料分析、摘要生成等?
如何讓用戶操作?全看
Client
app
如何設(shè)計frommcp.server.fastmcp
import
FastMCPmcp=
FastMCP("Demo")@mcp.prompt()def
review
code(code
:
str)->
str
:returnf"Please
review
this
code:\n\n{code}"?
例如在ClaudeApp是用下拉選單,然后會跳出一個小表單讓你填參數(shù)?
例如在zed
IDE
中,可在對話中設(shè)計快捷鍵//來選templateMCPserver提供PromptsClaude
app使用范例用戶挑選resource
跟prompt
templateClaude
app使用范例然后就加入prompt
輸入里面?
本機MCPserver,采用
①
stdio
標準輸入輸出?
目前絕大部分的MCPservers范例都是用
stdio
實作的?
遠端
MCP
server
則是?
②HTTP+SSE(Server
Sent
Events)
協(xié)議版本2024-11-05?
③Streamable
HTTP協(xié)議版本2025-03-26(這新出的取代舊的SSE)?
訊息本身使用
JSON-RPC定義?MCPTransports實作MCPclient和server
實際是如何傳訊息的?
目前有三種實作①本機:標準IO(stdio)?
在App啟動時,會依據(jù)MCPserver
設(shè)定(例如
ClaudeDesktop
App
的claude_desktop_con?g.json)啟動對應的
MCPserver?
MCPserver是透過child
process
啟動,并使用
標準輸
入輸出(stdio)來與主程序溝通?
stdio是一種簡單的資料通道,讓parentprocess
和
child
process
透過:?
stdin(標準輸入)
和
stdout
(標準輸出)來雙向交換資料,是目前MCPServer最常見的做法?
但這種方式有好有壞:需要本機環(huán)境可以正確執(zhí)行
MCPserver程序,常見是由JavaScript或
Python撰寫。如果這沒問題,那跑起來很容易,也可以用本機資源(例如開瀏覽器),也不用擔心
HTTPserver占
?
Port
。Client跟Server都在本機app
的
process
之內(nèi)②遠端:HTTP+SSEStatefulconnection(持續(xù)用
SSE連線)?
MCPServer
是個獨立的
HTTPServer
,有兩個端點
:?
SSE
Endpoint:Client建立連線后,用于接收Server傳來的事件,通常是GET/sse?
HTTP
POST
Endpoint:Client用來送出訊息給Server,通常是
POST/messages③遠端:StreamableHTTP可以是Stateless
也可以是Stateful
connection?
不一定需要持續(xù)保持SSE
連線,對于后端部署更為容易?
MCPServer是個獨立的HTTPServer
,只有一個端點,通常是/mcp?
HTTP
POST:client傳送JSON-RPC
訊息?
每筆JSON-RPC請求為一個
POST?
Server
回應可為JSON或直接開啟SSEstream(根據(jù)客戶端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
就執(zhí)行這個程序成為child-processMCPInspector協(xié)助debugging
MCPserver
的開發(fā)者工具(就是一種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/?lesystem(這個只能你指定的特定目錄)?
/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相關(guān)?
https://g/microsoft/playwright-mcp?
https://github.com/browserbase/mcp-server-browserbase/tree/main/browserbase(SaaS)?
WebSearch
相關(guān)?
https://github.com/tavily-ai/tavily-mcp(SaaS)?
https://github.com/mendableai/?recrawl-mcp-server(SaaS)?
Code
Interpreter?
https://github.com/e2b-dev/mcp-server(SaaS)?
https://ai.pydantic.dev/mcp/run-python/(free)MCPclient開發(fā)?
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有內(nèi)建支援
(2025/3/27)?
https://openai.github.io/openai-agents-python/mcp/?
Demo范例:使用
?lesystem
MCPserver管理目錄?
https://github.com/ihower/ihower-llm-workshop/blob/main/mcp-client-example1.py?
Demo范例:使用
tavily和?lesystem
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參數(shù)%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
執(zhí)行_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版本?
若是用第三方工具應用需要授權(quán),你需要手動獲得工具廠商的APIkey
寫在設(shè)定檔里面才會動?
少部分有做remote
MCPserver廠商,
目前也都是只做SSE版本,還不是新的
Streamable
HTTP版本?
ClientApp不一定支援,例如本機的Claude
Desktopapp就不支援?
就算支援,也不一定支援最新的Streamable
HTTP
喔?
ClaudeWeb版有支援安裝MCPserverSSE
(需買
Max
Plan),但似乎還不支援streamable
HTTP?
有趣的是Web設(shè)定好,會同步讓你本機的也可以用
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
是遠端??
Cloud?are有出一個本機的proxy
MCPserver可以繞,推薦?
https://www.npmjs.com/package/mcp-remote?
https://developers.cloud?are.com/agents/guides/remote-mcp-server/RemoteMCPServer踩坑經(jīng)驗(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:
不會跳轉(zhuǎn)授權(quán)/modelcontextprotocol/inspector/issues/390?
MCP
Inspector0.13(2025/5/22)都修好惹!!!
?
OpenAI
Responses
API
能讓幫你傳HTTPAuth
header,但不會幫你跑
OAuth流程喔?
j
然后Spec
關(guān)于OAuth2規(guī)格還在改?/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/speci?cation/2025-03-26/changeloghttps://blog.christianposta.com/the-updated-mcp-oauth-spec-is-a-mess/??MCP的Sampling功能?
MCP
Server
可以請求Client
進行
LLM
inference
推論?
Server
發(fā)送sampling/createMessage
請求?
Client
可讓使用者審閱/修改prompt
(人類審核機制)?
Client
執(zhí)行推論,回傳回應?
MCP
Server
繼續(xù)后續(xù)工具執(zhí)行流程?
Why?
外部
MCP
server
若需要用到
LLM
能力
,則
MCP
server
本身就不需要自備
LLM
能力
,可以沿用
Client
的
LLM?
安全隱私:對Client
app
來說,使用的
MCP
server
就不會把資料又傳給外部
LLM
服務,而是都用我自家的
LLM?
有趣,但目前沒有什么app
和library
實作這個
(2025/05)?
一個實用場景可能是在Agents
as
Tools
架構(gòu)(下述)復習:多代理人架構(gòu)之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?
安全性風險?
程序執(zhí)行攻擊:大多MCPservers是透過本機stdio執(zhí)行
,若從不明來源下載安裝,可能被執(zhí)行惡意程序碼?
命名攻擊:使用與常見工具名稱極為相似的MCPserver名稱,冒充合法工具以取得信任與執(zhí)行機會?
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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 一元二次函數(shù)、方程和不等式 基礎(chǔ)測試(含解析)-2026屆高三數(shù)學一輪復習
- 原電池新型電源(練)-2023年高考化學一輪復習(新教材新高考)
- 4項目四 自動售檢票系統(tǒng)終端設(shè)備
- 四川省德陽市綿竹中學2024-2025學年高二上學期開學考試地理試卷(含答案)
- 合同談判策略及技巧培訓資料
- 移動醫(yī)療應用程序開發(fā)安全標準
- 2024-2025學年江蘇省無錫第六高級中學高二(下)期中數(shù)學試卷(含答案)
- 2025秋初中數(shù)學九年級上冊人教版教案設(shè)計 22.1.2二次函數(shù)y=ax2的圖象和性質(zhì)(2)-1教案
- 山東省濱州市鄒平市2024-2025學年八年級上學期期末考試物理試題【含答案】
- 三角函數(shù)的概念與誘導公式(復習講義)-2026年高考數(shù)學一輪復習原卷版
- 電商運營知識點
- 監(jiān)理人員組織形式及監(jiān)理人員進場計劃表
- 慢性心功能不全護理個案分析
- DB32∕T 2452-2013 刺參浮筏吊養(yǎng)技術(shù)規(guī)范
- DB37T 5118-2018 市政工程資料管理標準
- 2024年中藥炮制工技能大賽理論考試題庫(含答案)
- 中級安全工程師《安全生產(chǎn)法律法規(guī)》考試(重點)題及答案
- 韶關(guān)學院《馬克思主義基本原理概論》2021-2022學年第一學期期末試卷
- 讀后續(xù)寫 Emily 的成長 課件 -高三英語上學期二輪復習專項
- GB/T 44794-2024家用和類似用途電自動控制器微波傳感功能的技術(shù)要求和評價方法
- 鄉(xiāng)村天然氣管道鋪設(shè)合同
評論
0/150
提交評論