modelcontextprotocol / modelcontextprotocol/python-sdk
How can I manage resource across multiple tool calls during one session?
未關閉
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 24.3k
- 分支
- 4k
- 平均合併
- 1 天 1 小時
- 30 天內合併 PR
- 31
描述
Description
I was messing around multiple agents running in parallel, and suffered from some kind of race condition. I had to write a lock for them.
It looks like each agent has their own session, but I don't have any idea to handle how they create and terminate.
The code can be like below, assuming it is a streamable-http app:
import asyncio
import mcp
from mcp.server.fastmthemcp import Context
import mcp.events # some mcp protocol events, maybe session creation or termination.
mcp_server = mcp.server.FastMCP("demo-locking")
lock = None
async def acquire_lock(ctx: Context):
# assume ctx.session.session_id = mcp-session-id acquired from headers, however not defined in this field.
while lock is not None and lock != ctx.session.session_id:
await asyncio.sleep(1)
ctx.info("Waiting for the lock")
lock = ctx.session.session_id
@mcp_server.tool()
async def tool1(ctx: Context):
await acquire_lock(ctx)
# ... do tool things
@mcp_server.tool()
async def tool2(ctx: Context):
await acquire_lock(ctx)
# ... do tool things
async def release_lock(ctx: Context):
if lock == ctx.session.session_id:
lock = None
mcp_server.add_handler(mcp.events.SESSION_TERMINATE, release_lock) # should be something like this to register a session cleanup.
app = mcp_server.streamable_http_app()
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
References
No response
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
先閱讀 streamable_http_app() 進入點以及範例中的 Context/session 參照,然後檢查 add_handler() 和 SESSION_TERMINATE 目前是如何定義的。該 issue 未指出現有的檔案或測試。若要視為完成,就需要決定並記錄一種協調工具呼叫之間資源以及處理工作階段清理的方法。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend-api-design
- Issue 類型
- 功能
- 難度
- 5/5
- 預估耗時
- 一週以上
- 活躍度
- 活躍
- 描述清晰度
- 需要釐清
- 新手友好度
- 35/100