modelcontextprotocol / modelcontextprotocol/python-sdk

How can I manage resource across multiple tool calls during one session?

Đang mở
#3,549 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Ngôn ngữ chính
Python
Star
24.3k
Fork
4k
Merge trung bình
1 ngày 1 giờ
Pull request đã merge (30 ngày)
31

Mô tả

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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu bằng cách đọc entry point streamable_http_app() và các tham chiếu đến Context/session trong ví dụ, sau đó kiểm tra cách add_handler() và SESSION_TERMINATE hiện được định nghĩa. Issue không xác định các tệp hoặc bài kiểm thử hiện có. Để được xem là hoàn tất, cần quyết định và ghi lại một cách tiếp cận để điều phối tài nguyên giữa các lần gọi công cụ và xử lý việc dọn dẹp session.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
backend-api-design
Loại issue
Tính năng
Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức độ hoạt động
Sôi nổi
Độ rõ ràng
Cần làm rõ
Mức phù hợp với người mới
35/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.