Skip to content

feat: type stub return values and escape docstrings - #28

Merged
benclarkeio merged 5 commits into
mainfrom
claude/quirky-turing-jbsmjg
Nov 8, 2026
Merged

benclarkeio merged 5 commits into
mainfrom
claude/quirky-turing-jbsmjg

Conversation

@benclarkeio

@benclarkeio benclarkeio commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

First of two stacked PRs. This one changes the generated stubs and what MCP calls return; the catalog follows in #29.

Changes

  • Return types: each stub's return type now comes from the declaration's response_json_schema, or from an MCP tool's outputSchema, which is read from the tool directly so it no longer needs ADK's JSON_SCHEMA_FOR_FUNC_DECL flag. Stubs no longer all return -> Any.
    • Objects with properties become TypedDict classes. Arrays become list[...], prefixItems included, since JSON arrays reach code as lists. Open maps become dict[str, ...]. Unions and nullables are kept. Anything unrepresentable becomes Any, and so does a tool with no schema.
    • $ref into $defs/definitions is resolved, including recursive references.
  • Shared types: identical shapes get one class across all the tools in a module. The catalog in feat: show return types in the catalog and point the names tier at stubs #29 can then define each shape once. Each stub file still carries every class its tool uses, so it reads on its own.
    • A $ref class is shared only when the definitions it reaches match, so two tools whose $defs differ don't share one.
    • The exception is an untitled top-level object, which stays the tool's own <Tool>Response. Otherwise a tool could return a class named after a different tool.
  • Names: a class is named after its $defs key or title, else the property holding it (Guest, BookingsItem).
    • If a different shape already has that name, the parent's name is prefixed; if that's taken too, a number is added.
    • Names that would shadow the stub's imports or a tool in the module are skipped.
  • Required keys: if the schema lists no required keys, the class is total=False. Otherwise only the keys it leaves out get NotRequired[...]. NotRequired is imported under TYPE_CHECKING, so stubs still import on the sandbox's 3.10 floor.
  • Odd keys: keys that aren't identifiers (first-name, class) use the functional TypedDict(...) syntax.
  • MCP results: ADK's McpTool returns the whole CallToolResult. When the tool declares an outputSchema, code now gets structuredContent alone, so the result matches the declared type.
    • The MCP spec requires structuredContent to match the outputSchema, and the content block is meant to be a serialised copy of it.
    • The unwrap happens after the after-tool callbacks, so callbacks still see ADK's result. Tools without an outputSchema are unchanged.
    • The saved tool-result artifact holds structuredContent too, so reloading it gives what the call returned. The large-result threshold measures that value.
  • Positional parameter: a tool with exactly one required parameter takes it positionally or by keyword, so load_artifact("x", version=2) works. All other parameters stay keyword-only.
  • Escaping: _format_docstring now escapes backslashes and """, so docstrings containing pattern regexes no longer raise SyntaxWarning.

Tests

  • Every generated stub compiles with warnings treated as errors, using descriptions, patterns, enums, examples and response keys full of backslashes, quotes and regexes. This test fails if the escaping is reverted.
  • The single-required-parameter stub is executed and called both positionally and by keyword.
  • A real ADK McpTool with an outputSchema produces the expected TypedDicts without the feature flag, and its stub runs.
  • Shared shapes across tools; $ref classes split when the tools' $defs differ; a clash qualified by the parent's name; $defs and title naming with a recursive $ref; top-level types kept per tool while top-level array items are shared; names avoiding imports and tool names.
  • The dispatcher returns structuredContent for an MCP tool with an outputSchema, through the result wrapper, while callbacks see the full result. The saved artifact holds structuredContent. Without an outputSchema the full result is returned.
  • A prefixItems array return type is a list.

ruff, mypy and pytest all pass (233 tests).

🤖 Generated with Claude Code

https://claude.ai/code/session_013TYQ7CMpjWGGd4WWTt2Czk

- Build each stub's return type from `response_json_schema`: objects become
  `TypedDict` classes in the stub module, arrays `list[...]`, the rest `Any`
- Let a tool with exactly one required parameter take it positionally
- Escape backslashes and `"""` in generated docstrings so regex patterns
  no longer raise `SyntaxWarning`

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013TYQ7CMpjWGGd4WWTt2Czk
- Hand code an MCP tool's `structuredContent` when it declares an
  `outputSchema`, after callbacks have seen ADK's result
- Read MCP return types from the tool's `outputSchema`, so they no longer
  need ADK's JSON-schema feature flag
- Give identical shapes one `TypedDict` across a module's tools
- Name classes after their `$defs` key or `title`, else the property
  holding them; qualify by parent, then number, on a clash
- Resolve `$ref` into `$defs`/`definitions`, including recursive refs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013TYQ7CMpjWGGd4WWTt2Czk
- Name it `<Tool>Response` rather than reusing another tool's identical
  shape, which named it after whichever tool sorted first

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013TYQ7CMpjWGGd4WWTt2Czk
- Only an untitled top-level object stays per tool; array items are
  entities like any nested object

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013TYQ7CMpjWGGd4WWTt2Czk
@benclarkeio

Copy link
Copy Markdown
Contributor Author
  • [P2] Keep typed MCP results consistent when saved and reloaded. The artifact wrapper saves the envelope before the dispatcher unwraps it. A successful lookup() returns {"id": "item-1"}, but the JSON artifact has that value under structuredContent. After feat!: return full tool results and artifact content to the code #27, load_artifact returns that envelope, so code using ["id"] on the saved result fails. With feat: type stub return values and escape docstrings #28 alone, an envelope over the existing 50,000-character threshold is also replaced before the dispatcher can unwrap it, so the typed stub returns the artifact notice. Unwrap point
  • [P2] Include the owning schema when sharing referenced types. Give two tools the same Envelope definition containing item: {"$ref": "#/$defs/Item"}. Let the first tool's Item.id be a string and the second's an integer. Rendering both in one module gives both id: str. Rendering the second alone correctly gives id: int. The cache keys the unresolved target without the definitions it refers to. Reference cache key
  • [P2] Remove the test's dependency on the constructor argument deleted by feat!: return full tool results and artifact content to the code #27. The new dispatcher test passes large_result_threshold. With both diffs applied it raises TypeError before reaching the assertions. Its fixture already fits the default threshold on main. Test setup
  • [P2] Advertise JSON arrays as lists. A response with two integer prefixItems and items: false renders as tuple[int, int], but the sandbox receives a list. The response renderer falls through to the parameter formatter for this schema. Array handling
  • [P3] Preserve optional keys in runtime type metadata. For a response with required id and optional next, the stub imports on Python 3.10–3.13, but __required_keys__ includes both fields and typing.get_type_hints(..., include_extras=True) raises NameError for NotRequired. Generated import

One interaction with google/adk-python#8033 when its response-schema option is enabled. A declared text/plain success can become -> str here, while the REST tool returns {"text": ...} for the plain-text body. Schema selection · REST return path

- Save an MCP tool's `structuredContent` as its artifact, so reloading it
  gives what the call returned. The size threshold measures that value too.
- Key shared `$ref` classes by the definitions they reach, so two tools
  whose `$defs` differ no longer share one class.
- Render `prefixItems` arrays as `list[...]`, since JSON arrays reach code
  as lists.
- Pass `mcp_results` the unwrapped tool, avoiding a circular import.
- Drop `large_result_threshold` from the dispatcher test; its fixture fits
  the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@benclarkeio

Copy link
Copy Markdown
Contributor Author

Addressed in f553235:

On google/adk-python#8033: that link is to the older head b1c193a. The current head (776420e) declares text responses as {"text": str}, matching what RestApiTool returns.

@benclarkeio
benclarkeio merged commit dcb15ab into main Nov 8, 2026
6 checks passed
@benclarkeio
benclarkeio deleted the claude/quirky-turing-jbsmjg branch November 8, 2026 13:18
benclarkeio pushed a commit that referenced this pull request Nov 8, 2026
- Take main's stubs, dispatcher and MCP result handling from #28 and #27
- Keep this branch's per-module catalog rendering

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013TYQ7CocX3w8EpGvN7Heip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants