Skip to content

FastMCP: Failed to serialize ToolContext to JSON Schema #2557

@xianhong1208

Description

@xianhong1208

I am attempting to expose a generate_image function as an MCP Server endpoint. During the setup, I've run into an issue where the ToolContext object fails to be serialized into a JSON Schema, which prevents the server from starting correctly.

from google.adk.tools.tool_context import ToolContext
from google.genai import Client
from google.genai import types
from mcp.server import FastMCP

Only Vertex AI supports image generation for now.

client = Client()

mcp = FastMCP("generate_image", host="0.0.0.0", port=5278)

@mcp.tool()
async def generate_image(prompt: str, tool_context: 'ToolContext') -> dict:
"""Generates an image based on the prompt."""
response = client.models.generate_images(
model='imagen-3.0-generate-002',
prompt=prompt,
config={'number_of_images': 1},
)
if not response.generated_images:
return {'status': 'failed'}
image_bytes = response.generated_images[0].image.image_bytes
await tool_context.save_artifact(
'image.png',
types.Part.from_bytes(data=image_bytes, mime_type='image/png'),
)
return {
'status': 'success',
'detail': 'Image generated successfully and stored in artifacts.',
'filename': 'image.png',
}

if name == "main":
mcp.run(transport="streamable-http")

Error:
raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.IsInstanceSchema (<class 'google.adk.tools.tool_context.ToolContext'>)

For further information visit https://errors.pydantic.dev/2.11/u/invalid-for-json-schema

Metadata

Metadata

Assignees

Labels

bot triaged[Bot] This issue is triaged by ADK botmcp[Component] Issues about MCP supporttools[Component] This issue is related to tools

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions