Skip to main content
BuildReviewed Oct 19, 2026

Building Python Mcp Servers

v1.0.1New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, then copy.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install ffmpeg-skill-building-python-mcp-servers

What this does: Builds robust Python MCP (Model Context Protocol) servers with FastMCP — tool design, error contracts, event-loop-safe blocking work, subprocess/CLI wrapping, single-file vs packaged distribution, global-state-free testing, and prompt-injection awareness. Use when writing an MCP server, exposing a tool or CLI to an LLM client, debugging tool registration/packaging, or testing MCP tools.

Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/ffmpeg-skill-building-python-mcp-servers/SKILL.md

Setup guide →
0Save

Instructions

Building Python MCP Servers

MCP servers expose tools to an LLM client (Claude Desktop, Claude Code, etc.).
The LLM is the caller, so the failure modes differ from a normal library: errors
must be machine-readable, every input is untrusted, and a green test suite often
proves nothing about whether the tools actually work. This skill encodes the
patterns that recur when these go wrong.

Quick Start (FastMCP)

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("my-server")

@mcp.tool()
def read_config(path: str) -> dict:
    """Read a config file. `path` must be absolute."""
    p = Path(path)
    if not p.is_absolute():
        return {"error": "path must be absolute"}
    if not p.exists():
        return {"error": f"no such file: {path}"}
    return {"data": p.read_text()}

if __name__ == "__main__":
    mcp.run()

Error Contract: return, don't raise — and stay consistent

An uncaught exception surfaces to the LLM as an opaque protocol error it can't
reason about. Return a structured result with a predictable shape instead, and
make callers check for it.

  • Pick one error shape and use it everywhere. A dict with an "error" key is
    the common convention. Document that callers must check for it.
  • Batch tools must report skips, not swallow them. The most common
    inconsistency: a single-item tool collects per-item errors, but a sibling
    "do this across a directory" tool silently continues past files that fail to
    load. For automation that is invisible data loss. Every batch tool should
    return both results and a per-item skipped/errors list.
@mcp.tool()
def validate_dir(path: str) -> dict:
    results, skipped = {}, []
    for f in Path(path).glob("*.md"):
        try:
            results[f.name] = _validate(f)
        except Exception as e:
            skipped.append({"file": f.name, "error": str(e)})  # never silently continue
    return {"results": results, "skipped": skipped}

Type footgun: YAML auto-parses an unquoted ISO date (date: 2025-06-15) into a
datetime.date, not a str or datetime.datetime. A validator that
handles only str/datetime will false-positive on native YAML dates. When
validating parsed values, enumerate every type the parser can actually produce.

Wrapping a subprocess / CLI

A huge share of MCP servers shell out to another tool. Three failures recur:

1. Don't discard stdout on a non-zero exit. Many CLIs exit non-zero by
design
(a linter/mutation-tester reporting findings) and write their real
output to stdout with an empty stderr. A wrapper that returns
f"Error: {result.stderr}" whenever returncode != 0 reports a successful run
to the LLM as an empty "Error: ".

def run_tool(args: list[str]) -> dict:
    r = subprocess.run(args, capture_output=True, text=True)
    return {                       # hand BOTH streams to the model; let it judge
        "returncode": r.returncode,
        "stdout": r.stdout,
        "stderr": r.stderr,
    }

2. Pin to the version you actually wrap, and verify subcommands exist. A
server written against a tool's 2.x CLI while the project pins 3.x will call
subcommands and flags that no longer exist — every wrapped tool breaks at
runtime. Check the installed version's --help, not your memory of it.

3. Parse args safely. Splitting an extra-args string with str.split()
breaks quoted, space-containing arguments — use shlex.split(). Never
interpolate a client-supplied string into a shell command; pass an argv list to
subprocess.run (no shell=True). When a tool accepts a target/path, remember
the LLM (or content it read) chose it — validate it.

No module-level global state (it makes the server untestable)

Parsing CLI args at import time and stashing them in module globals
(WORKING_DIR, MAKEFILE_PATH, caches…) forces every test to
del sys.modules["server"] and re-import under a patched sys.argv just to
reset state — brittle and easy to get wrong. Keep configuration in an object or
pass it through; construct tools from a factory.

def build_server(config: Config) -> FastMCP:
    mcp = FastMCP("my-server")

    @mcp.tool()
    def do_thing(x: str) -> dict:
        return {"result": _work(x, config)}   # config captured, not global

    return mcp

This also avoids double registration: a module-level "create all tools" loop
plus the same loop inside main() registers every tool twice when the file is
run directly (uv run server.py, as Claude Desktop does) versus via a console
entry point. Register in exactly one place.

Keep blocking work off the protocol event loop

Do not assume a framework moves synchronous tool functions to a worker thread.
Some FastMCP runtimes invoke them inline on the protocol event loop. A SQLite
query, filesystem walk, dependency traversal, or synchronous HTTP call that takes
five seconds can therefore block pings and every unrelated request for the same
five seconds.

Make the tool async and move only the blocking boundary to a thread:

import asyncio

@mcp.tool()
async def find_dependents(item_id: int) -> dict:
    rows = await asyncio.to_thread(repository.find_dependents, item_id)
    return {"items": [row.to_dict() for row in rows]}

Keep connection ownership in mind. Do not create a SQLite connection on the
event-loop thread and hand that connection to the worker. Open and close it
inside repository.find_dependents, or use a pool/driver whose concurrency
contract explicitly permits the handoff. A thread wrapper around a shared,
thread-affine connection merely trades event-loop starvation for intermittent
database errors.

Test responsiveness, not just the slow tool's result. Start a deliberately
blocked repository call, invoke a lightweight tool (or protocol ping) before
releasing it, and require the lightweight request to finish first:

slow = asyncio.create_task(call_tool("find_dependents", {"item_id": 42}))
await entered_worker.wait()

healthy = await asyncio.wait_for(call_tool("health", {}), timeout=0.2)
assert healthy == {"ok": True}

release_worker.set()
await slow

A timing assertion on the slow call alone cannot detect event-loop starvation;
the regression is that independent protocol traffic stops making progress.

Sampling is an optional client capability — contain failures in the tool

ctx.sample(...) is not guaranteed to work just because the tool itself was
called successfully. The connected client may not support sampling, or its
sampling handler may raise while processing the request. Those are different
failure modes at the framework layer, but they are the same tool-level outcome:
the requested analysis could not be produced.

Catch the exception around the sampling boundary inside the tool and convert
it to the server's normal error shape. Do not rely on the framework's outer
exception wrapper; by then the caller receives an opaque protocol/tool error
instead of your documented contract.

async def sample_or_error(ctx: Context, prompt: str) -> dict:
    try:
        response = await ctx.sample(prompt)
    except Exception as exc:
        return {"error": f"sampling failed: {exc}"}
    return {"result": response.text or ""}

Keep the try block narrow so unrelated programming errors are not mislabeled as
sampling failures. Test both boundaries explicitly: a client with no sampling
support, and a configured sampling handler that raises. Also test an empty
sampling response if the tool promises an empty-string or other fallback.

Distribution: single-file vs packaged

MCP servers are often launched as a single file (uv run server.py), so two
packaging traps are easy to ship without noticing:

  • Module/package name collision. Having both a top-level server.py and a
    server/ package directory means import server resolves to the package
    (shadowing the module), so a console entry point like server:main finds no
    main and fails. Only running the file directly works. Pick one name.
  • Over-narrow build includes. A build config like
    only-include = ["server.py"] produces a wheel containing just that file —
    import server.analyzers raises ModuleNotFoundError for anyone who
    pip installs it, even though uv run server.py works locally. If you ship a
    package, include the package and its data files.

For a PEP 723 single-file server, pin explicit versions in the inline
# /// script header and keep them in sync with pyproject.toml; a
transitive-only dependency (imported but never declared) breaks the moment the
intermediary drops it.

Testing: prove the tools actually work

Mocking the subprocess/transport layer and asserting that argv contains certain
tokens locks in commands that may not exist in the wrapped tool — the suite stays
green while every tool is broken at runtime. A passing CI here does not mean
the server works.

  • Keep at least one integration test that invokes the real wrapped tool (or
    a real sample file) end to end.
  • A bare import server smoke test is meaningless under a name collision (it can
    import an empty package). Assert a tool runs and returns expected output.
  • Test the error contract: malformed input returns your "error" shape, batch
    tools populate skipped.

Treat all tool I/O as untrusted (prompt injection)

Tool inputs, file contents, and especially other tools' descriptions can be
attacker-influenced and flow into the model's context. A server that feeds such
text back into a second LLM call is itself a prompt-injection surface — its
output is advisory, not authoritative. Don't grant a tool more filesystem/network
reach than it needs, validate paths, and never let tool output be treated as a
trusted instruction.

MCP Server Checklist

Contract:
- [ ] One consistent error shape; documented that callers check it
- [ ] Batch tools return a per-item skipped/errors list (never silent continue)
- [ ] Inputs validated (absolute paths, allowed types) before use
- [ ] Sampling failures (unsupported client and handler exception) normalized inside the tool

Subprocess:
- [ ] Both stdout and stderr returned; non-zero exit not assumed to be failure
- [ ] Pinned to the wrapped tool's actual version; subcommands verified
- [ ] shlex.split for arg strings; argv list (no shell=True)

Structure:
- [ ] No module-level CLI parsing / global state
- [ ] Tools registered in exactly one place
- [ ] Blocking database/filesystem/network work moved off the protocol event loop
- [ ] Concurrency test proves a lightweight request completes while a slow tool is blocked

Distribution & tests:
- [ ] No server.py / server/ name collision; build includes the whole package
- [ ] PEP 723 header deps pinned and synced with pyproject
- [ ] An integration test exercises a real tool (not just mocked argv)

Note for this repository (ffmpeg-skill)

mcp/server.py here is a hand-rolled stdio JSON-RPC server, NOT FastMCP — the
@mcp.tool() decorator examples above don't apply directly. But most of the
principles transfer almost exactly, because this server's entire job is
wrapping 42 subprocess-based CLI tools:

  • The subprocess-wrapping section (stdout/stderr handling, argv-list-only, no
    shell=True) matches mcp/server.py's actual design: execution.shell: false and arbitrary_executables: false are load-bearing guarantees in
    contract --json, not just documentation.
  • "No module-level global state" and "tools registered in exactly one place"
    are already true by construction here: tools/list is derived from
    scripts/_contract.py at call time, not from a hand-written table (see
    tests/test_contract.py's test_mcp_tools_match_contract and
    test_mcp_schema_drift_follows_the_scripts).
  • "Testing: prove the tools actually work" is already the norm —
    test_mcp_tool_call_round_trip and the contract tests build real JSON-RPC
    requests and check real tool output, not mocked argv.
  • The event-loop/blocking-work section does not apply: this server is
    synchronous stdio, not an async framework moving work onto a shared loop.
  • The prompt-injection section is worth taking seriously as-is: any tool
    whose input includes a caller-supplied path (nearly all of them) should be
    read with the same wariness this section describes.

Source: wdm0006/python-skills (MIT).

This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
reproducing-ci-locallyRun the CI gate on your machine so it agrees with the runner — deriving the exact command, paths, markers, and env from the workflow file instead of the Makefile, unblocking gate steps that short-circuit and hide the next failure, pinning the linter version CI resolves, building the interpreter/toolchain environment the runner builds, and confirming the run is green instead of explaining a red job away. Use when a check passes locally but fails in CI (or the reverse), when a lint/format job goes red on an untouched file, when setting up a local dev loop for an unfamiliar repo, or before pushing a branch you expect to merge.0 installsconcurrent-branchesResolve conflicts and merges when several branches are open against one repo at the same time — the hotspot files every change must touch (registry manifests, a single version field, shared tool config, one aggregated test module, tracked build output), union-vs-recompute-vs-rebuild as three different correct resolutions, generated artifacts that must never be merged, non-deterministic serialization that makes every branch conflict, renumbered identifiers that git cannot show you, and why a clean auto-merge is not a passing test. Use when rebasing or merging a long-lived branch, resolving conflict markers, reviewing a merge commit, deciding what a repo should commit vs generate, or setting up a repo that will take parallel contributions.0 installsprobing-edge-valuesFind the option values an ffmpeg-skill tool accepts without anyone having decided what they mean — zero, a negative number, a value far past any real frame or clip — by running tests/edge_values.py over every numeric option in the contract, then reading each call that ran or hung against the option's help, and checking the few properties a tool should keep (doing it twice changes nothing more, an inverse returns the source's shape, the output is what probe.py says). Use when looking for defects nobody has reported, before a tool moves from beta to stable, after adding a numeric option, or when a report says a tool "hung", "wrote a strange file" or "accepted nonsense".0 installsmanaging-python-releasesManages Python library releases including semantic versioning, changelog maintenance (Keep a Changelog format), release automation with GitHub Actions, and deprecation workflows. Use when planning releases, writing changelogs, automating release pipelines, or communicating breaking changes.0 installsrunning-github-actions-efficientlyCut GitHub Actions minutes and wall-clock time without losing coverage — the OS billing multiplier (macOS 10x / Windows 2x / Linux 1x), trigger hygiene that stops push+pull_request double-firing, concurrency that cancels superseded runs, dependency caching keyed on lockfiles, matrix discipline, and auditing scheduled crons that bill 24/7. Use when CI is burning included minutes, when runs feel slow, when setting up a new repo's workflows, or when reviewing an existing workflow for waste.0 installsshipping-across-surfacesLand a change everywhere the same fact is stated — enumerating the full surface inventory (landing copy, docs, machine-readable summaries, changelog badges repeated across every page, sitemap, README, descriptions embedded in code, and untyped frontend consumers of typed responses), generating a surface instead of restating it, drift tests where you cannot generate, never hand-maintaining a copy of a surface another codebase owns, shipping a paired PR when you change a format a different codebase decodes, and keeping overloaded product words apart. Use when adding or renaming a user-facing feature, editing product/marketing copy or docs, renaming a serialized response field, changing a serialization or share-link format, wiring one repo's output into another's checks, or reviewing a PR that touched only one place a fact appears.0 installs

More from ffmpeg-skill

View source →
ffmpeg-skillEdit video and audio with local FFmpeg: cut, join, reframe, speed, captions, overlays, silence removal, sync, loudness, HDR to SDR, platform exports and checks. Use whenever the user mentions a video or audio file (mp4, mov, wav, m4a), footage, captions, a reel or short, YouTube/TikTok delivery, LUFS or ffmpeg, even without saying "edit". Needs FFmpeg 6.1+ and Python 3.10+; stdlib only, no cloud.24 installsreviewing-ffmpeg-skill-changesReview a change to the ffmpeg-skill repository for the failures its own contract makes possible — a claim in a result document that is true at one layer and false at the layer a caller reads, a new flag that reaches the code but not the contract/docs/demo surfaces, a "bug" that docs/design-decisions.md already decided with a pinning test, a fix with no regression test, a new runtime dependency or a raw ffmpeg shell call that breaks the scope boundary, a SKILL.md line added without one trimmed, a review that re-derives findings from a summary instead of the tree at the reviewed commit. Use when asked to review a PR or diff in this repository, when authoring code here and needing a pre-commit check, or when triaging an external review or audit report about this codebase.5 installsffmpeg-skillEdit video and audio with local FFmpeg: cut, join, reframe, speed, captions, overlays, silence removal, sync, loudness, HDR to SDR, platform exports and checks. Use whenever the user mentions a video or audio file (mp4, mov, wav, m4a), footage, captions, a reel or short, YouTube/TikTok delivery, LUFS or ffmpeg, even without saying "edit". Needs FFmpeg 6.1+ and Python 3.10+; stdlib only, no cloud.4 installskeeping-git-repos-cleanPrevents, detects, and remediates files that should never be committed — secrets (.env, API tokens, hardcoded credentials) and dev artifacts (build output, scratch databases, editor/OS files). Covers .gitignore (and why it does not untrack), git rm --cached, auditing tracked files, history scrubbing, and credential rotation. Use when a repo has committed secrets or junk, when setting up a new repo's ignore rules, or when reviewing what a repo actually tracks.1 installsci-pipeline-synthesizerGenerate GitHub Actions CI/CD pipeline configurations for automated building and testing of library and package projects. Use when creating or updating CI workflows for npm packages, Python packages, Go modules, Rust crates, or other library projects that need automated build and test pipelines. Includes templates for common package ecosystems with best practices for dependency caching, matrix testing, and artifact publishing.0 installsbuilding-the-review-pageBuild or change the standalone review page (scripts/_review.py, `npx ffmpeg-skill review`) — the editor-style screen where a person looks at a render project and its result and composes an instruction for their agent. Covers the fixed constraints (one offline HTML file, nothing executed, no new dependency, not a contract tool), the 16:10 three-column layout, the numbering scheme every element carries (S, C, T, A, M, R, P,0 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.656 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.561 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.373 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.269 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.186 installsfounder-consumerThe consumer panel. Spins up a swarm of buyer sub-agents (default 100, --quick for 20) trained on the user's target customer, each with a different income, age, buying behaviour and objection, shows every one the same pitch, and runs the business through 100 buyer scenarios to see who buys, who doesn't, and why. Tallies the answers into buy rates by segment, the reasons people pass in their own words, what would flip a no, and price answers for founder-pricing. Use when the user says "would people buy this", "test it on customers", "run the consumer panel", "simulate buyers", "who is my customer", or "validate demand".154 installs

Frequently asked questions about building-python-mcp-servers

What does the building-python-mcp-servers skill do?

Builds robust Python MCP (Model Context Protocol) servers with FastMCP — tool design, error contracts, event-loop-safe blocking work, subprocess/CLI wrapping, single-file vs packaged distribution, global-state-free testing, and prompt-injection awareness. Use when writing an MCP server, exposing a tool or CLI to an LLM client, debugging tool registration/packaging, or testing MCP tools. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the building-python-mcp-servers skill?

Run `npx @skills-hub-ai/cli install ffmpeg-skill-building-python-mcp-servers` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/ffmpeg-skill-building-python-mcp-servers/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does building-python-mcp-servers work with?

building-python-mcp-servers runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the building-python-mcp-servers skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use building-python-mcp-servers after installing it?

In Claude Code, type `/ffmpeg-skill-building-python-mcp-servers` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the building-python-mcp-servers skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.

Badge for your README

Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.

Install on Skills Hub badge preview
Markdown
[![Install on Skills Hub](https://skills-hub.ai/api/badges/skill/ffmpeg-skill-building-python-mcp-servers)](https://skills-hub.ai/skills/ffmpeg-skill-building-python-mcp-servers)
HTML
<a href="https://skills-hub.ai/skills/ffmpeg-skill-building-python-mcp-servers"><img src="https://skills-hub.ai/api/badges/skill/ffmpeg-skill-building-python-mcp-servers" alt="Install on Skills Hub"></a>

More options in the badge docs.