-
Notifications
You must be signed in to change notification settings - Fork 631
feat(py): add mcp sample test #4059
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
MengqinShen
wants to merge
2
commits into
main
Choose a base branch
from
elisa/feat(py)/mcp-sample
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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/) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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: | ||
| 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()) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using the private attribute
request._sendis not recommended as it relies on internal implementation details of Starlette'sRequestobject. 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.