Skip to main content
Glama

mcp-longjobs

MCP向けの永続的で再開可能な操作 — タイムアウト、切断、クライアントの再起動をものともしない長時間実行タスクと大容量ファイル。あらゆるクライアントで、今日から。

CI npm license

中国語ドキュメント

問題

実際の作業を行う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サポートは不要):

  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 は次のチェックポイントで協調的に処理を中断します。

失敗はプロトコルエラーではなくデータです — モデルが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

用途

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"]
    }
  }
}

そして、こう依頼します:「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を開いてください。

ライセンス

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

    ActivityStale
    ResponsivenessOutdated data

    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.
      -