MastraM
Mastraโ€ข3mo ago
Nevo David

Can't access auth when calling an agent from MCP

Hello, I am facing a problem happy to get your help! ๐Ÿ™‚
Working with express, I have created the following MCP
export const startMcp = async (app: INestApplication) => {
  const mastraService = app.get(MastraService, { strict: false });
  const organizationService = app.get(OrganizationService, { strict: false });

  const mastra = await mastraService.mastra();
  const agent = mastra.getAgent('postiz');
  const tools = await agent.getTools();

  const server = new MCPServer({
    name: 'Postiz MCP',
    version: '1.0.0',
    tools,
    agents: { postiz: agent },
  });

  app.use(
    '/mcp/:id',
    async (req: Request, res: Response, next: NextFunction) => {
      if (req.method === 'OPTIONS') {
        res.sendStatus(200);
        return;
      }

      // @ts-ignore
      req.auth = await organizationService.getOrgByApiKey(req.params.id);
      // @ts-ignore
      if (!req.auth) {
        throw new HttpException('Invalid url', 400);
      }

      const url = new URL(
        `/mcp/${req.params.id}`,
        process.env.NEXT_PUBLIC_BACKEND_URL
      );
      await server.startHTTP({
        url,
        httpPath: url.pathname,
        options: {
          sessionIdGenerator: () => {
            return randomUUID();
          },
        },
        req,
        res,
      });
    }
  );
};


The req.auth works great in tools, I have been doing something like this:
  // @ts-ignore
  if (options?.extra?.authInfo) {
    // @ts-ignore
    runtimeContext.set('organization', JSON.stringify(options.extra.authInfo));
  }


Here is where I face a problem / bug.
I am using the MCP inspector from Anthropic.
When I execute a tool, it works great with options?.extra?.authInfo.
But if I send a question to my agent "ask_postiz",
I don't get the options?.extra?.authInfo in the tool anymore.
Are there any extra steps I am missing?
Was this page helpful?