Here is a throwaway git repo with one file staged. I run one command, and the agent reads the diff, writes a commit message and makes the commit. I don’t type anything else.
This post builds that agent line by line. It comes to about 150 lines of Python. An agent that uses tools is a loop around an API call and a list of functions, and that loop is what we’re writing.
This is part 3 of the MCP series. Every file below is typed in full and in order, so you can follow along, and each step ends with a checkpoint: a command that tells you whether you’re on track. The finished code is in the git-tools-mcp-agent repo.
You need four things:
- Python 3.14 or newer
- uv, to manage the project and the Python version
- git
- An OpenRouter API key. OpenRouter puts many models behind one OpenAI-style API and has a free option, which is what we use. Create a key on their site and keep it private.
You also need a clone of the server from part 1. We use it as it is, with no changes:
git clone https://github.com/nononsense-ai/git-tools-mcp-server.git
What we reuse
In part 1 we built an MCP server with two git tools, git_diff and git_commit. In part 2 we wrote a Python client that launches that server and calls those tools. Neither involved a model. A human typed every command.
In part 3 a model takes over the typing. You say “review my staged changes and commit them”, and the model reads the diff, writes the message and commits, calling the same server through the same client.
We throw nothing away from the first two parts, and the server stays unchanged. From the client we reuse the server launch, the MCP config file, the repo resolver, the error classes and the error handling pattern from part 2.
The method I forgot
When I wrote the client in part 2, I left out a method. It has typed methods for the two tools it knows about, git_diff and git_commit, and it can list tool names. That was fine for a command line, where I picked which method to call.
A model works differently. To use a tool it needs the name, the description and the input schema, so it knows what the tool does and what arguments to send. And when it picks one, we have to call it by name with whatever arguments it produced. The client can do neither: it has no method that returns the full tool definitions, and no public method that calls a tool by name.
I should have added those in part 2 and didn’t. So here we subclass the client and add the two missing methods ourselves. That works fine, and it shows you can extend the client without editing it. If you’d rather fix it where it belongs, move the two methods into the client repo and delete the subclass; nothing else changes.
How the pieces fit
You give the agent a prompt. The agent sends the conversation and a list of tools to the model. The model doesn’t run anything; it answers with a request, something like “call git_diff”. The agent runs that tool through the MCP client, which talks to the MCP server, which runs git on your repo. The result goes back into the conversation, and the agent asks the model again.
There are three pieces:
- The MCP server exposes git operations as tools, each with a name, a description and a schema for its arguments. Those come from the docstrings and type hints in the server code. So the sentence in the commit tool’s docstring that says to call
git_difffirst is advice the model actually reads. - The MCP client launches the server and lets you list and call its tools.
- The agent is the part we write today. It sends messages and tools to the model, runs whichever tool the model asks for, adds the result to the conversation and asks again, until the model answers in plain text.
The agent contains no git-specific code. It asks the server what tools exist and hands them to the model as they are. If the server gains a new tool, the agent can use it without any changes.
Step 1: scaffold the project
Four commands. uv init --package gives us a src/ layout. Then we pin Python 3.14 and add three dependencies: our client from GitHub, the OpenAI SDK, and python-dotenv.
uv init --package git-tools-mcp-agent
cd git-tools-mcp-agent
uv python pin 3.14
uv add git+https://github.com/nononsense-ai/git-tools-mcp-client.git openai python-dotenv
Now create the four empty files we’ll fill in:
cd src/git_tools_mcp_agent
touch cli.py llm.py mcp_tools.py agent.py
cd ../..
cli.pyparses arguments and holdsmain.llm.pycreates the model client.mcp_tools.pydiscovers tools and calls them.agent.pyhas the system prompt and the loop.
The __init__.py file just exports main, and uv already created it.
Open pyproject.toml and look for a [project.scripts] section. Recent versions of uv add it for you when you use --package. It’s the line that makes uv run git-tools-mcp-agent work, so if yours is missing it, add it:
[project.scripts]
git-tools-mcp-agent = "git_tools_mcp_agent:main"
Step 2: config and secrets
Tell the agent where the MCP server lives. Create mcp.json in the project root, in the same format other MCP-aware tools use. The agent runs this command as a subprocess and talks to it over standard in and standard out:
{
"mcpServers": {
"git-tools": {
"command": "uv",
"args": [
"run",
"--directory",
"/absolute/path/to/git-tools-mcp-server",
"git-tools-mcp-server"
]
}
}
}
Replace the path with the absolute path to the server you cloned. If you’re not sure what that is, run pwd inside that folder.
Next, .env, with your OpenRouter key. Paste your real key after the equals sign:
OPENROUTER_API_KEY=sk-or-...
Both files are specific to your machine, and .env is a secret, so they go in .gitignore. uv already created that file, so add these two lines at the bottom:
mcp.json
.env
And commit a copy named mcp.example.json with a placeholder path, so other people can see the shape:
{
"mcpServers": {
"git-tools": {
"command": "uv",
"args": [
"run",
"--directory",
"/path/to/git-tools-mcp-server",
"git-tools-mcp-server"
]
}
}
}
Step 3: llm.py, the model client
This file has one job: give the rest of the program a ready model client.
We use OpenRouter so we can call a model named openrouter/free, which costs nothing. The catch is that it isn’t one fixed model. OpenRouter picks whichever free model is available, so the model answering you can change from run to run, and some are better at tool calling than others. We’ll come back to that at the end.
OpenRouter speaks the OpenAI API format, so we use the regular OpenAI SDK and point it at a different base URL. Start with the imports and two constants:
import os
from git_tools_mcp_client.exceptions import ConfigError
from openai import AsyncOpenAI
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
DEFAULT_MODEL = "openrouter/free"
The base URL is the only thing that differs from calling OpenAI directly.
Now the key check:
def get_api_key() -> str:
key = os.environ.get("OPENROUTER_API_KEY", "").strip()
if not key:
raise ConfigError("OPENROUTER_API_KEY is not set; put it in .env or export it")
return key
We read OPENROUTER_API_KEY from the environment. The empty-string default means a missing variable gives us an empty string instead of None, and strip() means a key made only of spaces counts as missing too. If there’s no key, we raise ConfigError, the exception from the part 2 client. That’s a client error, so main will catch it in Step 6 and print one clean error line instead of a traceback. We check now so the problem doesn’t surface later as a confusing 401 from the API.
And the client itself:
def make_llm() -> AsyncOpenAI:
return AsyncOpenAI(base_url=OPENROUTER_BASE_URL, api_key=get_api_key())
It’s AsyncOpenAI, not plain OpenAI. Everything else in this program is async: the MCP client starts the server with async with, and listing and calling tools are coroutines you await. A normal client would block the event loop during a model call that can take many seconds, and the background work that keeps the MCP connection alive couldn’t run. Our agent only does one thing at a time, so async won’t make it faster. We use it so the model call fits the code around it.
Checkpoint. With a fake key, creating the client should work and print AsyncOpenAI:
OPENROUTER_API_KEY=fake uv run python -c "from git_tools_mcp_agent.llm import make_llm; print(type(make_llm()).__name__)"
AsyncOpenAI
If you get an import error, check the file name and your dependencies.
Step 4: mcp_tools.py, tool discovery and dispatch
This is the heart of the project, and it’s where I make up for the missing method.
An LLM’s tool-calling API wants a list of tools, each with a type of function, a name, a description and a parameters schema. An MCP tool already has a name, a description and an input schema, so the conversion is a straight mapping. What we need is a way to get the full tool definitions out of the client, and a way to call a tool by name.
Imports, then the subclass. AgentGitToolsClient extends GitToolsClient, the class from part 2:
from typing import Any
from git_tools_mcp_client.client import GitToolsClient
from openai.types.chat import ChatCompletionToolUnionParam
class AgentGitToolsClient(GitToolsClient):
"""GitToolsClient plus generic tool discovery and dispatch for an LLM agent."""
openai_tools asks the server for its tools with list_tools and reshapes each one for the model: the name, the description, and the input schema as parameters. Part 2’s list_tool_names threw away everything except the names. This is the method I forgot.
async def openai_tools(self) -> list[ChatCompletionToolUnionParam]:
tools = (await self._client.list_tools()).tools
return [
{
"type": "function",
"function": {
"name": t.name,
"description": t.description or "",
"parameters": t.input_schema,
},
}
for t in tools
]
And call_tool, which runs any tool by name and returns its output as a string:
async def call_tool(self, name: str, args: dict[str, Any]) -> str:
return await self._call(name, args)
It’s a thin public wrapper around the client’s private _call method, so we keep what that method already does: joining the text blocks and raising ToolCallError when the server reports an error.
Because we subclass instead of copying, we inherit the rest of part 2 for free: the async with startup, the check that the server still has git_diff and git_commit, and the timeout handling. Nothing in this file mentions git_diff or git_commit.
One note on style. _client and _call are private by convention, and a subclass reaching into them is a mild smell. That’s another reason these two methods belong in the client class. For a tutorial series, subclassing let me show the gap and close it without rewriting part 2.
Checkpoint. This should print nothing. No output means the imports resolve:
uv run python -c "import git_tools_mcp_agent.mcp_tools"
Step 5: agent.py, the prompt and the loop
Start at the top with the imports and the system prompt:
import json
import sys
from typing import cast
from git_tools_mcp_client.exceptions import ClientError
from openai import AsyncOpenAI
from openai.types.chat import (
ChatCompletionAssistantMessageParam,
ChatCompletionMessageParam,
ChatCompletionToolUnionParam,
)
from git_tools_mcp_agent.mcp_tools import AgentGitToolsClient
SYSTEM_PROMPT = (
"You are a git assistant. Use the tools to inspect the staged changes "
"and commit them when asked. Always call git_diff before git_commit and "
"write a commit message that matches the real changes. "
"Never invent diff content."
)
DEFAULT_MAX_STEPS = 8
The prompt is short, but each sentence has a job. “Always call git_diff before git_commit” makes the model look before it writes, and “never invent diff content” discourages it from making up a message for changes it hasn’t seen. DEFAULT_MAX_STEPS is 8; I’ll explain that when we reach the loop.
Dispatch
dispatch runs one tool safely:
async def dispatch(git: AgentGitToolsClient, name: str, args: dict) -> str:
try:
return await git.call_tool(name, args)
except ClientError as e:
return f"error: {e}"
If a tool fails, say the model sends an empty commit message, we don’t crash. We catch the client error and return the error text as the tool’s result, so the model reads it in the next round and can fix its call.
Four things to know before the loop
Why there’s a loop at all. The model can’t run tools; it can only ask for one. We run the tool, and the model has to see the result before it decides what to do next, so one model call is never enough. For our default task it goes like this:
- We send the request, and the model replies “call
git_diff”. - We run it and send back the diff, and the model replies “call
git_commitwith this message”. - We run that and send back the result, and the model replies with plain text: done.
That’s three model calls, and only the last one has no tool request. The loop keeps going until the model answers without one.
Why we cap it. The model decides when to stop, not us. A confused model, and free models sometimes are, can keep asking for tools forever, for example by repeating the same malformed call. Every pass costs time, tokens and rate limit, and one of our tools makes real commits, so a cap guarantees the program ends. Eight leaves room for the normal three calls plus a few retries after a tool error, and a flag lets you change it.
What the model sends back. When it wants a tool, content is empty and tool_calls is filled in, with an id, a function name and arguments for each call. Two details matter for the code. arguments is a JSON string, not an object, so we have to parse it. And every call has an id that we send back with its result, in a message with the role tool.
How it ends. When the model is finished, the reply has text in content and no tool calls. So the stop condition is simply “no tool calls”.
The loop
The function takes the git client, the model client, the tool list, your prompt, a model name and the step limit. messages is the whole conversation: it starts with the system prompt and your request and grows every round. The model has no memory beyond this list, so we resend it each time. The cast is only there to keep the type checker happy.
async def agent_loop(
git: AgentGitToolsClient,
llm: AsyncOpenAI,
tools: list[ChatCompletionToolUnionParam],
user_prompt: str,
model: str,
max_steps: int,
) -> str:
messages = cast(
list[ChatCompletionMessageParam],
[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_prompt},
],
)
Each pass through the loop is one model round trip. We send the messages and the tool list, then append the assistant’s reply before doing anything else, because the API requires the tool results that follow to match an assistant message that asked for them. model_dump(exclude_none=True) turns the SDK object back into a plain dict. If there are no tool calls, we’re done and the text is the final answer.
for _ in range(max_steps):
resp = await llm.chat.completions.create(
model=model, messages=messages, tools=tools
)
msg = resp.choices[0].message
messages.append(
cast(ChatCompletionAssistantMessageParam, msg.model_dump(exclude_none=True))
)
if not msg.tool_calls:
return msg.content or ""
Otherwise, run each requested tool:
for call in msg.tool_calls:
if call.type != "function":
messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": f"error: unsupported tool call type: {call.type}",
}
)
continue
try:
raw = call.function.arguments
args = json.loads(raw or "{}") if isinstance(raw, str) else raw
except json.JSONDecodeError:
result = "error: arguments were not valid JSON"
else:
print(f"[tool] {call.function.name}({args})", file=sys.stderr)
result = await dispatch(git, call.function.name, args)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": result}
)
return "stopped: too many steps"
First a guard: if the call type isn’t function, we still answer it with an error message, because skipping any tool call makes the next API request fail. The arguments arrive as a JSON string, so we parse them, and if the JSON is malformed we report that back as a tool result and let the model retry instead of raising. If it parses, we print the call to standard error so you can watch the loop, then run it through dispatch. Either way, the result goes back as a tool message with the matching tool_call_id.
Logs go to standard error and the answer goes to standard out, so you can pipe the answer somewhere and still watch the calls.
And if we fall out of the loop without an answer, we return stopped: too many steps.
Checkpoint. Again, no output means success:
uv run python -c "import git_tools_mcp_agent.agent"
Step 6: cli.py, the command line
Most of this file is part 2 again. load_params, resolve_repo and ClientError come from the client library, so the MCP config file and the --repo flag behave exactly as before. Type the imports:
import argparse
import asyncio
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
from git_tools_mcp_client.config import load_params, resolve_repo
from git_tools_mcp_client.exceptions import ClientError
from openai import OpenAIError
from git_tools_mcp_agent.agent import DEFAULT_MAX_STEPS, agent_loop
from git_tools_mcp_agent.llm import DEFAULT_MODEL, make_llm
from git_tools_mcp_agent.mcp_tools import AgentGitToolsClient
Now parse_args. The prompt is optional: with none you get the default, “review and commit the staged changes”, and with one you can ask for something else. --repo is the repository the server operates on, so the agent isn’t tied to your current directory. --config, --server, --model, --max-steps and --timeout round out the options.
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
prog="git-tools-mcp-agent",
description="LLM agent that uses the git tools mcp server",
)
p.add_argument(
"prompt",
nargs="?",
default="Review my staged changes and commit them with a good message",
help="what to ask the agent (default: review and commit staged changes)",
)
p.add_argument(
"--repo", type=Path, default=Path("."), help="git repo to operate on"
)
p.add_argument(
"--config",
type=Path,
default=Path(os.environ.get("GIT_TOOLS_CONFIG", "mcp.json")),
help="MCP servers config (default: $GIT_TOOLS_CONFIG, else mcp.json)",
)
p.add_argument("--server", default="git-tools", help="server name in the config")
p.add_argument("--model", default=DEFAULT_MODEL, help="OpenRouter model id")
p.add_argument(
"--max-steps", type=int, default=DEFAULT_MAX_STEPS, help="max LLM round trips"
)
p.add_argument(
"--timeout", type=float, default=30.0, help="MCP request timeout in seconds"
)
return p.parse_args()
One thing to know: --timeout is parsed here but isn’t passed to the client in this version. Wiring it up makes a good exercise.
run is the whole program in a few lines. Build the model client, read the MCP config, start the server (async with launches the subprocess and shuts it down on exit), fetch the tools and run the loop:
async def run(args: argparse.Namespace) -> None:
llm = make_llm()
params = load_params(args.config, args.server, resolve_repo(args.repo))
async with AgentGitToolsClient(params) as git:
tools = await git.openai_tools()
print(
await agent_loop(git, llm, tools, args.prompt, args.model, args.max_steps)
)
And main. Load .env first, so the key is in the environment before anything reads it, then run the program. except* is Python’s exception group syntax. The async stack can raise several errors at once, as we saw in part 2, so we print each as one error line and exit with code 1 instead of dumping a traceback:
def main() -> None:
load_dotenv()
args = parse_args()
try:
asyncio.run(run(args))
except* (ClientError, OSError, OpenAIError) as eg:
for e in eg.exceptions:
print(f"error: {e}", file=sys.stderr)
sys.exit(1)
Step 7: __init__.py
One small file. __init__.py exports main, which is what the [project.scripts] entry points at:
from git_tools_mcp_agent.cli import main
__all__ = ["main"]
Checkpoint. If you see the help text with all the options, everything’s wired up:
uv run git-tools-mcp-agent --help
Step 8: run it
The agent makes real commits, so practise on a throwaway repo. Make an empty folder, initialise git, create a file and stage it, then come back to the project:
rm -rf /tmp/scratch && mkdir /tmp/scratch && cd /tmp/scratch
git init -q && echo "hello" > a.txt && git add a.txt
cd -
First, ask for something that doesn’t commit:
uv run git-tools-mcp-agent --repo /tmp/scratch "Show me the diff but don't commit"
Watch the [tool] lines on standard error: you should see a git_diff call, then the model’s answer. Each of those lines is a full round trip. The model decided to call something, your code ran it, and the result went back into the conversation.
Now the default. With no prompt it reviews and commits, so this time you should see the diff call, then the commit call, then the model’s final answer:
uv run git-tools-mcp-agent --repo /tmp/scratch
That’s the loop from earlier, running for real. And git log shows the commit the agent wrote:
git -C /tmp/scratch log --oneline
The model’s wording will differ from run to run, since openrouter/free can route to a different model each time.
Options
| Option | Default | Meaning |
|---|---|---|
prompt | review and commit staged changes | What to ask the agent |
--repo | . | Git repo the server works on |
--config | $GIT_TOOLS_CONFIG, else mcp.json | MCP servers config |
--server | git-tools | Server name in the config |
--model | openrouter/free | OpenRouter model id |
--max-steps | 8 | Maximum model round trips |
--timeout | 30.0 | Parsed, but not yet passed through |
When it goes wrong
error: OPENROUTER_API_KEY is not set; put it in .env or export it. The key isn’t reaching the program. Check that.envis in the project root and that the variable name is spelled exactly right.- The server fails to start. Check the absolute path in
mcp.json. It has to point at the folder where you cloned the server. - The agent loops, sends malformed arguments, or you hit a rate limit. That’s the free model. Pin a different one with
--model, or just try again. It’s the rough edge of a router that picks among free models. - uv complains about Python. Check that 3.14 is pinned.
Two rough edges
Model quality varies with the free router. And there’s no confirmation before committing: the agent commits as soon as the model asks, so only point it at repositories where that’s fine.
Challenge: add an approval step
Before the agent runs a call to git_commit, print the message and ask yes or no. If the answer is no, return an error string as the tool result so the model knows it was declined. You only need to touch dispatch. Post your solution in the comments on the video.
If you want more:
- Pass
--timeoutthrough to the client. - Add a retry with backoff for rate limits.
- Swap in a different MCP server. The agent needs no changes for that, only the config file.
Recap
- An agent is a loop around an API call and a list of functions.
- The model never runs anything. It asks, your code runs the tool, and the result goes back into the conversation.
- MCP tool definitions (name, description, input schema) map straight onto the model’s tool-calling format, so the agent holds no git-specific code.
- The loop ends when the model replies with no tool calls. A step limit guarantees it ends even when the model doesn’t cooperate.
- Tool errors go back to the model as text, which is what lets it fix its own calls.
- Malformed arguments go back the same way. Answer every tool call, even an unsupported one, or the next request fails.
- Logs go to standard error and the answer to standard out.
Across the series we built a server that exposes tools with descriptions a model can read, a client that connects, discovers, calls and handles errors with no model involved, and an agent that lets a model choose the calls, with a loop, a step limit and errors fed back as text.
Related posts
This is part 3. MCP Server in Python: Claude Can’t See Why Tools Fail builds the server, MCP Client in Python: Build One Without a Model builds the client this agent extends, and Who Actually Runs the Command? How AI Agents Work explains the agent loop in a more general setting.