MCP is the standard protocol for exposing tools for AI agents usage. The MCP exposes APIs and the documentation for each API to the LLM. In this post we create a simple python based MCP server and use it in Gemini CLI.
Create The MCP Server
To prepare the MCP server project use:
# install UV in case it is not already installed
curl -LsSf https://astral.sh/uv/install.sh | sh
uv init magic_server
cd magic_server
uv venv
uv add "mcp[cli]"
Next we add our main.py and expose our tool:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Demo")
@mcp.tool(name="do_magic_trick")
def do_magic_trick(a: int, b: int) -> int:
return a + b + 6
mcp.run(transport="stdio")
#mcp.run(transport="streamable-http")
#mcp.run(transport="sse")
We can run the MCP as a local tool using STDIO for the lower level communication, or using SSE and streamable-http to connect to the server over the network.
Run Gemini CLI and MCP Server STDIO
npx https://github.com/google-gemini/gemini-cli
{
"selectedAuthType": "oauth-personal",
"mcpServers": {
"pythonTools": {
"command": "/home/my-user/.local/bin/uv",
"args": [
"run",
"main.py"
],
"cwd": "/home/my-user/magic_server",
"env": {
},
"timeout": 15000
}
}
}
Once we restart the gemini CLI it will run the MCP server to get the metadata of the exposed tools, and we can use the tools simple by using the prompt: "do the magic_trick for 5 and 6".
Run Gemini CLI and MCP Server Service
To expose the MCP server as a public tool, we need to run the MCP server over the network. For this we can use SSE and http-streaming, so update the main.py to use the relevant method.
Notice:
1. At this time gemini CLI supports only SSE, but it seems that http-streaming is the winning standard.
2. In case using TLS (HTTPS access) the server should use a valid TLS certificate.
To configure the gemini to use the tool over the network, update the file ~/.gemini/settings.json:
{
"selectedAuthType": "oauth-personal",
"mcpServers": {
"discoveredServer": {
"url": "http://localhost:8000/sse"
}
}
}
Unlike running MCP using the STDIO, in this case we need to run the MCP ourselves:
uv run main.py
No comments:
Post a Comment