Skip to content
Open
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
65 changes: 65 additions & 0 deletions samples/mcp-server-hello/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# MCP server hello

A Genkit app's tools, served to any MCP client over stdio.

`src/main.py` is a bookshop app with three tools: `opening_hours`,
`search_books` and `check_stock`. It defines no model, so nothing here needs an
API key. `src/client.py` launches it and uses it with the MCP SDK's own
client, the way Claude Desktop, an IDE or another agent would.

```bash
uv sync
uv run src/client.py
```

```
Connected to bookshop: Ask about books, stock and opening hours.
Tools:
check_stock: Say how many copies of a title are on the shelf.
opening_hours: Report the shop's opening hours for a day of the week.
search_books: List the titles the shop carries on a topic.
opening_hours({'name': 'Sunday'}) [ok]: closed
search_books({'topic': 'fantasy'}) [ok]: {'titles': ['The Hobbit', 'A Wizard of Earthsea']}
check_stock({'title': 'Dune'}) [ok]: {'title': 'Dune', 'copies': 1}
check_stock({'title': 'Ulysses'}) [error]: NOT_FOUND: We do not carry 'Ulysses'
```

To use it from another MCP client, give the client this command, run from this
folder:

```bash
uv run src/main.py
```

## What it shows

`create_mcp_server(ai, 'bookshop')` wraps the app and registers nothing. The
tools it serves are the ones defined with `@ai.tool()`, read again on every
`tools/list`. `server.start()` serves on stdin and stdout until the client
closes stdin.

MCP arguments are always an object, so each tool takes a Pydantic model and a
client sends that model's fields: `{'title': 'Dune'}`, not
`{'book': {'title': 'Dune'}}`. A tool that takes a bare `str` is not served.

`search_books` and `check_stock` return models, so they advertise an output
schema and answer with structured content. `opening_hours` returns a string,
which arrives as text.

`check_stock` raises a `PublicError` for a title the shop does not carry. The
client gets an error result with its status and message. Any other
`GenkitError` sends only `Tool 'check_stock' failed: <status>`, and any other
exception `Tool 'check_stock' failed`, since their text can carry a URL or a
credential.

stdout is the wire, so the server logs to stderr. The client passes the
server's stderr through, which is why the failed `check_stock` call prints a
traceback above the client's output.

## Tests

The tests launch the real server and drive it with the MCP SDK client:

```bash
uv run pytest samples/mcp-server-hello --no-cov # from the repo root
```
17 changes: 17 additions & 0 deletions samples/mcp-server-hello/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[project]
name = "mcp-server-hello"
version = "0.2.0"
requires-python = ">=3.10"
dependencies = [
"genkit",
"genkit-mcp",
"mcp>=1.26.0,<2",
"pydantic>=2.10.5",
]

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

[tool.hatch.build.targets.wheel]
packages = ["src"]
61 changes: 61 additions & 0 deletions samples/mcp-server-hello/src/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# 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

"""Launch the bookshop server and use it the way any MCP client would."""

import asyncio
import sys
from pathlib import Path
from typing import Any

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.types import CallToolResult, TextContent

SERVER = StdioServerParameters(command=sys.executable, args=[str(Path(__file__).with_name('main.py'))])


def describe(result: CallToolResult) -> str:
"""Show a result's structured content when it has some, else its text."""
if result.structuredContent is not None:
return str(result.structuredContent)
return ' '.join(block.text for block in result.content if isinstance(block, TextContent))


async def call(session: ClientSession, tool: str, arguments: dict[str, Any]) -> None:
result = await session.call_tool(tool, arguments)
status = 'error' if result.isError else 'ok'
print(f'{tool}({arguments}) [{status}]: {describe(result)}')


async def main() -> None:
async with stdio_client(SERVER) as (read_stream, write_stream), ClientSession(read_stream, write_stream) as session:
info = await session.initialize()
print(f'Connected to {info.serverInfo.name}: {info.instructions}')

print('Tools:')
for tool in (await session.list_tools()).tools:
print(f' {tool.name}: {tool.description}')

# The arguments are the fields of the tool's input model, not the Python parameter name.
await call(session, 'opening_hours', {'name': 'Sunday'})
await call(session, 'search_books', {'topic': 'fantasy'})
await call(session, 'check_stock', {'title': 'Dune'})
await call(session, 'check_stock', {'title': 'Ulysses'})


if __name__ == '__main__':
asyncio.run(main())
84 changes: 84 additions & 0 deletions samples/mcp-server-hello/src/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# 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

"""A Genkit app's tools, served to MCP clients over stdio."""

import asyncio

from genkit_mcp import create_mcp_server
from pydantic import BaseModel

from genkit import Genkit, PublicError

ai = Genkit()

# Title: (topic, copies on the shelf).
BOOKS = {
'The Hobbit': ('fantasy', 3),
'A Wizard of Earthsea': ('fantasy', 0),
'Dune': ('science fiction', 1),
}
HOURS = {'saturday': '9am to 6pm', 'sunday': 'closed'}


# MCP arguments are always an object, so every tool takes a model rather than a bare string.
class Day(BaseModel):
name: str


class Topic(BaseModel):
topic: str


class Title(BaseModel):
title: str


class Results(BaseModel):
titles: list[str]


class Stock(BaseModel):
title: str
copies: int


@ai.tool()
async def opening_hours(day: Day) -> str:
"""Report the shop's opening hours for a day of the week."""
return HOURS.get(day.name.lower(), '10am to 7pm')


@ai.tool()
async def search_books(query: Topic) -> Results:
"""List the titles the shop carries on a topic."""
return Results(titles=[title for title, (topic, _) in BOOKS.items() if topic == query.topic.lower()])


@ai.tool()
async def check_stock(book: Title) -> Stock:
"""Say how many copies of a title are on the shelf."""
if book.title not in BOOKS:
# A PublicError's message reaches the client; any other exception's text does not.
raise PublicError('NOT_FOUND', f'We do not carry {book.title!r}')
_, copies = BOOKS[book.title]
return Stock(title=book.title, copies=copies)


server = create_mcp_server(ai, 'bookshop', instructions='Ask about books, stock and opening hours.')

if __name__ == '__main__':
asyncio.run(server.start())
103 changes: 103 additions & 0 deletions samples/mcp-server-hello/tests/mcp_server_hello_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# 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

"""The sample's server, launched as a child process and driven by the MCP SDK's own client."""

import asyncio
import os
import sys
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path

import pytest
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.types import TextContent

SRC = Path(__file__).resolve().parents[1] / 'src'

# Every await on the child process is bounded by this, so a hang fails the test instead.
LIMIT = 60


@asynccontextmanager
async def bookshop() -> AsyncIterator[ClientSession]:
"""Launch the sample's server and open an initialized session on it."""
server = StdioServerParameters(command=sys.executable, args=[str(SRC / 'main.py')])
# The server logs to stderr, including a traceback for the stock lookup that fails on purpose.
with open(os.devnull, 'w') as errlog:
async with (
stdio_client(server, errlog=errlog) as (read_stream, write_stream),
ClientSession(read_stream, write_stream) as session,
):
await asyncio.wait_for(session.initialize(), timeout=LIMIT)
yield session


@pytest.mark.asyncio
async def test_lists_every_tool_with_an_object_input() -> None:
"""All three tools are listed, each taking the fields of its input model."""
async with bookshop() as session:
tools = {tool.name: tool for tool in (await asyncio.wait_for(session.list_tools(), timeout=LIMIT)).tools}

assert sorted(tools) == ['check_stock', 'opening_hours', 'search_books']
assert tools['opening_hours'].inputSchema['properties'].keys() == {'name'}
assert tools['check_stock'].inputSchema['required'] == ['title']
assert tools['check_stock'].outputSchema is not None
assert tools['check_stock'].outputSchema['properties'].keys() == {'title', 'copies'}


@pytest.mark.asyncio
async def test_a_typed_output_arrives_as_structured_content() -> None:
"""A tool returning a model answers with that model's fields."""
async with bookshop() as session:
result = await asyncio.wait_for(session.call_tool('check_stock', {'title': 'Dune'}), timeout=LIMIT)

assert not result.isError
assert result.structuredContent == {'title': 'Dune', 'copies': 1}


@pytest.mark.asyncio
async def test_a_public_error_reaches_the_client_as_an_error_result() -> None:
"""The client reads the error's status and message, and the session stays usable."""
async with bookshop() as session:
failed = await asyncio.wait_for(session.call_tool('check_stock', {'title': 'Ulysses'}), timeout=LIMIT)
after = await asyncio.wait_for(session.call_tool('opening_hours', {'name': 'Sunday'}), timeout=LIMIT)

assert failed.isError
assert [block.text for block in failed.content if isinstance(block, TextContent)] == [
"NOT_FOUND: We do not carry 'Ulysses'"
]
assert [block.text for block in after.content if isinstance(block, TextContent)] == ['closed']


@pytest.mark.asyncio
async def test_the_client_script_runs_against_the_server() -> None:
"""`src/client.py` connects, lists the tools and prints each call's answer."""
process = await asyncio.create_subprocess_exec(
sys.executable,
str(SRC / 'client.py'),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
stdout, _ = await asyncio.wait_for(process.communicate(), timeout=LIMIT)
lines = stdout.decode().splitlines()

assert process.returncode == 0
assert lines[0] == 'Connected to bookshop: Ask about books, stock and opening hours.'
assert "search_books({'topic': 'fantasy'}) [ok]: {'titles': ['The Hobbit', 'A Wizard of Earthsea']}" in lines
assert "check_stock({'title': 'Ulysses'}) [error]: NOT_FOUND: We do not carry 'Ulysses'" in lines
20 changes: 20 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading