modelcontextprotocol / modelcontextprotocol/typescript-sdk

Ability to pass custom context to tool handlers

Open
#956 4 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement needs decision P3 v2
Dominant language
TypeScript
Stars
13.4k
Forks
2.2k
Avg merge
3d 15h
Merged PRs (30d)
4

Description

Is your feature request related to a problem? Please describe.

It would be helpful if it were possible to pass arbitrary context to all tools containing information that was derived from the original request.

For my use case, I need to run an additional check to get the current role for a user within my application, but I imagine there would also be other use cases that would be best served by a generic mechanism.

Describe the solution you'd like

Frameworks like GraphQL and TRPC support creating a context object per-request, which is then passed to all methods. A similar implementation for McpServer could look like:

const mcpServer = new McpServer(
  { name: "my-server", version: "1.0.0" },
  {
    async getContext({ req, res }) {
      const role = await getUserRole(req.auth);
      return { role };
    },
  }
);

mcpServer.registerTool("get_info", {}, (input, { ctx }) => {
  if (ctx.role !== "admin") {
    throw new Error("Unauthorized");
  }
  return await getInfo(input);
});

Describe alternatives you've considered
https://github.com/modelcontextprotocol/typescript-sdk/pull/166 added support for accessing AuthInfo from a tool call, however this is limited to what is returned from the bearer token middleware.

Additional context
Add any other context or screenshots about the feature request here.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the McpServer constructor and registerTool handler shape shown in the issue, then review PR 166 and its AuthInfo support. Trace how a request reaches tool handlers and determine the context lifecycle and API boundaries. Done means arbitrary per-request context is available to all registered tools without replacing the existing AuthInfo access.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.