[v2] createMcpHandler legacy fallback misses an abort that happens before it subscribes

Abierto Apto para principiantes
#3,136 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@mariano-aguero ya está trabajando en esto.

Desde el 30/10/2026.

  • #3137 de @mariano-aguero — abierto

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
82/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
typescript

Línea de trabajo

Empieza en packages/server/src/server/createMcpHandler.ts, en createLegacyStatelessFallback, alrededor de las líneas citadas 342–360, y compara cómo gestiona las cancelaciones con PerRequestHTTPServerTransport.handleMessage. El issue describe el fallo y una posible solución; se considera terminado cuando una solicitud cancelada antes de la suscripción desmonta el transporte y cancela ctx.mcpReq.signal, igual que una cancelada después.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

v2
What happened?

In the legacy stateless fallback of createMcpHandler, a request whose client aborts before the handler subscribes to request.signal is never seen as aborted. The tool runs with a ctx.mcpReq.signal that never fires, and the transport and server built for that request are only torn down when the tool finishes.

createLegacyStatelessFallback awaits factory() and product.connect(transport), and only then calls request.signal?.addEventListener('abort', teardown, { once: true }). An abort event that already fired is not delivered to a listener added later, and nothing checks request.signal.aborted after subscribing:

https://github.com/modelcontextprotocol/typescript-sdk/blob/39ae8e6192cf43273aaaf2de4169dfa9f7216e28/packages/server/src/server/createMcpHandler.ts#L342-L360

We hit it on a server whose tool waits up to 45 s for a state change and stops early on ctx.mcpReq.signal. A client that dropped the request while auth and the factory were still running left that wait running to its end. On a loaded machine that window was a few hundred ms. Our workaround is to also listen on ctx.http.req.signal in the tool.

What did you expect?

A request aborted before the handler subscribed is handled like one aborted after: teardown runs, the transport closes and ctx.mcpReq.signal aborts. The modern path already does this, since PerRequestHTTPServerTransport.handleMessage checks signal.aborted before dispatching.

A possible fix is to check right after subscribing:

request.signal?.addEventListener('abort', teardown, { once: true });
if (request.signal?.aborted) teardown();
Code to reproduce
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';

const handler = createMcpHandler(() => {
  const server = new McpServer({ name: 'repro', version: '0.0.0' });
  server.registerTool('wait', { description: 'Waits up to 2 s for the request to be aborted' }, async (ctx) => {
    const started = Date.now();
    const aborted = await new Promise((resolve) => {
      if (ctx.mcpReq.signal.aborted) return resolve(true);
      ctx.mcpReq.signal.addEventListener('abort', () => resolve(true), { once: true });
      setTimeout(() => resolve(false), 2_000);
    });
    console.log(`tool saw the abort: ${aborted}, after ${Date.now() - started} ms`);
    return { content: [{ type: 'text', text: 'done' }] };
  });
  return server;
});

async function call(signal) {
  const request = new Request('http://localhost/mcp', {
    method: 'POST',
    headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
    body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'wait', arguments: {} } }),
    signal,
  });
  // Held for the whole exchange, as a server framework holds it.
  await handler.fetch(request).then((res) => res.text(), () => undefined);
  return request;
}

console.log('client aborts 1 s into the call:');
const late = new AbortController();
setTimeout(() => late.abort(), 1_000);
await call(late.signal);

console.log('client aborted before the handler subscribed:');
await call(AbortSignal.abort());

Output with Node 22.11:

client aborts 1 s into the call:
tool saw the abort: true, after 971 ms
client aborted before the handler subscribed:
tool saw the abort: false, after 2001 ms

The script keeps the Request alive until the response is read. Without that, undici can garbage-collect the original request and its signal stops reaching the clone that classifyEntryRequest forwards, so even the first case never sees the abort. That is unrelated to this issue.

SDK version

@modelcontextprotocol/server 2.3.1. The same code is on main at 39ae8e6 (2.4.0 was not tested).

Area

Server

Lenguaje dominante
TypeScript
Estrellas
13.7k
Forks
2.4k
Merge medio
2 d 7 h
PR fusionados (30 d)
26

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de modelcontextprotocol/typescript-sdk

Todos los issues de modelcontextprotocol/typescript-sdk

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.