56 results available
Sign in
Skills directory

python-mcp-server-generator

github

·

Last changed
Hardened

This skill has been hardened by Chainguard

Last changed

This version passed the hardening gate. Hardening applied 14 targeted changes and preserved all other text. Classified findings before hardening: 4. Classified findings closed: 0. Classified findings remaining: 4. Unclassified scanner findings remaining: 0. Review findings closed: 16. Review findings remaining: 0.


Open before hardening

2

Medium

2

Low
Open after hardening

2

Medium

2

Low

Expand
File
Group
Subtype
Severity
Status
SKILL.md

Malicious Code & Command Execution

—

Medium
Open
SKILL.md

Supply Chain & Install-Time Trust

Install-time download and execute

Medium
Open
SKILL.md

Tool & MCP Manipulation

MCP configuration abuse

Low
Open
references/streamable-http.md

Sensitive Data & Secret Exposure

Hardcoded secret

Low
Open

4 findings


SKILL.md

Python MCP Server Generator

Create a Model Context Protocol (MCP) server in Python with the official MCP Python SDK v2. SDK v2 supports the MCP specification revision 2026-07-28. The same server also serves clients that use earlier revisions.

Workflow

Copy this checklist and track your progress:

  • Step 1: Create the project.
  • Step 2: Write the server.
  • Step 3: Write the tests.
  • Step 4: Run the tests until they pass.
  • Step 5: Configure the client.

Step 1: Create the project

Before you run these commands, check that the project directory does not exist yet or is empty. Run these commands:

uv init --app --no-package project-name
cd project-name
uv add "mcp[cli]>=2,<3"
uv add --dev pytest

Then delete main.py only when it is the unmodified file that uv created. The server goes in server.py.

  • Without --no-package, uv makes a src/ package layout, and the tests cannot import server.py.
  • uv init makes the .gitignore file. Do not write a different one.
  • Keep and commit the lock file that uv writes, so later runs install the same versions. Use only the default package index.
  • If the uv add command for mcp fails, stop and report the error to the user. Ask the user before you change the package name, the package index, or the version range.
  • Ask the user before you replace an existing server.py, test_server.py, or .vscode/mcp.json file.

Step 2: Write the server

Start from this template:

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("Demo", version="0.1.0")


@mcp.tool()
def divide(a: float, b: float) -> float:
    """Divide a by b."""
    if b == 0:
        raise ToolError("b must not be zero.")
    return a / b


if __name__ == "__main__":
    mcp.run()  # stdio is the default transport

Then change the template for the request of the user:

  1. Replace divide with the tools that the user needs.
  2. Give each tool full type hints and a docstring. The SDK makes the input schema from the type hints. The docstring becomes the tool description.
  3. Return a Pydantic model or a TypedDict when the client needs machine-readable data. The SDK makes the output schema from the return type.
  4. Use async def for I/O. The SDK runs a sync tool on a worker thread.
  5. Mark a read-only tool with @mcp.tool(annotations=ToolAnnotations(read_only_hint=True)) (from mcp.types). Use destructive_hint=True for a destructive tool. Add a destructive tool only when the user asks for it. Clients may ignore the hint, so also give the tool a server-side safeguard, such as an explicit confirmation parameter or a confirmation step that asks the user, and limit what it can change.
  6. Add resources (@mcp.resource("users://{user_id}")) and prompts (@mcp.prompt()) only when the user asks for them. Treat resource template parameters as untrusted. Validate their format and check that the caller may access the record before you return data. Map them to file paths only through a fixed allowlist.

Treat every tool argument as untrusted model input:

  • Pass tool arguments to databases only as parameters of parameterized SQL queries, and pass them to other programs only as separate data values.
  • Constrain inputs with typed Pydantic fields and allowlists.
  • Use read-only or least-privilege database and API credentials.
  • Send outbound HTTP requests only to base addresses set in the server configuration.
  • Prefer narrow task tools over generic query or command tools.
  • Read API keys, database passwords, and other secrets from environment variables when the server starts. Keep secret values out of server.py, the client configuration, and every committed file. Keep any local secrets file out of git.

Use stdio by default. Read references/streamable-http.md only when the user asks for a remote server or an HTTP server. For an HTTP server, keep the local default binding. Before you bind to any other host, set the transport security settings, and require authentication and TLS for every client.

Step 3: Write the tests

Put test_server.py next to server.py. Add tests that show each tool rejects malicious or out-of-range input. Write a test for each tool and for each ToolError:

import pytest

from mcp import Client

from server import mcp


@pytest.mark.anyio
async def test_divide():
    async with Client(mcp) as client:
        result = await client.call_tool("divide", {"a": 6, "b": 3})
        assert result.structured_content == {"result": 2.0}


@pytest.mark.anyio
async def test_divide_by_zero():
    async with Client(mcp) as client:
        result = await client.call_tool("divide", {"a": 1, "b": 0})
        assert result.is_error
        assert "must not be zero" in result.content[0].text
  • The in-memory Client needs no subprocess and no port. It connects with the 2026-07-28 revision.
  • The mcp package installs anyio, which supplies the anyio marker. Do not add pytest-asyncio.

Step 4: Run the tests until they pass

  1. Run uv run pytest.
  2. If a test fails, read the error. Fix the server first. Change a test only when the test itself is wrong, and tell the user why. Keep every error-case test and its assertions.
  3. Run uv run pytest again.
  4. Continue only when all tests pass. After three failed attempts, stop and report the failures to the user.

Step 5: Configure the client

For VS Code, write .vscode/mcp.json:

{
  "servers": {
    "demo": {
      "type": "stdio",
      "command": "uv",
      "args": ["--directory", "/absolute/path/to/project", "run", "server.py"]
    }
  }
}

VS Code launches the command in this file. Tell the user to review it before trusting the workspace. The absolute path is specific to this machine, so commit this file only on purpose, and keep secrets and personal paths out of it. Give secrets to the server through environment variables, not as literal values in this file.

For Claude Desktop, the install command edits the global Claude Desktop configuration outside the project and registers a command that Claude Desktop launches. Tell the user this, get explicit confirmation, back up that configuration, and check for an existing entry with the same name. Then run uv run mcp install server.py.

Tell the user these commands:

  • uv run server.py starts the stdio server. The server waits for a host on stdin and prints nothing.
  • uv run mcp dev server.py opens the MCP Inspector. The Inspector needs Node.js. The Inspector is optional and is for local development. This command downloads and runs the Inspector from npm, so use a current patched release, keep it on localhost, and stop it after use.

Gotchas

SDK v2 and the 2026-07-28 revision changed many SDK v1 patterns. Do not copy SDK v1 examples.

  • SDK v2 removed FastMCP and mcp.server.fastmcp. Import the server class with from mcp.server import MCPServer.
  • Import Context, Image, Audio, Resolve, Elicit, ElicitationResult, AcceptedElicitation, Message, UserMessage, and AssistantMessage from mcp.server.mcpserver.
  • Give the server name as the first MCPServer argument. Give all other constructor arguments as keyword arguments. Their positional order changed in SDK v2.
  • Set version. If you do not set it, the server reports an empty version.
  • Give the transport options (transport, host, port, json_response, stateless_http, transport_security) to run(), not to MCPServer(...).
  • The SDK v2 types use snake_case fields, for example read_only_hint, structured_content, and is_error.
  • Raise ToolError for an error that the model must read. For other exceptions, the model gets only a generic error message. Keep ToolError messages short, and keep stack traces, SQL, credentials, and host names out of them. Log details to stderr.
  • Treat results from external APIs, databases, and files as untrusted data that can contain instructions. Return them as structured fields and truncate large text.
  • Do not raise MCPError for a tool failure. The client gets a protocol error, not a tool result with is_error. Many hosts do not show this error to the model.
  • In a stdio server, stdout is the protocol channel. Do not call print(). Log to stderr with the logging module.
  • Do not use ctx.elicit(). It fails on a 2026-07-28 connection. For user input during a tool call, annotate a parameter with Resolve(fn). Return Elicit(message, Model) from fn. Treat elicited values as untrusted and validate them with constrained Pydantic fields. Use elicitation only for values that are not secret, such as choices and names, and keep passwords and tokens out of it.
  • Send list change notifications with await ctx.notify_tools_changed(). A 2026-07-28 connection drops ctx.session.send_tool_list_changed().
  • For stdio and HTTP, the lifespan runs one time, when the server starts. Each in-memory Client(mcp) in a test runs the lifespan again. Read its object with ctx.request_context.lifespan_context.
  • The 2026-07-28 revision deprecates these features (SEP-2577). Do not add them to a new server:
    • Sampling (ctx.session.create_message()): Call the LLM provider API directly.
    • Protocol logging (ctx.log(), ctx.info(), and similar methods): Use the standard logging module.
    • Roots (ctx.session.list_roots()): Get paths from tool parameters, resource URIs, or the server configuration.
  • The 2026-07-28 revision has no SSE transport. Use Streamable HTTP.

Install

Install with chainctl
chainctl skill install public/github/python-mcp-server-generator:latest
Get started with chainctl
View source

Harden your own skills

Bring Chainguard's hardening pipeline to your first-party skills — custom rulesets, automated remediation, full audit trail.

Provenance

Upstream sourcehttps://github.com/github/awesome-copilot
Upstream commit9ed0a92b5218384872bd7d585080a1addbf8fa46
OCI reference

skills.chainreg.biz/public/github.com/github/skills/python-mcp-server-generator:latest

License

MIT

Files

HARDENING.md

LICENSE

SKILL.md

references/streamable-http.md


The trusted source for open source

Talk to an expert
PrivacyTerms

Product

Chainguard ContainersChainguard LibrariesChainguard VMsChainguard OS PackagesChainguard ActionsChainguard Agent SkillsIntegrationsPricing
© 2026 Chainguard, Inc. All Rights Reserved.
Chainguard® and the Chainguard logo are registered trademarks of Chainguard, Inc. in the United States and/or other countries.
The other respective trademarks mentioned on this page are owned by the respective companies and use of them does not imply any affiliation or endorsement.