Skip to content
Go back

MCP Server in Python: Claude Can't See Why Tools Fail

This is an MCP server I wrote in Python. Claude Code uses it to read my staged changes and commit them.

The odd part: I gave the server the same bad path twice and changed one word in the code. With one word, Claude started guessing; with the other, the server’s own message carried the reason. This post builds the server, with two git tools, and shows where that word goes.

You need to know some Python. You don’t need AI engineering experience or an API key, because you can build and test the server without a model. The code is in the git-tools-mcp-server repo, and every step has a tag.

What an MCP server is

An MCP server is how you hand your own tools to an AI app. You write it once, and any app that speaks MCP can discover it and use it.

You need Python 3.14, git, uv and Node (only for the Inspector). The exact versions are in the repo’s README.

Three roles

A server can offer tools, resources and prompts. Today it’s only tools: functions the model decides to call.

In the last post, the gcommit agent kept its tools inside itself: a schema, a function and a dispatch table. MCP moves all of that out into a server, and the agent just asks what’s there.

How the messages travel

Everything is JSON-RPC. A request has an id, and the response carries the same id. A notification has no id, so nothing comes back.

Locally, the host launches your server as a subprocess and talks to it through standard in and standard out, one JSON message per line. That means standard out belongs to the protocol, and logs go to standard error. Hold that thought, because it decides where an approval prompt can live.

Sequence diagram of an MCP session over stdio. The host and client send initialize, an initialized notification with no id and no reply, tools/list and tools/call for git_diff. The server answers each request with a response carrying the same id.

In the spec up to November 2025, a session starts with initialize, then an initialized notification, then a tool list, then tool calls. The newest spec, dated 2026-07-28, drops those first two steps. The Python SDK serves both, and the Inspector shows the older flow, so that’s what we’ll watch.

Step 1: a package and the git code

Create a package with uv and add the MCP SDK with its cli extra:

uv init --package git-tools-practice
cd git-tools-practice
uv add "mcp[cli]"

Before any MCP, we write the hands: plain Python that runs git. _run_git is the only place we call git, and it makes three decisions:

Every failure comes back as a string that starts with ERROR.

import os
import subprocess

GIT_TIMEOUT_SECONDS = 10


def repo_dir() -> str | None:
    return os.environ.get("GIT_TOOLS_REPO") or None


def _run_git(cmd: list[str]) -> subprocess.CompletedProcess[str] | str:
    """Run a git command. Returns the result, or an ERROR string on failure."""
    d = repo_dir()
    if d and not os.path.isdir(d):
        return f"ERROR: GIT_TOOLS_REPO is not a directory: {d}"
    try:
        return subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=GIT_TIMEOUT_SECONDS,
            cwd=d,
            stdin=subprocess.DEVNULL,
        )
    except subprocess.TimeoutExpired:
        return f"ERROR: git timed out after {GIT_TIMEOUT_SECONDS}s"
    except FileNotFoundError:
        return "ERROR: git is not installed or not on PATH"

run_git_diff builds the command on top of that. The environment variable GIT_TOOLS_REPO says which repo to use, because a client launches your server from a folder you don’t control.

This file knows nothing about MCP, on purpose, and that comes back at the end.

Step 2: turn it into a tool

MCPServer takes a name, and the @mcp.tool() decorator reads the type hints and the docstring to build the schema the model sees. So the docstring works as the model’s instructions, not as a comment.

from typing import Optional

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

from . import git_ops

mcp = MCPServer(
    "git-tools",
    instructions=(
        "Tools for reading staged git changes and creating commits in one "
        "repository. Always inspect the diff before committing."
    ),
)


@mcp.tool()
def git_diff(staged: bool = True, path: Optional[str] = None) -> str:
    """Returns a git diff for the current repo.

    By default returns the staged diff. Pass 'path' to see the diff of a
    single file, which is useful when the full diff is too large or has been
    truncated.

    Args:
        staged: If true (default), diff staged changes. If false, diff unstaged changes.
        path: Optional. Relative path of a single file to diff.
    """
    return _unwrap(git_ops.run_git_diff(staged=staged, path=path))

main calls mcp.run(), which is the loop reading standard in. In pyproject.toml, the [project.scripts] table registers a command, git-tools-practice, so a client can launch the server.

Run it and nothing happens, which looks like a hang but is just the server waiting for a message.

Step 3: test it without a model

The MCP Inspector is a test client. You start it with npx, set the repo with -e, and give it the server command:

npx @modelcontextprotocol/inspector@latest \
  -e GIT_TOOLS_REPO=/path/to/a/repo \
  uv run git-tools-practice

Keep the -e flag, because the Inspector doesn’t pass your shell’s variables to the server it launches. In the Inspector you’ll see the tool list and git_diff, with the schema the decorator built.

Or skip the SDK completely

scripts/raw_jsonrpc.py starts the server and sends four JSON lines by hand: initialize, the initialized notification, a tool list, and a call to git_diff.

GIT_TOOLS_REPO=/path/to/a/repo uv run python scripts/raw_jsonrpc.py

Four messages go out and three replies come back, since the notification has no id and so gets none.

Step 4: the tool that changes something

git_commit has no approval prompt, because it can’t have one: standard in is the protocol, so there’s nobody to ask, and the host does the asking instead. Claude Code and Claude Desktop show an allow prompt before the call goes out.

@mcp.tool()
def git_commit(message: str) -> str:
    """Creates a commit with a given message.

    Commits whatever is currently staged. Call git_diff first so the message
    describes the actual changes.

    Args:
        message: The commit message.
    """
    return _unwrap(git_ops.run_git_commit(message=message))

That’s a real trade-off: this server is only safe with a client that asks first, so keep approval on for git_commit.

In Claude Code, the model reads the staged diff, writes a one-line message, and asks before it commits. That allow prompt is the guard. You can add the server with:

claude mcp add git-tools -e GIT_TOOLS_REPO=/path/to/a/repo -- \
  uv --directory /absolute/path/to/git-tools-mcp-server run git-tools-mcp-server

Step 5: the one word

Every result starts with OK or ERROR, and _unwrap turns an ERROR into a tool error:

def _unwrap(result: str) -> str:
    if result.startswith("ERROR"):
        raise ToolError(result)
    return result.removeprefix("OK: ").removeprefix("OK:")

That’s the one word: ToolError. On SDK 2, a tool error’s message reaches the model, after an Error executing tool <name>: prefix. Any other exception still marks the call as failed, but the model only sees “Error executing tool” plus the tool’s name.

So back to the start. With a ValueError, Claude knew the call failed but couldn’t see why, so all it could do was guess. With a ToolError, the reason was in the tool’s own message, and Claude could quote it.

Break three things on purpose

The repo path check

Comment it out and point at a folder that doesn’t exist. Git is fine; the folder is what’s missing. Yet the error says git is not installed. I hit exactly this, and it sent me looking in the wrong place. Point it at a file instead of a folder and the check catches that too, with the same clear message.

The timeout

Set it to a millisecond. With the handler, you get a clear “git timed out” message. Take the handler out and you get a raw traceback instead. Inside the server, that becomes the generic error.

A file that doesn’t exist

Without a check, git says OK: (no changes). That looks like a clean tree for a file that isn’t there, and a model might commit without ever looking at it. With the check, you get path not found.

One more thing: a stray print

A stray print used to corrupt the protocol, but on SDK 2, in my run, nothing broke, because the SDK sends standard out to standard error. Don’t depend on that.

Recap

  1. Keep your logic in plain Python and make the MCP layer thin. git_ops.py knows nothing about MCP, and server.py knows nothing about subprocesses.
  2. Errors need a reason, so raise a ToolError.
  3. The server can’t ask a human, so the client has to.

What I’d change: I only added the path check after I saw “no changes” for a file that wasn’t there. Next time I’d validate inputs before git does.

Try it yourself

Connect this server to Claude Desktop. The repo’s README has the setup. For a challenge, add a git_status tool: one function in git_ops.py and one decorated function in server.py.

To see the code at any step, use the tags p01-step-1 through p01-step-8:

git clone https://github.com/nononsense-ai/git-tools-mcp-server.git
cd git-tools-mcp-server
git checkout p01-step-3
git checkout main   # back to the final code

Next time we build the other side: an MCP client in Python, so your agent stops hard-coding its tools.

This builds on Who Actually Runs the Command? How AI Agents Work, where the gcommit agent kept its tools inside itself.


Share this post:

Previous Post
Next-Concept Modeling (NCM): Up to 31x Faster Text Generation
Next Post
MCP Client in Python: Build One Without a Model