Skip to main content
Glama

mcp-longjobs

适用于 MCP 的持久、可恢复操作——能够经受超时、断连和客户端重启的长时任务与大文件。今天,在任何客户端上都能用。

CI npm license

中文文档

问题

有三件事会让每个做实际工作的 MCP 服务器出问题:

  • 长时工具调用会超时。 客户端对每次调用设置超时(通常为 10–60 秒)。一次爬取、一次构建、一个批处理任务失败——而模型的“重试”会从头重启整个操作。

  • 失败无法修复。 一次失败的调用返回的是自由格式的错误,于是模型只能猜测:盲目重试,或者放弃。它无法修正一个参数然后继续。

  • 大文件没有传输方案。 二进制内容要么是 JSON 中的 base64(33% 开销,硬性消息大小上限),要么是没有任何约定的裸 URL——没有分块、没有断点续传、没有完整性校验。

2026-07-28 版 MCP 规范 增加了 Tasks——支持中途输入和持久句柄的异步执行。但目前还没有客户端支持它,而且规范要求服务器对未选择加入的客户端拒绝任务。因此,每个长时运行的服务器都需要一条能在当今客户端上工作的回退路径。这就是本包。

Related MCP server: Simple Streamable HTTP MCP Server

你能得到什么

import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { JsonFileSessionStore, withTasks, withFileTransfer, asToolRegistrar } from "mcp-longjobs";

const mcp = new McpServer({ name: "my-server", version: "1.0.0" });
const registrar = asToolRegistrar(mcp);
const store = new JsonFileSessionStore("./state/sessions.json");

const tasks = withTasks(registrar, { store });

tasks.taskTool("crawl-site", {
  description: "Crawl a site and produce a report (takes minutes)",
  inputSchema: { url: z.string(), maxPages: z.number().default(50) },
}, async (args, ctx) => {
  for (const page of pages) {
    if (ctx.signal.aborted) throw new Error("cancelled");
    await ctx.progress(`Crawled ${page.url}`, done / total);

    if (needsConfirmation(page)) {
      const answer = await ctx.needInput({ prompt: `Include ${page.url}?`, choices: ["yes", "no"] });
      if (answer === "no") continue;
    }
  }
  return { summary, reportPath }; // small result for the model; big artifacts go through file transfer
});

withFileTransfer(registrar, { store, storageDir: "./state/blobs" });

在当今的客户端上,模型会体验到(无需 Tasks 支持):

  1. crawl-site 立即返回一个 taskId 和轮询 durable_task_get 的说明——不再有超时。

  2. 轮询显示实时进度:{ "status": "working", "progress": { "message": "Crawled /pricing", "fraction": 0.4 } }。

  3. 中途提出的问题会将任务暂停为 input_required;模型通过 durable_task_respond 回答,任务会从停止处继续。

  4. 客户端崩溃?新会话? 使用相同的 taskId 调用 durable_task_get 仍然有效——状态保存在存储中,而不是连接中。

  5. durable_task_cancel 会在下一个检查点协作式地中止工作。

失败是数据,而不是协议错误——一个结构化错误封装,模型可以在一次往返中修复:

{
  "status": "failed",
  "error": {
    "code": "offset_mismatch",
    "message": "Expected offset 131072, got 0.",
    "retryable": true,
    "recoveryHint": "Do NOT resend the whole file. Re-send this chunk starting at offset 131072.",
    "partial": { "cursor": 131072 }
  }
}

包(子路径导出)

Import

用途

mcp-longjobs/tasks

withTasks() + durable_task_* 门面:后台执行、进度、中途输入、协作式取消

mcp-longjobs/files

withFileTransfer():分块上传/下载、恢复游标、sha256 校验、路径安全根目录

mcp-longjobs/core

会话模型、可插拔存储(内存、JSON 文件)、结构化错误封装

设计说明

  • 字节永远不会流经模型。 模型只看到元数据:句柄、大小、sha256、进度。通过工具调用传输的分块适用于中小型负载;大文件应带外传输(计划提供 TUS 端点),由模型验证完整性。

  • 模型是导演,而不是信使。 门面工具的结果自带说明(“使用此 id 调用 durable_task_get”、“从偏移量 N 处恢复”),因此任何有能力的模型都可以在零宿主端支持的情况下驱动该协议。

  • 失败是可修复的数据。 每次失败都携带 code、retryable、recoveryHint 和 partial.cursor——哪里出错了、重试是否可行、应该改做什么、以及哪些已经成功。

  • 生命周期词汇与规范一致。 working / input_required / completed / failed / cancelled,因此原生适配器以后可以无缝接入,而不会造成破坏性变更。

状态

组件

状态

Tasks 回退门面(进度 / 输入 / 取消)

✅ 已实现

持久会话存储(内存、JSON 文件)

✅ 已实现

带断点续传和校验和的分块文件传输

✅ 已实现

原生 ext-tasks 适配器(CreateTaskResult / tasks/get)

🔜 跟踪 SDK 的实验性 Tasks API

用于大文件的 TUS 1.0 带外端点

🔜 计划中——参见 mcp#189

Redis / SQLite 存储、Python 移植

🔜 计划中

快速开始

git clone https://github.com/ljppanda/mcp-longjobs
cd mcp-longjobs
npm install && npm run build
node dist/examples/report-generator.js

(一旦发布到 npm,同一个服务器只需一条命令即可运行:npx mcp-longjobs。)

将你的客户端指向它(stdio):

{
  "mcpServers": {
    "report-generator": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-longjobs/dist/examples/report-generator.js"]
    }
  }
}

然后问:“生成一份关于电动汽车电池的报告,包含 3 个部分。” 观察模型启动任务、轮询 durable_task_get 并获取结果。在运行中途杀掉客户端,重新启动,然后询问同一个 taskId——它会恢复。

开发

npm install
npm test         # vitest
npm run build    # tsc -> dist/
npm run example  # build + run the demo server

贡献

欢迎提交 PR——尤其是:存储后端(SQLite/Redis)、原生 ext-tasks 适配器和 TUS 端点。如果是较大的改动,请先开一个 issue。

许可证

MIT

Available Tools

9 tools
durable_task_cancelCancel a durable taskA

Cooperatively cancel a running task. The task stops at its next checkpoint.

Inputs: taskId (required).

durable_task_getGet durable task statusA

Poll a long-running task created by this server. Repeat until status is "completed" or "failed".

Inputs: taskId (required).

durable_task_respondAnswer a durable task's questionA

Deliver input that a paused task (status input_required) asked for.

Inputs: taskId (required), response (required).

file_transfer_commitFinalize an upload sessionA

Verify size and sha256 (when declared), then move the staged file to its destination.

Inputs: handle (required).

file_transfer_openOpen a resumable file transferA

Open a chunked upload or download session. Upload: send chunks with file_transfer_write starting at offset 0, then file_transfer_commit. Download: fetch chunks with file_transfer_read until eof. Sessions survive server restarts — resume at the reported nextOffset.

Inputs: path (required), direction (required), size, sha256.

file_transfer_readRead one chunk from a download sessionA

Fetch a byte range as base64. Repeat with nextOffset until eof; the final response carries the whole-file sha256.

Inputs: handle (required), length, offset.

file_transfer_statusInspect a transfer sessionA

Report direction, status, bytes received so far, and destination — useful after a restart.

Inputs: handle (required).

file_transfer_writeWrite one chunk to an upload sessionA

Append a base64 chunk at the session's expected offset. A wrong offset returns a repairable error with the correct cursor instead of failing the transfer.

Inputs: data (required), handle (required), offset (required).

generate-reportGenerate a market reportA

Simulates a slow job (~2s per section). Demonstrates background execution, progress polling, restart-safe state, and cooperative cancellation.

Inputs: topic (required), sections.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 9 tools

    Disambiguation5/5

    Each tool maps to a distinct action within its domain: durable_task_get/respond/cancel are clearly separate task lifecycle operations, and file_transfer_open/write/read/commit/status cover distinct phases of a transfer. generate-report is the only job-creation tool and does not overlap with the polling or transfer tools.

    Naming Consistency3/5

    Most tools follow a clear prefix_verb snake_case pattern, such as durable_task_get and file_transfer_open, but generate-report breaks this by using a hyphenated verb-noun style. The group prefixes help readability, but the mixed conventions prevent a higher score.

    Tool Count5/5

    Nine tools is well within the ideal range, and each appears to serve a specific necessity for either durable task coordination or chunked file transfer. The count feels focused and purposeful rather than bloated.

    Completeness4/5

    The task lifecycle is well covered with get, respond, and cancel, and the file transfer flow covers open, read/write, commit, and status. Minor gaps exist: there is no explicit file transfer cancellation/abort tool, and task creation is only demonstrated through generate-report rather than a generic create tool.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      A reference implementation demonstrating proper MCP server patterns with HTTP transport, featuring session management, progress notifications, and example tools for testing server functionality. Serves as a clean template for building MCP servers with streamable responses and comprehensive error handling.
      7
      MIT
    • F
      license
      Not graded
      quality
      B
      maintenance
      Remote MCP server that launches user-supplied scripts inside disposable Docker containers, returning task IDs for async tracking and bounded output tails.
      -