Skip to main content
Glama
muhammadwaqasmbd

mcp-server-template

mcp-server-template

A production-shaped starting point for an MCP server.

The quickstart in the MCP docs gets you a working tool in ten lines. This is what you end up adding over the following three weeks, once that tool is being called by something you do not control.

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

What is missing there is not features. It is what happens when the tool hangs, raises, returns a novel, or gets called forty times at once — and what the model is allowed to see when it does.


The problem this solves

An MCP tool's caller is a language model, which changes the engineering.

  • A model cannot read a stack trace, but it will cheerfully repeat one to your user. So a leaked traceback is both useless and a disclosure.

  • A model has its own deadline. A tool that hangs does not produce a slow answer; it produces a dead conversation.

  • A model cannot tell a truncated result from a complete one. Silently overflowing its context does not raise an error — it degrades the answer, and you find out from a customer.

  • A model will retry if you let it. So "not found" and "upstream is down" have to be different answers, or it will hammer a service over a record that was never there.

Every one of those is handled once, in one place, so that a tool added on a Friday afternoon inherits the same protections as the one written carefully on day one.


Related MCP server: mcp-starter-kit

What you get

Per-tool timeout

Real cancellation, not a warning afterwards. Returns a retryable error the model can act on

Concurrency ceiling

Bounded parallel execution, so a burst cannot stampede whatever your tools call

Error boundary

Declared errors reach the caller; unexpected ones become internal_error with no detail, and the traceback goes to the log

Secret redaction

Applied to logs and outbound messages, because keys escape through interpolated exception strings more often than through code

Visible truncation

Oversized results are cut with a marker, never silently

Correlation ids

One id per call, in the log and in the error the user can quote back to you

Structured logs on stderr

stdout belongs to the protocol — a stray print() corrupts the stream

Fail-fast config

Bad settings stop the server at boot, not on the first request

Offline tests

The suite runs on a train. No live keys, no network


Quickstart

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

Serve it over the network instead:

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

Point a desktop client at it

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

Adding your own tool

Write the function. Nothing else.

# 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

Register it behind the guard:

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

It now has the timeout, the ceiling, the error boundary, the truncation and the logging. You wrote none of that.

Raise InvalidInput when the model can fix it. Raise UpstreamUnavailable when retrying might work. Return normally for outcomes that are simply false — a missing record is an answer, not a failure.


Architecture

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

The dependency arrow points one way: tools know nothing about MCP, and the guard knows nothing about your tools. That is why the tests run in milliseconds without a server, and why an SDK change touches exactly one file.


What this deliberately does not do

Being honest about the edges is more useful than a longer feature list.

  • No authentication. Over stdio the OS boundary is the security boundary. If you expose it over HTTP, put real auth in front — the SDK supports it, and wiring it here would imply a threat model you have not chosen yet.

  • No retry logic inside tools. The guard reports whether a failure is retryable; deciding to retry belongs to the caller, which has the context and the budget.

  • No rate limiting per caller. The concurrency ceiling bounds total work, not per-identity fairness. If you need that, you need identity first.

  • No persistence, queue or scheduler. A tool server that quietly became a job runner is a distributed system nobody designed.

  • No streaming partial results. Worth adding for long-running tools; left out because it complicates the error boundary and most tools do not need it.


Testing

make test

The suite is deliberately about failure, not coverage. It asserts that a hung tool is cancelled, that an unexpected exception cannot leak its message, that oversized output is truncated visibly, that the concurrency ceiling holds under ten simultaneous calls, and that a blocking sync tool does not starve the event loop.


Licence

MIT — see LICENSE.

Built by Muhammad Waqas, who spends most of his time on agent systems in regulated industries, where a confident wrong answer is a reportable incident.

Available Tools

3 tools
fetch_recordA

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

ParametersJSON Schema
NameRequiredDescriptionDefault
keyYes
simulate_outageNo

Output Schema

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

ParametersJSON Schema
NameRequiredDescriptionDefault
secondsNo

Output Schema

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

ParametersJSON Schema
NameRequiredDescriptionDefault
itemsYes

Output Schema

ParametersJSON 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

ActivityMaintained
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
    11 npm
    MIT
  • F
    license
    Not graded
    quality
    B
    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
    C
    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