Pass context from request endpoint to message handler

未关闭
#236 2 条评论 8 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
32/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
停滞
技术栈
csharp
领域
api, backend

调研方向

从 McpEndpointRouteBuilderExtensions 和 McpServer 开始,跟踪 OnMessageReceivedAsync 以及 issue 中所示的 RequestHandlers.Set 调用。确定如何让不透明的调用方上下文与 IJsonRpcMessage 一起传递到工具处理程序或 MCP 请求上下文中。在长时间运行的工具调用期间可以使用端点提供的上下文,且无需存储或传递已完成的 HttpContext,即表示完成。

由索引模型根据 Issue 内容生成。

描述

enhancement needs confirmation

Is your feature request related to a problem? Please describe.
When the server is started, it runs in a scope that has the current HttpContext. In that context there might be useful headers that are relevant for that session. But when you need to call a tool the message endpoint might have a different HttpContext and different headers.
For example you might want to use the bearer token from the message endpoint to call a tool or to get the list of tools. In the case of SSE transport, you will need to transfer this token to the tool handler.

Describe the solution you'd like
Be able to build an object (could be opaque) on the message endpoint (can contain anything you want, you can include headers or other info) and pass that object alongside with the IJsonRpcMessage to the tool hander. Maybe make it available on the mcp request context.

Example call:

McpEndpointRouteBuilderExtensions:

await transport.OnMessageReceivedAsync(message, callerContext, context.RequestAborted);

McpServer:

RequestHandlers.Set(
    RequestMethods.ToolsCall,
    (request, callerContext, cancellationToken) => callToolHandler(new(this, request, callerContext), cancellationToken),
    McpJsonUtilities.JsonContext.Default.CallToolRequestParams,
    McpJsonUtilities.JsonContext.Default.CallToolResponse);

This could be extended to other requests as well.

Describe alternatives you've considered
Storing the context in memory introduces additional overhead since it has to be cleaned up and introduces unneeded complexity.
Storing the context in a cache is not ok because we might want to pass sensitive information.
Passing the http context directly is not ok because the post /message request could be finished by the time the tool call is actually processed.

Additional context
In this case we have tool calls with long timeout, they might take a long time to complete, in the order of minutes at least.

主要语言
C#
星标
4.5k
派生
814
平均合并
9 天 19 小时
30 天内合并 PR
4

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

modelcontextprotocol/csharp-sdk 的其他 Issue

查看 modelcontextprotocol/csharp-sdk 的全部 Issue

相似的 Issue

更多 C# Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。