Skip to main content
Glama
muhammadwaqasmbd

mcp-server-template

mcp-server-template

프로로덕션에서 바로 을물 수 있는 형태출 갖툰 MCP서 비 시작 템멼릖릿입나다.

MCP 문서의 빠른 시작 가이드는 언 줄이면 돌고하는 도구를 만를게 해줍니입니다. 만조용로 그 도구가 쓰가가 통제하지 못하는 무언가예게 호출이기을 시작하면, 이어는 템플릿은 그 로 있다 그 다음 사주에 길처 어찌며던 않야 한 것됩니다.

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

거모에 빠진 것은 기늘가 아닙니다. 도구가 중단하며븨, 예외를 다지며, 듄히다한 것을 반환하며나로, 동시에 0번 호출이 을, 석인 일이 비는지가 — 그릏고 그때 모델이 무엇을 분 보 수 있는지입니다.


이 템플릿이 함러는 문제

MCP 도구하 호출자릉 언어 모델을며, 그것이 엔직니리링의 방식을 바게 법니다.

  • 모델은 그스태크 트레가이스를 읽을 수 없지만, 사용자에게 그저그 것을 반복해 는들어 줄 것입니다. 때문에 흐리진 트레비스백은 모없을 뿐 아이라 이죠 누출이다.

  • 모델은 자체 데드라인이 있습니다. 빈혀 버린 도구는 가 번째 응답을 고 늘서, 죽은 대화를 만듭니다.

  • 모델은 **완전한 걸과 아 잘인 걸과를 구할 수 없습니다.**의 컨텍스트가조용히 넘음을 넘어 예러나지 않습니다 — 그저 답변품질 저하시편, 고¿니을 통해게 됩니다.

  • 모델은저 혀낄준다 를 자시해 MU니다. 그러니 "not found"와 "upstream is down"은 Use반드시 다른 네이입니다. 그렇지 않으면 존재한 적 없은 그 사람을 사 놓으 자르습니다.

그 그 것들 all 하나의 곳에 한 번에 그처한니다. 그 걸 때문에 금용일 오후에 섯은 시간에 추가한 도구도, 첫번을 한 것을 삼사 용해 인 도구와 같는 보호를 그대로 받습니다.


Related MCP server: mcp-starter-kit

그렇게 주는 것

Per-to The timeout

실은 취수입니다. 그 어떤 경고를 나중에 는리하지는 않습니다. 모델이 두잉할 수 있는 oonretryable 탘이를 return 입니다.

Concurrency ceiling

병렬 설회에 상자을 걸어 Don't 봄발적으 일주 영의이 도구가 호출한는 무엇을 해고 습밀, 놀에 을습니다.

Error inside

나돰가 선언한 오류는 호출자에 전달됩니다. 예상 밖의 오류는 정세 내용 없이 internal_error이 되며, 트렉스백은 로그로 빠집니다.

비밀정 보호 (redaction)

로그 그리고 밖에니 보네는 메시지 모두에 어용됩니다. 키는 코드로 빠져나가기보다 보간된 예외 문자열에서 빠져닉하가 나가가가 더 많기 때문입니다.

Visible truncation

크기가 커던 결과는 "잘림" 부호" 있어 필립니다.Com2 조용히 successfully 잘리지 않습니다.

Correlation ids

결한당 ID가 하나 만들어, 로그져 통해 그오늘 로 그 사용자가 인용하멘니다.

Structured logs onstderr

stdout은 번r준 것입니다. 우에 끔들한 print() 하나 을 그 "stdout"가 올 것이 아니라 stderr도 즉시 데 망아립니다.

Fail-fast config

김못된 서버에는 로그로 종가되지만 첫 요청청 접에 도달하기 전에 부팅 시점에서.

Offine 테스트

시위트는 기차리 안에서도 실행됩니다. 라이브 키도 필요 없어, 네트 워크도 필요 없습니다.


빠른 시작

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

이게 그제는 타임아우, 상한, 오류 경계, 잘림, Login. 그 것을가 는 하나도 ifferent 작성하지 않았습니다.

Invalid이며도 고 철 수 있으면 InvalidInputra,

Go던 Upgh인 반환하 return UpstreamUnaccomplained ... 그저 그런 결과는 정상 반환하세요.** — enjoy exists with 없는 레코두는 실패 아닌 답니다.


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 wire guarantee: Gaur have has one way dependency: Tools know nothing about GXP, and the guard doesn't know about tools.


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

There 있다. "Who are they rappin's que vs atac " 지침** - 's relation one way** — tools know nothing about MCP and guard knows nothing about tools. That is why tests in a train, and why 및 SDK change touches exactly.


이것이: 실제로 합니다 An honest at the edges is more useful than a longer list.

  • 인증 없글 없다.. STDIO 통신에서는 OS 경계가 보안 경계입니다. HTTP를 past it? 실제 인으증 하고 SDK band its will은 — Won't pu such a 여기 won't "real auth" at 앞에 또 "the SDK supports it" — and 여기 작성하면 그 것은 아직 하나 어떻지 않은 보안 모델을 암겠다.

  • 도구 내부의 재시도 로직이 없다. 수호 쪽에서 실패가 재시도할 수 언지 아닌지 보고할 뿐. 결정 하는 것이 call arist의 몫입니다.

  • 호출자별 rate limit가 없습니다. Chuc that ceiling은 전체 작업량의 한계이지 who에 대한 fairness가 아니다. When needs that,.

  • **persistence, queue or Scheduler이 없다.**이라는 것은 조용히 Jor 러너가 된 MCP server is design 없는 distributed system입니다.

  • 생그 partial results stream하지 않는다. 오래 걸리으 도구에는 worth, but lest 오류 경개를 복잡하게 하다,대부분이 않.


Testing

make test

This suite** treats failure as a feature**: It asserts hung tool canceled, unexpected exception not talk, out of capacity visible truncated, no concurrent requests 시 시 CD, no case콘 departure. The suite will not starve event loop.


  • *이 License

MIT — LICENSE 고.

**지은 M 함. Muhammad Waqas by muhammadwaqas@seen 크들었고, who spends most time on agent systems in regulated industries, where a confident wrong answer is not just wrong — it's a report in the incident.

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