Skip to main content
Glama
muhammadwaqasmbd

mcp-server-template

mcp-server-template

本番運用を想定したMCPサーバーへの出発地点。

MCPドキュメントのクイックスタートを使えば、10行で動くツールが手に入ります。しかし、そのツールが自分の管理下にない何かによって呼ばれるようになったとき、あなたがその後3週間で追加していくことになるのが、このテンプレートです。

@mcp.tool()
def add(a: int, b: int) -> int:
    return a + b          # fine on a laptop

ここに足りないのは機能ではありません。重要なのは、ツールがハングしたとき、例外を投げたとき、想定外の結果を返したとき、一度に40回呼ばれたとき――そして、そのときにモデルに見せてもよいものは何か――です。


このテンプレートが解決する問題

MCPツールの呼び出し元は言語モデルであり、それがエンジニアリングの考え方を変えます。

  • モデルはスタックトレースを読めるないが、それをあったままユーザーにしゃべります。つまり、トレースバックの漏れは無意味なだけでなく、情報の開示でもあることになります。

  • モデルには自分の締め切りがあります。ハングするツールは遅い回答を生むのではなく、その会話を終わらせるのです。

  • モデルは末尾を切り詰めた結果と完全な結果を区別できない。コンテキストに静かにあふれてもエラーにはならず、回答の質が下がる。あなたはそれをまず顧客から知らされることになるでしょう。

  • モデルは、許せば再試行します。だから「見つからない」と「上流が落ちている」は別の回答にしなければなりません。さもなければ、最初から存在しないレコードを狙ってサービスに叩き続けることになります。

これの一つひとつは、一度だけ、一つの場所で処理されます。金曜の午後に追加したツールも、最初の日に注意深く書いたツールと同じ保護を受けられます。


Related MCP server: mcp-starter-kit

得られるもの

ツールごとのタイムアウト

その後に警告があるのではなく、本物のキャンセル。モデルが対処できる retryable エラーを返します

並行上限

並列実行を制限し、バーストがツールの呼び出し先を踏みつけられないようにします

エラー境界

宣言されたエラーは呼び出し元へ到達し、想定外のものは詳細のない internal_error になる。トレースバックはログに残ります

機密情報の伏せ字

ログおよび送信メッセージに適用。鍵はコードを経由するよりも、補間された例外文字列から漏れることが多いためです

見える方式の切り詰め

サイズを超えた結果は、静かにではなく、切ったことがわかる区切り印とともに返します

相関ID

呼び出しごとに1つのIDをログと、ユーザーが後で引用できるエラーの中に入れる

stderr への構造化ログ

stdout はプロトコル専用。はぐれた print() はストリームを壊してしまう

起動時設定検証

おかしな設定は最初のリクエストではなく、サーバーの起動時に止める

オフラインで動くテスト

スイートは列車の中で走る。実際の鍵もネットワークも不要


クイックスタート

git clone https://github.com/muhammadwaqasmbd/mcp-server-template
cd mcp-server-template
make install
make test
make run          # stdio, ready for a desktop MCP client

ネット越しに提供するには次のようにします:

TRANSPORT=streamable-http PORT=8000 python -m mcp_server_template

デスクトップクライアントから使う

{
  "mcpServers": {
    "template": {
      "command": "python",
      "args": ["-m", "mcp_server_template"],
      "cwd": "/absolute/path/to/mcp-server-template"
    }
  }
}

自前のツールを追加する

関数を書くだけです。他のことは他は何もありません。

# src/mcp_server_template/tools/orders.py
from ..errors import InvalidInput, UpstreamUnavailable

async def cancel_order(order_id: str) -> dict:
    """Cancel an order. Returns the order's new state."""
    if not order_id.strip():
        raise InvalidInput("order_id must not be empty")     # model can fix this
    ...
    raise UpstreamUnavailable("order service timed out")     # model may retry

ガードの後ろに登録します:

mcp.tool(name="cancel_order", description="Cancel an order by id.")(
    guard.wrap(orders.cancel_order)
)

これで、タイムアウト、並行制約、エラー境界、切り詰め、ログがすべて手に入ります。それらはあなたが一切書いていません。

モデルが修正できるときは InvalidInput を、再試行が効くかもしれないときは UpstreamUnavailable を投げてください。単に偽という出力は通常通りに返します ― レコードが存在しないのはエラーではなく、それが答えなのです。


アーキテクチャ

server.py      the ONLY module that imports the MCP SDK
   │
   ├── guard.py          timeout · concurrency · error boundary · truncation · timing
   ├── errors.py         what a model is allowed to see, and secret redaction
   ├── observability.py  JSON logs on stderr, correlation ids
   ├── config.py         validated once at boot, immutable thereafter
   └── tools/            plain functions. No protocol knowledge. No decorators

依存の矢印は一方向です:ツールはMCPについて何も知らず、ガードはあなたのツールについて何もしません。だからサーバーなしでテストがミリ秒単位で実行できるしくみまり、SDKの変更がたった一つのファイルにしか触れないのです。


このテンプレートが意図的にやらないこと

境界を正直に語ることは、機能一覧を長くすることよりも価値があります。

  • 認証はしません。 stdio では、OS の境界がそのままセキュリティの境界です。HTTP経由で公開するなら、その前に本物の認証を置いてください。SDK で対応しています。ここに配線してしまえば、あなたがまだ選んでいない前提の元の脅威モデルを暗に想定することになります。

  • ツールの中に再試行ロジックは持ちません。 ガードが失敗が再試行可能かどうかを報告し、再試行の判断は呼び出し元に属する。呼び出し元はそのための文脈と予算を持っています。

  • 発信者ごとのレート制限はしません。 並行上限は総作業量を制限するものであって、呼び出し元IDごとの公平性ではありません。それが要るなら、その前にID要ります。

  • 永続化・キュー・スケジューラは持ちません。 ひっそりジョブランナーになったツールサーバーは、誰も設計していない分散システムです。

  • 結果の分割ストリーミングはしません。 時間のかかるツールには追加する価値がありますが、エラー境界が複雑になるため、また多くのツールは必要としないから、含めていません。


テスト

make test

このテストスイートは意図的に、失敗の姿に焦点を当てていて、カバレッジではありません。ハングしたツールがキャンセルされること、想定外の例外のメッセージが漏れないこと、大きい出力が目に見える形で切り詰められること、並行した10回の呼び出しでも上限が守られること、そしてブロッキングする同期ツールがイベントループを枯渇させないことを検証します。

ライセンス

MIT — LICENSE を参照。

Muhammad Waqas が作っています。彼は規制の厳しい業界のエージェントシステムにほとんどの時間を費やしており、そこでは、過剰な自信を持った誤った回答は、報告すべきインシデントになります。

Available Tools

3 tools
fetch_recordA

Look up a record by key. Returns found=false when absent; that is not an error.

NameRequiredDescriptionDefault
keyYes
simulate_outageNo

Output Schema

NameRequiredDescription

No output parameters

TDQS

A3.6/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden of behavioral disclosure. It does add one valuable behavioral detail: a missing record is reported via 'found=false' and is not treated as an error. This is useful context. However, it does not state that the operation is read-only, nor does it explain the simulate_outage parameter's behavior. The description provides some behavioral clarity but leaves notable gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, direct, and front-loaded with the primary action. It avoids verbosity and includes only the most essential information. The key behavioral note about 'found=false' is presented efficiently. No wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple fetch tool, the description covers the main action and the most important edge case (absent record). However, it omits any explanation of the 'simulate_outage' parameter, which is part of the tool's interface. While an output schema exists and relieves the description of detailing return values, the parameter gap remains. The description is adequate for basic usage but incomplete for full correct invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It implicitly clarifies that 'key' is the lookup identifier, but it offers no additional detail about the parameter's format or acceptable values. The 'simulate_outage' parameter is entirely unexplained—an agent cannot infer its purpose or effect from the description. Given the low coverage, this is a significant shortfall.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the primary action: 'Look up a record by key.' This is a specific verb (look up) with a clear resource (record) and method (by key). It is immediately distinct from sibling tools like summarise_lengths and slow_operation, as those suggest different operations. No ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies when to use the tool (when you need to retrieve a record by its key) but provides no explicit guidance on alternatives or exclusion conditions. It does not mention any context where this tool should be avoided or mention sibling tools. This qualifies as implied usage, which meets the minimum viable threshold.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

slow_operationA

Sleeps, to demonstrate the server's timeout behaviour.

NameRequiredDescriptionDefault
secondsNo

Output Schema

NameRequiredDescription
resultYes

TDQS

A3.7/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description must carry the full burden of behavioral disclosure. It states the core behavior (sleeping) and the intended effect (timeout demonstration), but does not mention the adjustable 'seconds' parameter, what happens after the sleep (return value or error), or any side effects. This is partially transparent but incomplete for a tool with no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, short sentence that front-loads the core action ('Sleeps') and purpose. There is no wasted wording, making it highly efficient and easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple tool with one optional parameter and an output schema, the description is fairly complete. It conveys the tool's purpose and behavior, and the output schema covers return values. However, it could explicitly mention that the sleep duration is configurable via the 'seconds' parameter, which is currently only in the schema. Overall, it is adequate for a demo tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema has one parameter 'seconds' with default 60 and 0% description coverage. The description does not mention this parameter at all, so it fails to connect the sleep duration to the parameter. The parameter name is somewhat self-explanatory, but the description provides no added meaning, leaving the agent to guess how the parameter influences the operation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'Sleeps' and the resource 'server's timeout behaviour', making the tool's purpose unmistakable. It distinguishes itself from siblings 'summarise_lengths' and 'fetch_record' which clearly serve different functions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for demonstrating timeout behaviour, which gives context, but it does not explicitly mention when to use this tool versus alternatives. No exclusions or conditions are provided, leaving the agent to infer that it is for testing timeouts only.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

summarise_lengthsA

Return per-item character counts and a total for a list of strings.

NameRequiredDescriptionDefault
itemsYes

Output Schema

NameRequiredDescription

No output parameters

TDQS

A3.7/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It states the behavior accurately but does not discuss edge cases (e.g., empty list, null elements) or any side effects. For a pure computation tool, this is adequate but minimal disclosure.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single, front-loaded sentence with no wasted words. The core functionality is stated immediately, making it quick for an agent to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool is simple, and an output schema exists, so the description does not need to explain return values. Combined with the clear single parameter and the presence of the output schema, the description is complete for an agent to invoke the tool correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate for the undocumented 'items' parameter. It clarifies that the parameter is a list of strings, which aligns with the schema. However, it does not add details about constraints (e.g., whether null is allowed) or the order of results. The description adds minimal value beyond the schema's type declaration.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool returns per-item character counts and a total for a list of strings, specifying a concrete verb and resource. It does not explicitly differentiate from siblings, but the siblings (fetch_record, slow_operation) are obviously distinct in purpose, so the lack of explicit differentiation isn't a major gap.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The purpose implies when to use it (whenever you need length summaries), but no explicit guidance is given about when not to use it or which alternatives to prefer. Since the alternatives are clearly unrelated, the implied usage is sufficient, though not explicit.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

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

  1. 3 tool updatesv0.1.0
    • First observedfetch_record
    • First observedslow_operation
    • First observedsummarise_lengths

TDQS

A4/5.0

Scored across 3 tools

Disambiguation5/5

Each tool addresses a separate concern: one computes string lengths, one looks up records, and one simulates a timeout. There is no overlap or realistic chance of choosing the wrong tool.

Naming Consistency4/5

Two tools follow a clear snake_case verb_noun pattern (summarise_lengths, fetch_record), but slow_operation reads as adjective_noun. The naming is still readable and predictable overall.

Tool Count5/5

Three tools is a reasonable size for a template server. Each tool exists to demonstrate a distinct capability, so none feel redundant or excessive.

Completeness5/5

As a template, the set covers the demonstrated scenarios: a utility operation, a record lookup with a defined absent-case, and a timeout example. There are no obvious dead ends or missing pieces for that purpose.

Maintenance

ActivityStale
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    C
    maintenance
    A production-ready foundation for building secure, observable MCP servers with built-in authentication, rate limiting, and reference tools like database-query and semantic-search.
    15
    33 npm
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A production-ready, security-first starting point for building Model Context Protocol servers, enforcing safe defaults like dry-run and tenant isolation.
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    An enterprise MCP server scaffold that provides secure, governed access to internal tools through RBAC, audit logging, rate limiting, and prompt-injection boundaries, with a FastAPI control plane and OpenTelemetry observability.
    MIT