Skip to content

Ability to pass custom context to tool handlers #956

@jordan-burnett

Description

@jordan-burnett

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
#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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions