Agent skill

Building Python MCP Servers

by kajisho5 in kajisho5/ffmpeg-skill

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…

MITAuto-check passedAgent Workflows

Install Building Python MCP Servers

skills CLI
$ npx skills add kajisho5/ffmpeg-skill --skill building-python-mcp-servers -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install kajisho5/ffmpeg-skill building-python-mcp-servers --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/kajisho5/ffmpeg-skill.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.claude/skills/mcp-server-design .claude/skills/building-python-mcp-servers && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
building-python-mcp-servers
GitHub stars
1.9k
Token cost
~3.2k tokens
SKILL.md length
1,353 words
Files
1
Skills in repo
14
Repo updated
First seen
Licence
MIT

At a glance

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…

  • Writing an MCP server
  • SKILL.md covers Quick Start (FastMCP), Error Contract: return, don't…, Wrapping a subprocess / CLI and No module-level global state…, plus 7 more sections
  • Calls uv and pip
  • Exposing a tool

What it does

Building Python MCP Servers is an agent skill from kajisho5/ffmpeg-skill. 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.

Its SKILL.md is about 3.2k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Agent Workflows, covering MCP servers, Async programming and State management. It works with Model Context Protocol and Python. The licence is MIT.

When your agent uses it

  • Writing an MCP server
  • Exposing a tool
  • CLI to an LLM client
  • Debugging tool registration/packaging

Example prompts

  • “Use the building-python-mcp-servers skill to build robust Python MCP (Model Context Protocol) servers with FastMCP — tool design, error contracts…”
  • “/building-python-mcp-servers”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit 008333a. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • uv
    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • github.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Building Python MCP Servers loads about 3.2k tokens when it runs. Until then it costs about 104 tokens; SKILL.md has 1,353 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~104
When it runs · the whole SKILL.md, loaded when a task matches
~3.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from kajisho5/ffmpeg-skill at commit 008333a, republished under its MIT licence (© kajisho5). 1,353 words, ~3,224 tokens.

Download SKILL.mdSave it as .claude/skills/building-python-mcp-servers/SKILL.md (or your agent's skills folder).
name
building-python-mcp-servers
description
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.

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)

python
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.
python
@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: ".

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

python
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:

python
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:

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

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

Show full SKILL.md (518 more words)Show less

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

© kajisho5, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .claude/skills/mcp-server-design of kajisho5/ffmpeg-skill.

Open the folder on GitHubat commit 008333a

Compare with similar skills

Building Python MCP Servers next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Building Python MCP Servers compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Building Python MCP Servers this skillkajisho5/ffmpeg-skill1.9k—~3.2kAutomated safety check: PassMIT
MCP Server Builderanthropics/skills180k64 repos~2.3kAutomated safety check: PassApache-2.0
MCP Server BuildershareAI-lab/learn-claude-code78k5 repos~1.2kAutomated safety check: PassMIT
Fastmcp Client CLIPrefectHQ/fastmcp28k1 repos~823Automated safety check: PassApache-2.0
MemPalace Setup and OperationMemPalace/mempalace59k—~2.2kAutomated safety check: PassMIT
FastmcpTommy-yw/RunbookHermes5464 repos~2.1kAutomated safety check: PassMIT

Similar skills

  • MCP Server Builder

    anthropics/skills

    Official

    Guides the design and implementation of Model Context Protocol servers in TypeScript or Python, from tool naming and error messages to evaluation.

    180k GitHub starsUsed in 64 repos~2.3k tokens
    Agent WorkflowsAuto-check passed
  • MCP Server Builder

    shareAI-lab/learn-claude-code

    Walks through building MCP servers in Python or TypeScript that expose tools, resources and prompts to Claude, with templates, registration and testing.

    78k GitHub starsUsed in 5 repos~1.2k tokens
    Agent WorkflowsAuto-check passed
  • Fastmcp Client CLI

    PrefectHQ/fastmcp

    Query and invoke tools on MCP servers using fastmcp list and fastmcp call.

    28k GitHub starsUsed in 1 repo~823 tokens
    Agent WorkflowsAuto-check passed
  • Installs and configures MemPalace as a private local palace, a shared-brain hub or a client of an existing hub, including MCP registration and version-correct initialization.

    59k GitHub stars~2.2k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • Fastmcp

    Tommy-yw/RunbookHermes

    Build, test, inspect, install, and deploy MCP servers with FastMCP in Python.

    546 GitHub starsUsed in 4 repos~2.1k tokens
    Agent WorkflowsAuto-check passed
  • Migrate To Archestra

    archestra-ai/archestra

    Migrate an existing agentic PoC/pilot (Claude Code project files, MCP configs, hooks, local tools, openclaw config, or similar hand-rolled setup artifacts) into an Archestra instance.

    4.4k GitHub stars~2.6k tokensUpdated today
    Agent WorkflowsAuto-check passed

More from kajisho5/ffmpeg-skill

All 14 skills in this repo
  • Ffmpeg Skill

    kajisho5/ffmpeg-skill

    Edit video and audio with local FFmpeg from natural-language requests: cut, trim, join, resize/reframe (9:16, 1:1), speed change, captions and subtitles (SRT/ASS, animated, karaoke), logos and text…

    1.9k GitHub stars~7.4k tokensUpdated 3 days ago
    Auto-check passed
  • CI Pipeline Synthesizer

    kajisho5/ffmpeg-skill

    Generate GitHub Actions CI/CD pipeline configurations for automated building and testing of library and package projects.

    1.9k GitHub starsUsed in 1 repo~1.1k tokens
    Auto-check passed
  • Reviewing Ffmpeg Skill Changes

    kajisho5/ffmpeg-skill

    Review 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…

    1.9k GitHub stars~2.3k tokensUpdated 3 days ago
    Auto-check passed
  • Concurrent Branches

    kajisho5/ffmpeg-skill

    Resolve 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…

    1.9k GitHub stars~2.8k tokensUpdated 3 days ago
    Auto-check passed
  • Guarding Destructive Operations

    kajisho5/ffmpeg-skill

    Add and review preconditions on operations that delete, overwrite, rewrite history, or resolve a caller-supplied name to a filesystem path — refusing instead of warning, placing the guard ahead of…

    1.9k GitHub stars~2.6k tokensUpdated 3 days ago
    Auto-check passed
  • Keeping Git Repos Clean

    kajisho5/ffmpeg-skill

    Prevents, 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).

    1.9k GitHub stars~2.1k tokensUpdated 3 days ago
    Auto-check: notes

Categories

Questions about Building Python MCP Servers

What does Building Python MCP Servers 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…. Building Python MCP Servers is an agent skill from kajisho5/ffmpeg-skill. 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.

When should I use Building Python MCP Servers?

Building Python MCP Servers fits situations like: writing an MCP server; exposing a tool; CLI to an LLM client; debugging tool registration/packaging.

How do I install Building Python MCP Servers in Claude Code?

Run `npx skills add kajisho5/ffmpeg-skill --skill building-python-mcp-servers -a claude-code`. Or copy the skill folder (.claude/skills/mcp-server-design in kajisho5/ffmpeg-skill) into .claude/skills/building-python-mcp-servers in your project. Claude Code loads it when a task matches its description.

How do I install Building Python MCP Servers in Codex?

Run `npx skills add kajisho5/ffmpeg-skill --skill building-python-mcp-servers -a codex`. Or copy the skill folder (.claude/skills/mcp-server-design in kajisho5/ffmpeg-skill) into .agents/skills/building-python-mcp-servers in your project. Codex loads it when a task matches its description.

Can I use Building Python MCP Servers in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add kajisho5/ffmpeg-skill --skill building-python-mcp-servers -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/building-python-mcp-servers, .gemini/skills/building-python-mcp-servers, .github/skills/building-python-mcp-servers and .opencode/skills/building-python-mcp-servers in your project.

What does Building Python MCP Servers need to run?

Going by SKILL.md and its folder, Building Python MCP Servers needs the command-line tools its instructions call (uv and pip). Our summary lists: Python 3.

Does Building Python MCP Servers access the network?

SKILL.md names 1 domain. As links in the text: github.com. This is read from the text; nothing was executed.

Is Building Python MCP Servers safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Building Python MCP Servers use?

Building Python MCP Servers is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Building Python MCP Servers use?

About 3.2k tokens (SKILL.md is roughly 13k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Building Python MCP Servers?

Skills that share tags, products or a category with Building Python MCP Servers: MCP Server Builder (anthropics/skills, 180k stars), MCP Server Builder (shareAI-lab/learn-claude-code, 78k stars), Fastmcp Client CLI (PrefectHQ/fastmcp, 28k stars) and MemPalace Setup and Operation (MemPalace/mempalace, 59k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Building Python MCP Servers?

kajisho5 (a GitHub user) maintains it in kajisho5/ffmpeg-skill, which has 1,887 GitHub stars. The repository holds 14 skills in this directory. The repository was last updated on October 5, 2026.

Source: kajisho5/ffmpeg-skill on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.