Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions py/samples/mcp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# MCP Sample

This sample demonstrates using the MCP (Model Context Protocol) plugin with Genkit Python SDK.

## Setup environment

Obtain an API key from [ai.dev](https://ai.dev).

Export the API key as env variable `GEMINI\_API\_KEY` in your shell
configuration.

### Run the MCP Client/Host
```bash
cd py/samples/mcp
genkit start -- uv run src/main.py
```

This will:
1. Connect to the configured MCP servers
2. Execute sample flows demonstrating tool usage
3. Clean up connections on exit

### Run the HTTP MCP Server
```bash
cd py/samples/mcp
genkit start -- uv run src/http_server.py
```

This will:
1. Start an MCP server over HTTP/SSE on port 3334.
2. Expose a test tool named test_http.

### Run the MCP Server
```bash
cd py/samples/mcp
genkit start -- uv run src/server.py
```

This starts an MCP server on stdio that other MCP clients can connect to.

## Requirements

- Python 3.10+
- `mcp` - Model Context Protocol Python SDK
- `genkit` - Genkit Python SDK
- `genkit-plugins-google-genai` - Google AI plugin for Genkit

## MCP Servers Used

The sample connects to these MCP servers (must be available):
- **mcp-server-git** - Install via `uvx mcp-server-git`
- **@modelcontextprotocol/server-filesystem** - Install via npm
- **@modelcontextprotocol/server-everything** - Install via npm

## Learn More

- [MCP Documentation](https://modelcontextprotocol.io/)
- [Genkit Python Documentation](https://firebase.google.com/docs/genkit)
- [MCP Plugin Source](../../plugins/mcp/)
40 changes: 40 additions & 0 deletions py/samples/mcp/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

[project]
dependencies = [
"genkit",
"genkit-plugin-google-genai",
"genkit-plugins-mcp",
"mcp",
]
description = "MCP sample application for Genkit Python SDK"
name = "mcp-sample"
readme = "README.md"
requires-python = ">=3.10"
version = "0.1.0"

[tool.uv.sources]
genkit = { workspace = true }
genkit-plugin-google-genai = { workspace = true }
genkit-plugins-mcp = { workspace = true }

[build-system]
build-backend = "hatchling.build"
requires = ["hatchling"]

[tool.hatch.build.targets.wheel]
packages = ["src"]
31 changes: 31 additions & 0 deletions py/samples/mcp/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

case "$1" in
server)
shift
exec genkit start -- uv run src/server.py "$@"
;;
http)
shift
exec genkit start -- uv run src/http_server.py "$@"
;;
*)
# Default to main.py
exec genkit start -- uv run src/main.py "$@"
;;
esac
96 changes: 96 additions & 0 deletions py/samples/mcp/src/http_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
HTTP MCP Server Example

This demonstrates creating an HTTP-based MCP server using SSE transport
with Starlette and the official MCP Python SDK.
"""

import asyncio
import logging

import mcp.types as types
import uvicorn
from mcp.server import Server
from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Mount, Route

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def main():
"""Start the HTTP MCP server."""

# Create SSE transport logic
# The endpoint '/mcp/' is where clients will POST messages
sse = SseServerTransport('/mcp/')

async def handle_sse(request):
"""Handle incoming SSE connections."""
async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using the private attribute request._send is not recommended as it relies on internal implementation details of Starlette's Request object. This could break with future updates to the library. It would be better to use a public API if one is available. If not, this reliance on an internal API should be documented with a comment.

read_stream, write_stream = streams

# Create a new server instance for this session
# This mirrors the JS logic of creating a new McpServer per connection
server = Server('example-server', version='1.0.0')

@server.list_tools()
async def list_tools() -> list[types.Tool]:
return [
types.Tool(
name='test_http',
description='Test HTTP transport',
inputSchema={'type': 'object', 'properties': {}},
)
]

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name == 'test_http':
# In this SSE implementation, valid session ID is internal
# but we can return a confirmation.
return [types.TextContent(type='text', text='Session Active')]
raise ValueError(f'Unknown tool: {name}')

# Run the server with the streams
await server.run(read_stream, write_stream, server.create_initialization_options())

# Return empty response after connection closes
return Response()

# Define routes
# GET /mcp -> Starts SSE stream
# POST /mcp/ -> Handles messages (via SseServerTransport)
routes = [
Route('/mcp', endpoint=handle_sse, methods=['GET']),
Mount('/mcp/', app=sse.handle_post_message),
]

app = Starlette(routes=routes)

config = uvicorn.Config(app, host='0.0.0.0', port=3334, log_level='info')
server = uvicorn.Server(config)

print('HTTP MCP server running on http://localhost:3334/mcp')
await server.serve()


if __name__ == '__main__':
asyncio.run(main())
Loading
Loading