MastraM
Mastra3mo ago
Incisiv3

@mastra/ai-sdk chatRoute with middleware context

Hey all, I'm trying to use the chatRoute from the mastra ai-sdk and I have middleware configured that is grabbing some additional metadata my backend sends and adding it to the runtime context. When the agent is called up with a users chat my middleware sees and sets the runtimeContext successfully but the agent runtimeContext is empty.

Is this a known issue or perhaps something I'm missing with this setup? This is from the docs here https://mastra.ai/en/docs/frameworks/agentic-uis/ai-sdk

export const mastra = new Mastra({
  workflows: { fileUploadProcessorWorkflow },
  agents: { fileProcessorAgent, investmentChatAgent },
  storage: getStorage(),

  // Server configuration to bind to all interfaces
  server: {
    port: 4111,
    host: "0.0.0.0",

    middleware: [
      async (c, next) => {
        const runtimeContext = c.get("runtimeContext");
        if (c.req.method === "POST" && c.req.url.includes("/chat")) {
          try {
            const clonedReq = c.req.raw.clone();
            const body = await clonedReq.json();
            if (body?.data) {
              for (const [key, value] of Object.entries(body.data)) {
                runtimeContext.set(key, value);
              }
            }
          } catch {}
        }
        await next();
      },
    ],

    apiRoutes: [
      chatRoute({
        path: "/chat",
        agent: "investmentChatAgent",
      }),
    ],
  }
})
Was this page helpful?