@devries-cameron20 / composio Mirror · read-only / commits / 495be0f0f
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

fix(google): send tool schemas Gemini and Vertex accept (#4751)

## Summary Both Google providers put Composio's JSON Schema into `FunctionDeclaration.parameters`, which only accepts Google's OpenAPI subset. Composio tool schemas carry keywords outside it: `examples`, `const`, `human_parameter_name`, `file_uploadable`, `exclusiveMinimum`, `null` types, and integer enums. With `@composio/google`, Gemini answers 400 `Unknown name "examples"` for the default tools of every popular toolkit. With `composio_google`, `wrap_tool` raises `ParseError` before any request is sent, for 2,604 of 7,212 tools. The TypeScript provider now sends the schema through `parametersJsonSchema`, which takes JSON Schema as-is. The Python provider's `vertexai` `FunctionDeclaration` can only build `parameters`, so it now reduces each schema to the Vertex `Schema` subset. Designated PR reviewer: [@jkomyno](mailto:alberto@composio.dev). Fixes #4750 ## Changes - `ts/packages/providers/google/src/index.ts`: `wrapTool` emits `parametersJsonSchema` instead of `parameters`. The `$ref` dereferencing and the `required` and object-type normalization are unchanged. - `ts/packages/providers/google/package.json` and `pnpm-lock.yaml`: raise the `@google/genai` peer dependency to `^1.6.0`, the first release that supports `parametersJsonSchema` on function declarations. - `ts/packages/providers/google/test/*`: assert the new field, and add a regression test that `examples`, `const`, a `null` branch, and an integer enum reach `parametersJsonSchema` unchanged. - `python/providers/google/composio_google/provider.py`: replace the top-level `examples` strip with `_to_vertex_schema`. It drops unsupported keywords at every depth, maps `oneOf` to `anyOf`, a string `const` to a one-value `enum`, and a `null` type to `nullable`, and drops enums with non-string values. Property names are kept as-is. - `python/tests/test_google_provider.py`: a regression test built from keywords in real tool schemas. It fails on `next` with the `humanParameterName` `ParseError`. - A minor changeset for `@composio/google`, since the declaration field and the peer range change. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I have read and understand every line of this diff, including any LLM-generated code - [x] Any third-party docs links or promotional content follow the [third-party links policy](https://github.com/ComposioHQ/composio/blob/next/CONTRIBUTING.md#third-party-links-in-docs) - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests or explain why not applicable - [x] I added a changeset if this change affects published packages ## Additional context - Code that reads `wrapped.parameters` from `@composio/google` output now finds the schema in `wrapped.parametersJsonSchema`. Passing the declarations to `functionDeclarations` works as before. - I couldn't call Vertex AI itself. All 7,212 tools from 50 toolkits wrap on `google-cloud-aiplatform` 1.162.0 and 2.2.0, and the Gemini API's `parameters` field, which uses the same `Schema` message, accepted 202 converted schemas. - The Python `composio_gemini` provider is not affected: it hands `google-genai` Python callables instead of schemas. --------- Co-authored-by: jkomyno <alberto@composio.dev>

Tarun Vashishtha committed Nov 13, 2026 at 22:26 UTC 495be0f0f1f43fba9f6eb8248d351631d732af61
10 files changed +322 -36
.ast-grep/baseline.json
-6
@@ -335,12 +335,6 @@
335 "source": " parameters: inputParameters as unknown as {\n type: 'object';\n properties: {\n [key: string]: {\n type: string;\n description?: string;\n };\n };\n required: string[];\n },",
336 "count": 1
337 },
338 - {
339 - "ruleId": "ts-double-assertion",
340 - "file": "ts/packages/providers/google/src/index.ts",
341 - "source": " parameters: {\n type: 'object',\n description: tool.description || '',\n properties: inputParameters?.properties || {},\n required: inputParameters?.required || [],\n } as unknown as Schema,",
342 - "count": 1
343 - },
338 {
339 "ruleId": "ts-double-assertion",
340 "file": "ts/packages/providers/llamaindex/src/index.ts",
.changeset/google-parameters-json-schema.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/google': minor
3 +---
4 +
5 +Fix Gemini rejecting Composio tools with a 400 such as `Unknown name "examples"`. `wrapTool` and `wrapTools` now put each tool's schema in `parametersJsonSchema` instead of `parameters`, so JSON Schema keywords that Composio tools carry, such as `examples`, `const`, `null` types, and integer enums, reach Gemini intact. The `@google/genai` peer dependency now requires `^1.6.0`, the first release that supports `parametersJsonSchema` on function declarations.
.changeset/google-python-vertex-schema.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/python-sdk': patch
3 +---
4 +
5 +Fix `composio_google` raising `ParseError` while wrapping tools whose schemas use JSON Schema keywords outside the Vertex AI `Schema` subset, such as `human_parameter_name`, `examples`, `const`, `oneOf`, type lists, and non-string enums. `wrap_tool` now reduces each schema to that subset: it drops unsupported keywords, turns `oneOf` into `anyOf`, a `null` type or enum member into `nullable`, a string `const` into a one-value `enum`, and moves non-string enum values into the description.
pnpm-lock.yaml
+1 -1
@@ -1623,7 +1623,7 @@ importers:
1623 ts/packages/providers/google:
1624 dependencies:
1625 '@google/genai':
1626 - specifier: ^1.1.0
1626 + specifier: ^1.6.0
1627 version: 1.52.0(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7))
1628 devDependencies:
1629 '@composio/core':
python/providers/google/composio_google/provider.py
+127 -14
@@ -2,6 +2,7 @@
2 Google AI Python Gemini tool spec.
3 """
4
5 +import json
6 import typing as t
7
8 from proto.marshal.collections.maps import MapComposite
@@ -17,6 +18,125 @@ from composio.types import Modifiers, Tool, ToolExecutionResponse
18 from composio.utils.json_schema import dereference_json_schema
19 from composio.utils.shared import normalize_tool_arguments
20
21 +# Fields of the Vertex AI ``Schema`` message. ``FunctionDeclaration`` raises a
22 +# ``ParseError`` for any other keyword, and Composio schemas carry several, such
23 +# as ``examples``, ``const``, and ``human_parameter_name``.
24 +_VERTEX_SCHEMA_FIELDS = frozenset(
25 + "type format title description nullable default items minItems maxItems enum"
26 + " properties propertyOrdering required minProperties maxProperties minimum"
27 + " maximum minLength maxLength pattern example anyOf additionalProperties".split()
28 +)
29 +
30 +
31 +def _merge(base: t.Dict[str, t.Any], over: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
32 + """Merge two schema nodes; ``over`` wins, but property maps and required lists combine."""
33 + merged = {**base, **over}
34 + if isinstance(base.get("properties"), dict) and isinstance(
35 + over.get("properties"), dict
36 + ):
37 + merged["properties"] = {**base["properties"], **over["properties"]}
38 + if isinstance(base.get("required"), list) and isinstance(
39 + over.get("required"), list
40 + ):
41 + names = base["required"] + over["required"]
42 + merged["required"] = list(dict.fromkeys(n for n in names if isinstance(n, str)))
43 + return merged
44 +
45 +
46 +def _to_vertex_schema(schema: t.Any) -> t.Any:
47 + """Reduce a JSON Schema node to the subset the Vertex AI ``Schema`` accepts.
48 +
49 + Unsupported keywords are dropped, ``oneOf`` becomes ``anyOf``, a string
50 + ``const`` becomes a one-value ``enum``, ``null`` in ``type`` or ``enum`` becomes
51 + ``nullable``, several types become ``anyOf``, and the values of a
52 + non-string ``enum`` move into the description because Vertex only accepts
53 + string enums. ``anyOf`` is left as the only field of its node, as Vertex
54 + requires. Property names are kept as-is.
55 +
56 + Explicit loops keep each nesting level to one stack frame, so the depth cap
57 + in ``dereference_json_schema`` stays the binding limit.
58 + """
59 + if isinstance(schema, list):
60 + items = []
61 + for item in schema:
62 + items.append(_to_vertex_schema(item))
63 + return items
64 + if isinstance(schema, bool):
65 + # A boolean schema node (``items: true``, which MCP toolkits emit) has no
66 + # Vertex equivalent. ``{}`` keeps ``true``; ``false`` loosens to it too,
67 + # since Vertex cannot express "no value is valid".
68 + return {}
69 + if not isinstance(schema, dict):
70 + return schema
71 + node = dict(schema)
72 + if "oneOf" in node and "anyOf" not in node:
73 + node["anyOf"] = node.pop("oneOf")
74 + if isinstance(node.get("const"), str) and "enum" not in node:
75 + node["enum"] = [node["const"]]
76 + if "type" in node:
77 + types = node.pop("type")
78 + types = types if isinstance(types, list) else [types]
79 + non_null = [name for name in types if name != "null"]
80 + if len(non_null) < len(types):
81 + node["nullable"] = True
82 + if "anyOf" in node:
83 + # Vertex has no allOf: drop the branches whose single type the list
84 + # rules out, and keep the rest as they are.
85 + node["anyOf"] = [
86 + branch
87 + for branch in node["anyOf"]
88 + if not isinstance(branch, dict)
89 + or not isinstance(branch.get("type"), str)
90 + or branch["type"] in types
91 + ] or node["anyOf"]
92 + if len(non_null) == 1:
93 + node["type"] = non_null[0]
94 + elif non_null and "anyOf" not in node:
95 + node["anyOf"] = [{"type": name} for name in non_null]
96 + enum = node.get("enum")
97 + if isinstance(enum, list) and None in enum:
98 + node["nullable"] = True
99 + enum = node["enum"] = [v for v in enum if v is not None]
100 + if isinstance(enum, list) and not all(isinstance(v, str) for v in enum):
101 + del node["enum"]
102 + allowed = ", ".join(json.dumps(v) for v in enum)
103 + node["description"] = (
104 + f"{node.get('description', '')} Allowed values: {allowed}.".strip()
105 + )
106 + if "anyOf" in node:
107 + # Vertex rejects anyOf next to any other field: fold a single option
108 + # into the node, or copy the node's other fields into each option.
109 + options = []
110 + for option in node.pop("anyOf"):
111 + if isinstance(option, dict) and option.get("type") == "null":
112 + node["nullable"] = True
113 + elif isinstance(option, dict):
114 + options.append(option)
115 + if len(options) == 1:
116 + return _to_vertex_schema(_merge(options[0], node))
117 + if options:
118 + rest = _to_vertex_schema(node)
119 + flat = [] # a converted option may itself be a lone anyOf: inline it
120 + for option in _to_vertex_schema(options):
121 + flat.extend(option.get("anyOf", [option]))
122 + return {"anyOf": [_merge(rest, option) for option in flat]}
123 +
124 + result: t.Dict[str, t.Any] = {}
125 + for key, value in node.items():
126 + if key not in _VERTEX_SCHEMA_FIELDS:
127 + continue
128 + if key == "properties" and isinstance(value, dict):
129 + properties = {}
130 + for name, prop in value.items():
131 + properties[name] = _to_vertex_schema(prop)
132 + value = properties
133 + elif key in ("items", "anyOf") or (
134 + key == "additionalProperties" and not isinstance(value, bool)
135 + ):
136 + value = _to_vertex_schema(value)
137 + result[key] = value
138 + return result
139 +
140
141 def _convert_map_composite(obj):
142 if isinstance(obj, MapComposite):
@@ -40,23 +160,16 @@ class GoogleProvider(
160 tool.input_parameters,
161 on_unresolved="sentinel",
162 )
43 - # Clean up properties by removing 'examples' field
44 - properties = t.cast(
45 - dict[str, dict],
46 - input_parameters.get("properties", {}),
47 - )
48 - cleaned_properties = {
49 - prop_name: {k: v for k, v in prop_schema.items() if k != "examples"}
50 - for prop_name, prop_schema in properties.items()
51 - }
163 return FunctionDeclaration(
164 name=tool.slug,
165 description=tool.description,
55 - parameters={
56 - "type": "object",
57 - "properties": cleaned_properties,
58 - "required": input_parameters.get("required", []),
59 - },
166 + parameters=_to_vertex_schema(
167 + {
168 + "type": "object",
169 + "properties": input_parameters.get("properties", {}),
170 + "required": input_parameters.get("required", []),
171 + }
172 + ),
173 )
174
175 def wrap_tools(self, tools: t.Sequence[Tool]) -> list[FunctionDeclaration]:
python/tests/test_google_provider.py
+146
@@ -40,6 +40,152 @@ def test_wrap_tool_dereferences_internal_refs() -> None:
40 assert message_schema["properties"]["subject"]["type"] == "STRING"
41
42
43 +def test_wrap_tool_drops_keywords_vertex_rejects() -> None:
44 + """Composio schema keywords outside the Vertex ``Schema`` must not raise."""
45 + tool = Tool.model_construct(
46 + slug="TEST_KEYWORDS",
47 + description="test",
48 + input_parameters={
49 + "type": "object",
50 + "properties": {
51 + "query": {
52 + "type": "string",
53 + "examples": ["is:unread"],
54 + "human_parameter_name": "Search query",
55 + "human_parameter_description": "What to search for",
56 + },
57 + "kind": {"type": "string", "const": "message"},
58 + "status": {
59 + "type": ["string", "null"],
60 + "enum": ["open", "closed", None],
61 + },
62 + "page_token": {
63 + "description": "Next page",
64 + "anyOf": [
65 + {"type": "string", "examples": ["abc"]},
66 + {"type": "null"},
67 + ],
68 + },
69 + "amount": {
70 + "description": "Amount",
71 + "anyOf": [
72 + {"type": "string"},
73 + {"anyOf": [{"type": "integer"}, {"type": "number"}]},
74 + ],
75 + },
76 + "flag": {
77 + "type": ["string", "null"],
78 + "anyOf": [{"type": "string"}, {"type": "boolean"}],
79 + },
80 + "shape": {
81 + "type": "object",
82 + "properties": {"kind": {"type": "string"}},
83 + "required": ["kind"],
84 + "oneOf": [
85 + {"properties": {"r": {"type": "number"}}, "required": ["r"]},
86 + {
87 + "properties": {"side": {"type": "number"}},
88 + "required": ["side"],
89 + },
90 + ],
91 + },
92 + "direction": {"type": "null"},
93 + "label": {"type": ["string", "null"]},
94 + "value": {"type": ["string", "integer"]},
95 + "id": {
96 + "type": ["string", "integer"],
97 + "anyOf": [
98 + {"type": ["string"], "enum": ["yes"]},
99 + {"type": "boolean"},
100 + ],
101 + },
102 + "format": {"type": "integer", "enum": [0, 1], "exclusiveMinimum": -1},
103 + "target": {
104 + "oneOf": [
105 + {"type": "object", "properties": {"id": {"type": "string"}}},
106 + {"type": "string"},
107 + ]
108 + },
109 + # A property may be named like a schema keyword.
110 + "description": {"type": "string", "file_uploadable": True},
111 + },
112 + "required": ["query"],
113 + },
114 + )
115 +
116 + parameters = GoogleProvider().wrap_tool(tool).to_dict()["parameters"]
117 + properties = parameters["properties"]
118 +
119 + assert properties["query"] == {"type": "STRING"}
120 + assert properties["kind"] == {"type": "STRING", "enum": ["message"]}
121 + assert properties["status"] == {
122 + "type": "STRING",
123 + "nullable": True,
124 + "enum": ["open", "closed"],
125 + }
126 + assert properties["page_token"] == {
127 + "type": "STRING",
128 + "description": "Next page",
129 + "nullable": True,
130 + }
131 + assert properties["amount"] == {
132 + "any_of": [
133 + {"type": "STRING", "description": "Amount"},
134 + {"type": "INTEGER", "description": "Amount"},
135 + {"type": "NUMBER", "description": "Amount"},
136 + ]
137 + }
138 + assert properties["flag"] == {"type": "STRING", "nullable": True}
139 + shapes = properties["shape"]["any_of"]
140 + assert [sorted(s["properties"]) for s in shapes] == [
141 + ["kind", "r"],
142 + ["kind", "side"],
143 + ]
144 + assert [s["required"] for s in shapes] == [["kind", "r"], ["kind", "side"]]
145 + assert properties["direction"] == {"nullable": True}
146 + assert properties["label"] == {"type": "STRING", "nullable": True}
147 + assert properties["value"]["any_of"] == [{"type": "STRING"}, {"type": "INTEGER"}]
148 + assert properties["id"] == {"type": "STRING", "enum": ["yes"]}
149 + assert properties["format"] == {
150 + "type": "INTEGER",
151 + "description": "Allowed values: 0, 1.",
152 + }
153 + assert len(properties["target"]["any_of"]) == 2
154 + assert properties["description"] == {"type": "STRING"}
155 +
156 + # Vertex rejects a schema that sets any other field next to any_of.
157 + def any_of_stands_alone(node: Any) -> bool:
158 + if isinstance(node, list):
159 + return all(any_of_stands_alone(item) for item in node)
160 + if not isinstance(node, dict):
161 + return True
162 + if "any_of" in node and len(node) > 1:
163 + return False
164 + return all(any_of_stands_alone(value) for value in node.values())
165 +
166 + assert any_of_stands_alone(parameters)
167 +
168 +
169 +def test_wrap_tool_accepts_boolean_schema_nodes() -> None:
170 + """MCP toolkits emit ``items: true``, which Vertex has no field for."""
171 + tool = Tool.model_construct(
172 + slug="TEST_BOOLEAN_NODE",
173 + description="test",
174 + input_parameters={
175 + "type": "object",
176 + "properties": {
177 + "params": {"type": ["null", "array"], "items": True},
178 + "options": {"type": "object", "additionalProperties": True},
179 + },
180 + },
181 + )
182 +
183 + properties = GoogleProvider().wrap_tool(tool).to_dict()["parameters"]["properties"]
184 +
185 + assert properties["params"] == {"type": "ARRAY", "nullable": True, "items": {}}
186 + assert properties["options"]["type"] == "OBJECT"
187 +
188 +
189 def _function_call_response() -> Any:
190 return GenerationResponse.from_dict(
191 {
ts/packages/providers/google/package.json
+1 -1
@@ -47,7 +47,7 @@
47 "license": "ISC",
48 "peerDependencies": {
49 "@composio/core": ">=0.16.0 <1.0.0 || >=1.0.0-beta.0 <1.0.0",
50 - "@google/genai": "^1.1.0"
50 + "@google/genai": "^1.6.0"
51 },
52 "devDependencies": {
53 "@composio/core": "workspace:*",
ts/packages/providers/google/src/index.ts
+6 -3
@@ -22,7 +22,7 @@ import {
22 dereferenceJsonSchema,
23 ensureObjectTypeOnProperties,
24 } from '@composio/core';
25 -import { FunctionDeclaration, Schema } from '@google/genai';
25 +import { FunctionDeclaration } from '@google/genai';
26
27 /**
28 * Interface for Google GenAI function declaration
@@ -143,12 +143,15 @@ export class GoogleProvider extends BaseNonAgenticProvider<
143 return {
144 name: tool.slug,
145 description: tool.description || '',
146 - parameters: {
146 + // Composio schemas are JSON Schema and carry keywords such as `examples`
147 + // and `const`. The OpenAPI-subset `parameters` field rejects those with a
148 + // 400, so send them through `parametersJsonSchema` instead.
149 + parametersJsonSchema: {
150 type: 'object',
151 description: tool.description || '',
152 properties: inputParameters?.properties || {},
153 required: inputParameters?.required || [],
151 - } as unknown as Schema,
154 + },
155 };
156 }
157
ts/packages/providers/google/test/google-ref.test.ts
+3 -5
@@ -1,9 +1,7 @@
1 /**
2 * Regression test: `GoogleProvider.wrapTool` rebuilds the root schema from
3 * `properties`/`required`, which used to discard the `$defs` block while
4 - * `$ref` pointers inside `properties` stayed dangling. The Google GenAI
5 - * `Schema` type has no `ref`/`defs` field, so a `$ref` on the `parameters`
6 - * path is unrepresentable and the API answers 400. `wrapTool` now
4 + * `$ref` pointers inside `properties` stayed dangling. `wrapTool` now
5 * dereferences `$ref`/`$defs` before the rebuild.
6 */
7
@@ -91,8 +89,8 @@ describe('GoogleProvider regression: $ref in JSON Schema', () => {
89 it('inlines internal $ref/$defs instead of stranding a dangling pointer', () => {
90 const wrapped = provider.wrapTool(refTool);
91
94 - expect(containsInternalRef(wrapped.parameters)).toBe(false);
95 - expect(wrapped.parameters?.required).toContain('message');
92 + expect(containsInternalRef(wrapped.parametersJsonSchema)).toBe(false);
93 + expect((wrapped.parametersJsonSchema as { required: string[] }).required).toContain('message');
94 });
95
96 it('does not throw when $ref points into an undeclared $defs block', () => {
ts/packages/providers/google/test/google.test.ts
+28 -6
@@ -56,7 +56,7 @@ describe('GoogleProvider', () => {
56 expect(wrapped).toEqual({
57 name: mockTool.slug,
58 description: mockTool.description,
59 - parameters: {
59 + parametersJsonSchema: {
60 type: 'object',
61 description: mockTool.description,
62 properties: mockTool.inputParameters?.properties || {},
@@ -76,7 +76,7 @@ describe('GoogleProvider', () => {
76 expect(wrapped).toEqual({
77 name: toolWithoutParams.slug,
78 description: toolWithoutParams.description,
79 - parameters: {
79 + parametersJsonSchema: {
80 type: 'object',
81 description: toolWithoutParams.description,
82 properties: {},
@@ -94,7 +94,7 @@ describe('GoogleProvider', () => {
94 },
95 });
96
97 - expect(wrapped.parameters?.required).toEqual(['input']);
97 + expect((wrapped.parametersJsonSchema as { required: string[] }).required).toEqual(['input']);
98 });
99
100 it('normalizes nested object schemas without treating property maps as schemas', () => {
@@ -110,7 +110,7 @@ describe('GoogleProvider', () => {
110 },
111 });
112
113 - const params = wrapped.parameters as unknown as {
113 + const params = wrapped.parametersJsonSchema as {
114 properties: Record<string, unknown>;
115 };
116 expect(params.properties).toEqual({
@@ -121,6 +121,28 @@ describe('GoogleProvider', () => {
121 });
122 expect(params.properties).not.toHaveProperty('type');
123 });
124 +
125 + it('sends JSON Schema keywords through parametersJsonSchema, not parameters', () => {
126 + // Gemini answers 400 ("Unknown name \"examples\"") when these keywords
127 + // are sent in the OpenAPI-subset `parameters` field.
128 + const properties = {
129 + query: { type: 'string', examples: ['is:unread'] },
130 + kind: { type: 'string', const: 'message' },
131 + page_token: { anyOf: [{ type: 'string' }, { type: 'null' }], default: null },
132 + format: { type: 'integer', enum: [0, 1] },
133 + };
134 + const wrapped = provider.wrapTool({
135 + ...mockTool,
136 + inputParameters: { type: 'object', properties, required: ['query'] },
137 + });
138 +
139 + expect(wrapped.parametersJsonSchema).toEqual({
140 + type: 'object',
141 + description: mockTool.description,
142 + properties,
143 + required: ['query'],
144 + });
145 + });
146 });
147
148 describe('wrapTools', () => {
@@ -139,7 +161,7 @@ describe('GoogleProvider', () => {
161 expect(wrapped[0]).toEqual({
162 name: mockTool.slug,
163 description: mockTool.description,
142 - parameters: {
164 + parametersJsonSchema: {
165 type: 'object',
166 description: mockTool.description,
167 properties: mockTool.inputParameters?.properties || {},
@@ -150,7 +172,7 @@ describe('GoogleProvider', () => {
172 expect(wrapped[1]).toEqual({
173 name: anotherTool.slug,
174 description: anotherTool.description,
153 - parameters: {
175 + parametersJsonSchema: {
176 type: 'object',
177 description: anotherTool.description,
178 properties: anotherTool.inputParameters?.properties || {},