mcp-longjobs
mcp-longjobs
MCP向けの永続的で再開可能な操作 — タイムアウト、切断、クライアントの再起動をものともしない長時間実行タスクと大容量ファイル。あらゆるクライアントで、今日から。
問題
実際の作業を行うMCPサーバーを必ず壊す3つの問題があります:
長時間実行されるツール呼び出しがタイムアウトする。 クライアントは呼び出しごとのタイムアウト(多くの場合10〜60秒)を課します。クロール、ビルド、バッチジョブが失敗すると、モデルの「リトライ」は操作全体を最初からやり直します。
失敗は修復できない。 失敗した呼び出しは自由形式のエラーを返すため、モデルは推測するしかありません:盲目的にリトライするか、諦めるか。1つのパラメータを修正して再開することはできません。
大容量ファイルには転送手段がない。 バイナリコンテンツは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サポートは不要):
crawl-siteはtaskIdとdurable_task_getをポーリングする指示を添えて即座に返ります — もうタイムアウトはありません。ポーリングするとライブの進捗が表示されます:
{ "status": "working", "progress": { "message": "Crawled /pricing", "fraction": 0.4 } }。実行途中の質問はタスクを
input_requiredとして一時停止します。モデルはdurable_task_respondで回答し、タスクは中断した場所から続行します。クライアントがクラッシュ?新しいセッション? 同じ
taskIdでのdurable_task_getは引き続き機能します — 状態は接続ではなくストアに保存されているからです。durable_task_cancelは次のチェックポイントで協調的に処理を中断します。
失敗はプロトコルエラーではなくデータです — モデルが1往復で修復できる構造化エンベロープ:
{
"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 | 用途 |
|
|
|
|
| セッションモデル、プラグ可能なストア(メモリ、JSONファイル)、構造化エラーエンベロープ |
設計ノート
バイト列はモデルを経由しない。 モデルが見るのはメタデータだけです:ハンドル、サイズ、sha256、進捗。ツール呼び出しによるチャンクは小〜中規模のペイロード向けで、大容量ファイルは帯域外で転送し(TUSエンドポイントを計画中)、モデルは整合性を検証します。
モデルは運び屋ではなく監督者です。 ファサードのツール結果には指示が含まれています(「このIDで
durable_task_getを呼び出せ」「オフセットNから再開せよ」)。そのため、能力のあるモデルならホスト側のサポートを一切必要とせずにプロトコルを操作できます。失敗は修復可能なデータです。 すべての失敗には
code、retryable、recoveryHint、partial.cursorが含まれます — 何が問題だったか、リトライが有効かどうか、代わりに何をすべきか、そして何がすでに成功したか。ライフサイクルの語彙は仕様に一致しています。
working / input_required / completed / failed / cancelledを使用するため、ネイティブアダプタは破壊的変更なしに後から組み込めます。
ステータス
コンポーネント | ステータス |
Tasksフォールバックファサード(進捗 / 入力 / キャンセル) | ✅ 実装済み |
永続セッションストア(メモリ、JSONファイル) | ✅ 実装済み |
再開とチェックサム対応のチャンク分割ファイル転送 | ✅ 実装済み |
ネイティブext-tasksアダプタ( | 🔜 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"]
}
}
}そして、こう依頼します:「EVバッテリーに関する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を開いてください。
ライセンス
Available Tools
9 toolsdurable_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
Scored across 9 tools
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.
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.
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.
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
Related MCP Connectors
MCP server for the FFmpeg Micro video transcoding API — create, monitor, download transcodes.
Public MCP server for discovering open jobs. Search, filter, and get application links.
Hosted MCP server for task-first delegation to remote workstations and workers.
QuLab MCP remote server (Streamable HTTP) for computational science and lab tools.
Related MCP Servers
- AlicenseAqualityCmaintenanceAsync MCP server for running long-running AI tasks with real-time progress monitoring, enabling users to start, monitor, and manage complex AI workflows across multiple models.623 npm5MIT
- AlicenseNot gradedqualityDmaintenanceA 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.7MIT
- AlicenseAqualityBmaintenanceA fire-and-poll MCP server that lets Claude Code run long background jobs without hitting tool-call timeouts.3MIT
- FlicenseNot gradedqualityBmaintenanceRemote MCP server that launches user-supplied scripts inside disposable Docker containers, returning task IDs for async tracking and bounded output tails.-