Skip to content
Go back

MCP Client in Python: Build One Without a Model

Last time I built an MCP server with two git tools. This time I wrote the other half: a client that starts that server, asks what it can do, and calls it from a command line. There’s no model and no agent loop, so no API key either.

Most tutorials skip this part on the way to the fun bit, and it breaks in boring ways: a wrong path in a config file, a server that never answers, an error that arrives wrapped inside another error. This post builds the client and then breaks it on purpose.

You need the server from the previous post, Python 3.14 or newer, git and uv. The code is in the git-tools-mcp-client repo, and every step has a tag. The server is in git-tools-mcp-server.

What an MCP client does

In the server post, I played the client by hand: first with the Inspector, then with a script that wrote JSON lines to the server’s standard in. A real client automates that. It has four jobs:

  1. Start the server, or find one that’s already running.
  2. Do the handshake, where both sides say what they support.
  3. Ask for the tool list.
  4. Call tools and read what comes back.

The SDK’s Client class does the first two. You write the last two, and everything around them: which server to start, how to report a failure, when to give up waiting.

Why no agent loop

An agent is a client, plus a model, plus a loop that feeds tool results back to the model. Remove the model and the loop and the client is what’s left: a program that can run someone else’s tools and understand the answers.

Build that first. You can test it without spending tokens, and when it fails (a bad config, a dead process) a model isn’t there to muddy the cause.

Generic and typed clients

A generic client doesn’t know what tools exist. Claude Desktop is one: it connects, lists whatever the server offers, and hands those definitions to a model. A typed client knows its server. It has a method called git_diff(staged, path) and your editor can autocomplete it.

A typed client gives up discovery and gets checking in return. This one has a safeguard: at startup it asks the server for its tool list, and it stops if a tool it needs has gone missing.

Two ways a call fails

When a tool runs and fails, the server raises ToolError. The client receives a normal result with is_error set to True and the message in content. When the call never completes (the server died, or the timeout ran out), you get an exception: MCPError.

Both can happen in one program, and they arrive differently. Step 7 catches both.

Step 1: connect and list the tools

Create the project:

uv init --package git-tools-mcp-client
cd git-tools-mcp-client
uv add mcp pydantic

You also need a scratch repo with one staged file for the server to work on. The repo’s README has the commands. Then save this as scripts/hello.py, with SERVER_DIR set to the absolute path of your server project:

import asyncio

from mcp import Client, StdioServerParameters

SERVER_DIR = "/absolute/path/to/git-tools-mcp-server"

params = StdioServerParameters(
    command="uv",
    args=["run", "--directory", SERVER_DIR, "git-tools-mcp-server"],
    env={"GIT_TOOLS_REPO": "/tmp/scratch"},
)


async def main() -> None:
    async with Client(params) as client:
        print("instructions:", client.instructions)
        for tool in (await client.list_tools()).tools:
            print(tool.name, "-", tool.description.splitlines()[0])


asyncio.run(main())
instructions: Tools for reading staged git changes and creating commits in one repository. Always inspect the diff before committing.
git_diff - Returns a git diff for the current repo.
git_commit - Creates a commit with a given message.

That’s a working client in under twenty lines. Entering the async with spawned the server and ran the handshake. Leaving it closed the pipes and shut the server down.

Two details matter later. uv resolves a relative --directory against wherever you ran the client from, so use an absolute path. And the SDK doesn’t pass your whole shell environment to the server. It copies a short list of variables (HOME, PATH, USER and a few more) and adds whatever you put in env. So GIT_TOOLS_REPO has to be in env. Exporting it in your terminal does nothing.

Step 2: call a tool and read the result

async def main() -> None:
    async with Client(params) as client:
        result = await client.call_tool("git_diff", {"staged": True})
        print("is_error:", result.is_error)
        print("blocks:", [b.type for b in result.content])
        print(result.content[0].text)

        bad = await client.call_tool("git_diff", {"path": "no/such/file.txt"})
        print("is_error:", bad.is_error)
        print(bad.content[0].text)
is_error: False
blocks: ['text']
diff --git a/a.txt b/a.txt
...
is_error: True
Error executing tool git_diff: ERROR: path not found in the repo: no/such/file.txt

A tool result is a list of content blocks, not a string. This server only returns text, but another server could send images, which is why the code filters on b.type.

The failed call didn’t raise anything in Python. It returned normally with is_error=True. That’s the trap: if you only check for exceptions, a failed git_commit looks like a success. So check is_error once, in one place.

Step 3: wrap the tools in a typed client

Calling client.call_tool("git_diff", {...}) with a string and a dict works until someone misspells either one. A wrapper class puts the names and argument shapes in one place. First, exceptions.py:

class ClientError(Exception): ...


class ServerMismatchError(ClientError): ...


class ToolCallError(ClientError): ...

A shared base class pays off in Step 6. Then client.py:

import sys
from typing import Any, ClassVar

from mcp import Client, StdioServerParameters

from git_tools_mcp_client.exceptions import ServerMismatchError, ToolCallError


class GitToolsClient:
    REQUIRED_TOOLS: ClassVar[frozenset[str]] = frozenset({"git_diff", "git_commit"})

    def __init__(self, params: StdioServerParameters) -> None:
        self._client = Client(params)

    async def __aenter__(self):
        await self._client.__aenter__()
        try:
            await self._verify_tools()
        except BaseException:
            await self._client.__aexit__(*sys.exc_info())
            raise
        return self

    async def __aexit__(self, *exc) -> None:
        return await self._client.__aexit__(*exc)

    async def _verify_tools(self) -> None:
        names = {t.name for t in (await self._client.list_tools()).tools}
        missing = self.REQUIRED_TOOLS - names
        if missing:
            raise ServerMismatchError(
                f"Server is missing tools: {', '.join(sorted(missing))}"
            )

    async def _call(self, name: str, args: dict[str, Any]) -> str:
        result = await self._client.call_tool(name, args)
        text = "\n".join(b.text for b in result.content if b.type == "text")
        if result.is_error:
            raise ToolCallError(text or f"{name} failed with no message")
        return text

    async def git_diff(self, staged: bool = True, path: str | None = None) -> str:
        args: dict[str, Any] = {"staged": staged}
        if path:
            args["path"] = path
        return await self._call("git_diff", args)

    async def git_commit(self, message: str) -> str:
        return await self._call("git_commit", {"message": message})

    async def list_tool_names(self) -> list[str]:
        return [t.name for t in (await self._client.list_tools()).tools]

Reading it from the bottom up:

Step 4: move the launch details into mcp.json

Hardcoding SERVER_DIR works for one person on one machine. A config file fixes that. MCP clients share a convention: a top-level mcpServers object, one entry per server, each with command, args and env.

{
  "mcpServers": {
    "git-tools": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/absolute/path/to/git-tools-mcp-server",
        "git-tools-mcp-server"
      ]
    }
  }
}

Commit a mcp.example.json with a placeholder path and gitignore the real mcp.json. Your path only exists on your machine, and env is where API keys end up for servers that need them.

StdioServerParameters is a pydantic model, so the whole file can be a model that holds a dict of them, and pydantic writes the error messages:

class McpConfig(BaseModel):
    servers: dict[str, StdioServerParameters] = Field(alias="mcpServers")


def load_config(path: Path) -> McpConfig:
    try:
        return McpConfig.model_validate_json(path.read_text())
    except FileNotFoundError:
        raise ConfigError(f"config not found: {path}") from None
    except ValidationError as e:
        raise ConfigError(f"invalid config: {path}:\n{format_errors(e)}") from e

model_validate_json parses and validates in one call. Broken JSON, a missing mcpServers key and a server entry without a command all come out as the same ValidationError, each with a path to the problem. The full config.py is at tag step-05-config.

--repo is not in mcp.json, on purpose. Which server to launch is set once. Which repo to run it on changes with every command, so load_params takes it as an argument and puts it into GIT_TOOLS_REPO at launch. It can also be None, because a command like tools doesn’t touch a repo.

Step 5: add the command line

cli.py is a plain argparse parser with global options (--config, --server, --repo) and three subcommands: tools, diff and commit. The global options go before the subcommand: git-tools-mcp-client --repo /tmp/scratch diff.

In client.py, the commands are a lookup table:

COMMANDS: dict[str, Handler] = {
    "diff": cmd_diff,
    "commit": cmd_commit,
    "tools": cmd_tools,
}


async def run(args: Namespace) -> None:
    repo = resolve_repo(args.repo) if args.needs_repo else None
    params = load_params(args.config, args.server, repo)

    async with GitToolsClient(params) as git:
        await COMMANDS[args.cmd](git, args)

Adding a command means writing one function and one line in the table. run() checks the repo before anything starts, so diff --repo /tmp fails without launching a server, while tools --repo /tmp still works.

uv init --package generated a placeholder main, so point the script at the real one in pyproject.toml:

[project.scripts]
git-tools-mcp-client = "git_tools_mcp_client.client:main"
uv run git-tools-mcp-client --repo /tmp/scratch diff
uv run git-tools-mcp-client --repo /tmp/scratch commit -m "add a.txt"

The full cli.py and the command functions are at tag step-06-cli.

Step 6: make errors readable

Ask for a file that doesn’t exist:

uv run git-tools-mcp-client --repo /tmp/scratch diff --path no/such/file.txt

I expected main() to catch the ToolCallError and print one line. Instead I got a long traceback. The ToolCallError was right there at the bottom, so why didn’t except ClientError catch it?

Because it never arrived alone. The client runs its reader and writer inside an anyio task group, and when an exception unwinds through that group, Python wraps it in an ExceptionGroup. An except ClientError clause doesn’t match a group that contains one.

Python 3.11 added except* for this:

from mcp.shared.exceptions import MCPError


def main() -> None:
    args = parse_args()
    try:
        asyncio.run(run(args))
    except* (ClientError, OSError, MCPError) as eg:
        for e in eg.exceptions:
            print(f"error: {e}", file=sys.stderr)
        sys.exit(1)

The tuple covers three families of failure: your own ClientError subclasses, OSError (the shell can’t find the command in your config), and MCPError (the server died or a request timed out). Run it again and you get:

error: unhandled errors in a TaskGroup (1 sub-exception)

No traceback, but the useful part is gone. In my run the group was wrapped twice, so eg.exceptions holds another group, and printing a group prints its summary line. A small generator walks down to the real exceptions:

def leaves(exc: BaseException):
    if isinstance(exc, BaseExceptionGroup):
        for sub in exc.exceptions:
            yield from leaves(sub)
    else:
        yield exc

Loop over leaves(eg) instead of eg.exceptions:

error: Error executing tool git_diff: ERROR: path not found in the repo: no/such/file.txt

That’s one line with the real cause, and exit code 1 for scripts that check it. Errors from before the async with, like a bad config, were never wrapped, so the same handler covers them.

Step 7: don’t wait forever

A server can start fine and then never answer: a hung git process, a deadlock, a bug. Without a limit your command just sits there. Client takes read_timeout_seconds, which applies to every request it sends:

DEFAULT_TIMEOUT = 30.0


class GitToolsClient:
    def __init__(
        self, params: StdioServerParameters, timeout: float | None = DEFAULT_TIMEOUT
    ) -> None:
        self._client = Client(params, read_timeout_seconds=timeout)

Add a --timeout option to the parser and pass args.timeout through run(). The server’s own git calls give up after 10 seconds, so 30 on the client side leaves room for a cold uv run start without hiding a real hang.

Try an absurdly small value. tools still works with --timeout 0.001, because listing tools does no work on the server. A call that has to run git doesn’t:

error: Request 'tools/call' timed out

That’s an MCPError, and the handler from Step 6 already catches it.

Break things on purpose

The tutorial in the repo has eight experiments; here are four of them. Put throwaway configs in /tmp/cfgtest/ so your real mcp.json stays untouched.

A server directory that doesn’t exist. Use "--directory", "/nonexistent" in args:

error: No such file or directory (os error 2)
error: Connection closed

The first line comes from uv, not from the client: it’s the server process’s standard error, passed through. The second is your MCPError, which only says the server went away. Together they tell you what happened and where.

A config entry with a missing field. Delete the command line:

error: invalid config: /tmp/cfgtest/nocmd.json:
  mcpServers.git-tools.command: Field required

The path in the message comes free from pydantic.

A tool the server doesn’t have. Add "git_push" to REQUIRED_TOOLS and run tools:

error: Server is missing tools: git_push

_verify_tools catches it at startup, before any command runs.

A server that starts and never answers. Use "command": "sleep", "args": ["100"] and --timeout 2:

error: Request 'initialize' timed out

The timeout covers the handshake too, not only tool calls. The whole command took about 14 seconds on my machine, well past the 2 I asked for. I didn’t trace where the rest goes, but no sleep process was left behind. Your timings may differ.

Recap

  1. A client has four jobs: start the server, handshake, list tools, call tools. Client does the first two.
  2. The SDK passes the server a short list of environment variables plus your env. Anything else, like GIT_TOOLS_REPO, has to be set explicitly.
  3. A tool failure is a normal result with is_error=True. A dead server or a timeout raises MCPError. Check for both.
  4. Keep tool names in one wrapper class, and verify at startup that the server still offers them.
  5. Let pydantic validate mcp.json, and keep per-run choices like the repo on the command line.
  6. Errors raised inside async with Client(...) arrive wrapped in ExceptionGroups, sometimes twice. Use except* and walk down to the real exception.
  7. Set a timeout.

Try it yourself

If you did the git_status challenge on the server, teach the client about it. You touch four places: add "git_status" to REQUIRED_TOOLS, add a method to GitToolsClient, write cmd_status, and add one entry to COMMANDS. Then run tools against a server that doesn’t have the tool yet and read the error from _verify_tools.

To see the code at any step, use the tags step-01-project through step-08-timeout:

git clone https://github.com/nononsense-ai/git-tools-mcp-client.git
cd git-tools-mcp-client
git checkout step-04-typed-client
git checkout main   # back to the final code

What’s next

The client can run someone else’s tools and report what happened. It can’t decide anything yet. That’s the job of a host, the app between you and a model. The next part builds one on top of this client: it hands the server’s tool definitions to a model, and the model reads the diff, writes the message and calls git_commit itself. It doesn’t ask you first, and adding an approval step is the challenge at the end.

This is part 2. MCP Server in Python: Claude Can’t See Why Tools Fail builds the server this client talks to, MCP Agent in Python: Let a Model Call Your Git Tools is part 3, and Who Actually Runs the Command? How AI Agents Work explains the agent loop behind it.


Share this post:

Previous Post
MCP Server in Python: Claude Can't See Why Tools Fail
Next Post
MCP Agent in Python: Let a Model Call Your Git Tools