From 1df2a1d9ee30645a66ab46082c70ae347c967840 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 3 Nov 2026 11:24:21 -0500 Subject: [PATCH 1/3] Pre-release review fixes: utcp core (#4) - Deeply nested tool schemas parse again: JsonSchema.fromJson no longer recurses, so a 50,000-deep `inputs` cannot overflow the stack and crash UtcpClient.create. - A millisecond field that overflows to infinity (`"timeout": 1e306`) throws a FormatException naming the field instead of UnsupportedError. - `http` sends a GET with its body, as the Python and TypeScript SDKs do; `streamable_http` still rejects it, as TypeScript does. A null body argument means no body everywhere. buildToolRequest takes a GetWithBody instead of postWithBody. - Null `const` and `default` are dropped like every other null keyword. - Tests pin the OAuth2 same-origin 401 guard, the stale-token eviction check and the string `expires_in` cache lifetime. - CHANGELOG marks the HTTP result and VariableLoader.toJson changes as breaking. --- packages/utcp/CHANGELOG.md | 10 +- packages/utcp/lib/src/data/json_schema.dart | 44 +++++---- .../utcp/lib/src/http/http_transport.dart | 43 ++++++--- .../src/http/sse_communication_protocol.dart | 6 +- ...treamable_http_communication_protocol.dart | 6 +- packages/utcp/lib/src/json.dart | 5 +- packages/utcp/test/integration/http_test.dart | 10 ++ .../http_communication_protocol_test.dart | 30 +++--- .../test/unit/http/http_transport_test.dart | 96 +++++++++++++++++++ packages/utcp/test/unit/http/sse_test.dart | 1 + .../test/unit/http/streamable_http_test.dart | 13 +++ packages/utcp/test/unit/json_test.dart | 24 ++++- packages/utcp/test/unit/text/text_test.dart | 24 +++++ 13 files changed, 253 insertions(+), 59 deletions(-) diff --git a/packages/utcp/CHANGELOG.md b/packages/utcp/CHANGELOG.md index 8bcdf8e..0e3d50b 100644 --- a/packages/utcp/CHANGELOG.md +++ b/packages/utcp/CHANGELOG.md @@ -1,22 +1,22 @@ ## Unreleased -- A tool's `inputs` and `outputs` schemas drop keywords whose value is null, which the Python SDK writes for every unset keyword and the TypeScript SDK rejects. `const` and `default` keep a null value. Added `JsonSchema.fromJson`. +- A tool's `inputs` and `outputs` schemas drop keywords whose value is null, `const` and `default` included, which the Python SDK writes for every unset keyword and the TypeScript SDK rejects. Added `JsonSchema.fromJson`. - **Breaking:** `ToolRepository` adds `removeTool` and `toJson`, and `ToolSearchStrategy` adds `toJson`; custom implementations must add them. `InMemoryToolRepository.removeTool` also drops the tool from its manual. -- `UtcpClientConfig.toJson` writes the shared configuration format and round-trips through `fromJson`; loaders are written when their new `VariableLoader.toJson` is not null. +- **Breaking:** `VariableLoader` adds `toJson`; custom implementations must add it. `UtcpClientConfig.toJson` writes the shared configuration format and round-trips through `fromJson`; loaders are written when their `toJson` is not null. - `tool_repository` and `tool_search_strategy` are parsed with `ToolRepository.registry` and `ToolSearchStrategy.registry`, so plugins can add their own types. - `UtcpClient.fromFile` and `UtcpClientConfig.fromFile` read a JSON or YAML configuration file, and `UtcpClient` takes a `rootDir` for transports that resolve relative paths, like `root_dir` in Python and TypeScript. - Manuals are written with `utcp_version` `1.1.0`, the spec version this package implements, from `utcpProtocolVersion`. - Variables that start with `ref`, such as `$refresh_token`, are substituted; only a `$ref` not followed by a word character marks a JSON Schema reference, as in Python. - Manual names keep Unicode letters and numbers when sanitized, as in Python, so `café` keeps its name and variable namespace. - A client parses call templates with its own protocols first and no longer replaces parsers in `CallTemplate.registry`, so one client's protocols do not change parsing for other clients. Added `TypeRegistry.scoped`. -- A tool call that supplies `body_field` to a GET `http` or `streamable_http` template fails with a clear error instead of sending a GET with a body, as in the TypeScript SDK. +- A tool call that supplies a body to a GET `streamable_http` template fails with a clear error instead of sending it, as in the TypeScript SDK; `http` keeps sending it, as both reference SDKs do. A null body argument means no body. `buildToolRequest` takes `getWithBody` to choose. - The OAuth2 token request omits `scope` when it is unset or empty instead of sending `scope=`. - `streamable_http` reads `chunk_size: 0` and `timeout: 0` as the defaults, as the reference SDKs do, and `timeout` and `sse` `retry_timeout` accept fractional milliseconds. - Only the first 64 KiB of an HTTP error body is read (`HttpStreamedResult.maxErrorBodyBytes`), as in the Python SDK. - `streamable_http` binary responses are regrouped into `chunk_size`-byte chunks, the last one possibly shorter, as the spec describes. Before, chunks were at most `chunk_size` and followed the network's reads. - Docs: tag search follows the TypeScript SDK's scoring and `limit` (0 returns every tool), and `oauth2_user` auth is TypeScript-only. -- HTTP tool results are parsed as JSON only for `application/json` and `+json` content types, matched case-insensitively; other types (such as `application/x-ndjson`) and invalid JSON are returned as text instead of throwing, as the spec requires. -- Tool results are no longer parsed as YAML; YAML is read only for discovered manuals (`HttpResult.decodeManual`). +- **Breaking:** HTTP tool results are parsed as JSON only for `application/json` and `+json` content types, matched case-insensitively, as the spec requires, so a JSON body with another or no content type comes back as a `String`. Invalid JSON is returned as text instead of throwing. +- **Breaking:** tool results are no longer parsed as YAML, so a YAML body comes back as a `String`, and `HttpResult.decode` no longer parses YAML; use `HttpResult.decodeManual` for manuals. - OAuth2: `expires_in` sent as a string is accepted, an `access_token` that is not a usable bearer token is rejected before it is cached, and a cached token is dropped when the server answers 401 or 403. - OpenAPI-generated http tools without a request body keep `body_field: "body"` instead of `null`, which the TypeScript SDK rejects. - An unknown `dotenv` variable loader error says how to register it. diff --git a/packages/utcp/lib/src/data/json_schema.dart b/packages/utcp/lib/src/data/json_schema.dart index 5c16aa8..32171e5 100644 --- a/packages/utcp/lib/src/data/json_schema.dart +++ b/packages/utcp/lib/src/data/json_schema.dart @@ -11,14 +11,12 @@ extension type const JsonSchema._(JsonMap json) implements JsonMap { /// Reads a schema from a UTCP document, dropping keywords whose value is /// null, here and in every nested schema. The Python SDK writes every /// keyword it models, unset ones as null (`"type": null`), which is not - /// valid JSON Schema and which the TypeScript SDK rejects. `const` and - /// `default` keep a null value, which is meaningful for them. + /// valid JSON Schema and which the TypeScript SDK rejects. That includes + /// `const` and `default`, which Python writes as null on every schema. factory JsonSchema.fromJson(JsonMap json) => JsonSchema(_withoutNulls(json)); static const empty = JsonSchema({}); - static const _nullableKeywords = {'const', 'default'}; - static const _schemaMaps = { 'properties', 'patternProperties', @@ -40,24 +38,36 @@ extension type const JsonSchema._(JsonMap json) implements JsonMap { 'propertyNames', }; - static JsonMap _withoutNulls(JsonMap schema) => { - for (final MapEntry(:key, :value) in schema.entries) - if (value != null || _nullableKeywords.contains(key)) - key: switch (value) { + // Iterative, so a schema nested deeper than the call stack still parses. + static JsonMap _withoutNulls(JsonMap root) { + final result = {}; + final pending = [(root, result)]; + JsonMap copy(JsonMap schema) { + final target = {}; + pending.add((schema, target)); + return target; + } + + Object? child(Object? value) => value is JsonMap ? copy(value) : value; + + while (pending.isNotEmpty) { + final (schema, target) = pending.removeLast(); + for (final MapEntry(:key, :value) in schema.entries) { + if (value == null) continue; + target[key] = switch (value) { final JsonMap map when _schemaMaps.contains(key) => { - for (final MapEntry(:key, :value) in map.entries) - key: value is JsonMap ? _withoutNulls(value) : value, + for (final MapEntry(:key, :value) in map.entries) key: child(value), }, final List list when _schemaLists.contains(key) || key == 'items' => - [ - for (final item in list) - item is JsonMap ? _withoutNulls(item) : item, - ], - final JsonMap map when _schemas.contains(key) => _withoutNulls(map), + [for (final item in list) child(item)], + final JsonMap map when _schemas.contains(key) => copy(map), _ => value, - }, - }; + }; + } + } + return result; + } String? get title => json.optString('title'); diff --git a/packages/utcp/lib/src/http/http_transport.dart b/packages/utcp/lib/src/http/http_transport.dart index f8fe8d2..7af0c6b 100644 --- a/packages/utcp/lib/src/http/http_transport.dart +++ b/packages/utcp/lib/src/http/http_transport.dart @@ -100,17 +100,31 @@ final _credentialHeaderPattern = RegExp( r'csrftoken|xsrftoken|xapikey|xauthtoken|xaccesstoken|xapitoken)', ); +/// What [buildToolRequest] does when a tool call supplies a body to a GET +/// template. +enum GetWithBody { + /// Sends the GET with its body, as `http` does in the Python and + /// TypeScript SDKs; some APIs, such as Elasticsearch `_search`, rely on it. + send, + + /// Throws a [UtcpException] before any request, as `streamable_http` does + /// in the TypeScript SDK. + reject, + + /// Sends a POST instead, as `sse` does. + sendAsPost, +} + /// Builds the request for a tool call: header fields, body field, path /// parameters, then query parameters, as described in the HTTP protocol /// specification. /// -/// A GET cannot carry a body, so supplying the body field to a GET template -/// throws a [UtcpException], as the TypeScript SDK does, unless -/// [postWithBody] is set: then the request becomes a POST instead. +/// A body argument that is null or absent means no body. [getWithBody] +/// decides what happens to a body supplied to a GET template. HttpRequestSpec buildToolRequest( HttpRequestTemplate template, ToolArguments args, { - bool postWithBody = false, + GetWithBody getWithBody = GetWithBody.send, }) { final remaining = {...args}; final request = HttpRequestSpec(template.httpMethod, Uri()) @@ -121,13 +135,19 @@ HttpRequestSpec buildToolRequest( } } final bodyField = template.bodyField; - final suppliesBody = bodyField != null && remaining.containsKey(bodyField); - final body = suppliesBody ? remaining.remove(bodyField) : null; - if (suppliesBody && request.method == HttpMethod.get && !postWithBody) { - throw UtcpException( - "body_field '$bodyField' was supplied but http_method is GET, which " - 'cannot carry a request body. Set http_method to POST.', - ); + final body = bodyField == null ? null : remaining.remove(bodyField); + if (body != null && request.method == HttpMethod.get) { + switch (getWithBody) { + case GetWithBody.send: + break; + case GetWithBody.reject: + throw UtcpException( + "body_field '$bodyField' was supplied but http_method is GET, " + 'which cannot carry a request body. Set http_method to POST.', + ); + case GetWithBody.sendAsPost: + request.method = HttpMethod.post; + } } final url = buildUrlWithPathParams(template.url, remaining); @@ -138,7 +158,6 @@ HttpRequestSpec buildToolRequest( ..addQuery(remaining); if (body != null) { - if (postWithBody) request.method = HttpMethod.post; final contentType = request.header('content-type') ?? template.contentType; request ..setHeader('Content-Type', contentType) diff --git a/packages/utcp/lib/src/http/sse_communication_protocol.dart b/packages/utcp/lib/src/http/sse_communication_protocol.dart index 7cf297c..3568886 100644 --- a/packages/utcp/lib/src/http/sse_communication_protocol.dart +++ b/packages/utcp/lib/src/http/sse_communication_protocol.dart @@ -106,7 +106,11 @@ class SseCommunicationProtocol extends CommunicationProtocol { SseCallTemplate template, Future cancel, ) async* { - final request = buildToolRequest(template, arguments, postWithBody: true); + final request = buildToolRequest( + template, + arguments, + getWithBody: GetWithBody.sendAsPost, + ); final sendsBody = request.body != null; request.setHeader('Accept', 'text/event-stream'); await _transport.authorize( diff --git a/packages/utcp/lib/src/http/streamable_http_communication_protocol.dart b/packages/utcp/lib/src/http/streamable_http_communication_protocol.dart index 1e36cf0..732ecb2 100644 --- a/packages/utcp/lib/src/http/streamable_http_communication_protocol.dart +++ b/packages/utcp/lib/src/http/streamable_http_communication_protocol.dart @@ -112,7 +112,11 @@ class StreamableHttpCommunicationProtocol extends CommunicationProtocol { StreamableHttpCallTemplate template, Future cancel, ) async* { - final request = buildToolRequest(template, arguments); + final request = buildToolRequest( + template, + arguments, + getWithBody: GetWithBody.reject, + ); final stop = Completer(); var timedOut = false; final deadline = Timer(template.timeout, () { diff --git a/packages/utcp/lib/src/json.dart b/packages/utcp/lib/src/json.dart index 5910e72..6f70864 100644 --- a/packages/utcp/lib/src/json.dart +++ b/packages/utcp/lib/src/json.dart @@ -272,12 +272,13 @@ extension JsonReader on JsonMap { Duration? optMilliseconds(String key) { final value = optNum(key); if (value == null) return null; - if (value < 0 || !value.isFinite) { + final microseconds = value * 1000; + if (value < 0 || !microseconds.isFinite) { throw FormatException( "Field '$key' must be a non-negative number, got $value.", ); } - return Duration(microseconds: (value * 1000).round()); + return Duration(microseconds: microseconds.round()); } JsonMap object(String key) => diff --git a/packages/utcp/test/integration/http_test.dart b/packages/utcp/test/integration/http_test.dart index 135f82f..02c1ce4 100644 --- a/packages/utcp/test/integration/http_test.dart +++ b/packages/utcp/test/integration/http_test.dart @@ -165,6 +165,16 @@ void main() { }, ); + test('a GET sends its body to the server', () async { + const query = {'query': 'match_all'}; + final result = await client.callTool('api.get_user', { + 'id': '42', + 'body': query, + }); + expect(result, containsPair('method', 'GET')); + expect(result, containsPair('body', query)); + }); + test('follows same-origin redirects', () async { expect(await client.callTool('api.moved'), {'redirected': true}); }); diff --git a/packages/utcp/test/unit/http/http_communication_protocol_test.dart b/packages/utcp/test/unit/http/http_communication_protocol_test.dart index 5ad605b..0449b34 100644 --- a/packages/utcp/test/unit/http/http_communication_protocol_test.dart +++ b/packages/utcp/test/unit/http/http_communication_protocol_test.dart @@ -210,7 +210,7 @@ void main() { }); group('tool calls', () { - test('a GET supplied its body field fails before any request', () async { + test('a GET sends a supplied body, as the reference SDKs do', () async { final sent = []; final protocol = HttpCommunicationProtocol( transport: HttpTransport( @@ -226,23 +226,17 @@ void main() { ); addTearDown(caller.close); const template = HttpCallTemplate(url: 'https://api.example.com/x'); - await expectLater( - protocol.callTool(caller, 'm.x', { - 'body': {'k': 1}, - }, template), - throwsA( - isA().having( - (e) => e.message, - 'message', - contains("body_field 'body' was supplied but http_method is GET"), - ), - ), - ); - expect(sent, isEmpty); - expect(await protocol.callTool(caller, 'm.x', {'q': 1}, template), { - 'ok': true, - }); - expect(sent.single.url.query, 'q=1'); + await protocol.callTool(caller, 'm.x', { + 'q': 1, + 'body': {'k': 1}, + }, template); + await protocol.callTool(caller, 'm.x', {'body': null}, template); + expect(sent.map((r) => (r.method, r.url.query, r.body)), [ + ('GET', 'q=1', '{"k":1}'), + ('GET', '', ''), + ]); + expect(sent.first.headers['Content-Type'], 'application/json'); + expect(sent.last.headers.containsKey('Content-Type'), isFalse); }); }); } diff --git a/packages/utcp/test/unit/http/http_transport_test.dart b/packages/utcp/test/unit/http/http_transport_test.dart index 1165c8c..65ed931 100644 --- a/packages/utcp/test/unit/http/http_transport_test.dart +++ b/packages/utcp/test/unit/http/http_transport_test.dart @@ -67,6 +67,30 @@ void main() { expect(request.body, 'a=1'); }); + test('getWithBody decides a GET body; a null body is no body', () { + const template = HttpCallTemplate(url: 'https://a.example/search'); + (HttpMethod, String?) build(GetWithBody mode, Object? body) { + final request = buildToolRequest(template, { + 'body': body, + }, getWithBody: mode); + return (request.method, request.body); + } + + expect(build(GetWithBody.send, {'q': 1}), (HttpMethod.get, '{"q":1}')); + expect(build(GetWithBody.sendAsPost, {'q': 1}), ( + HttpMethod.post, + '{"q":1}', + )); + expect( + () => build(GetWithBody.reject, {'q': 1}), + throwsA(isA()), + ); + for (final mode in GetWithBody.values) { + expect(build(mode, null), (HttpMethod.get, null), reason: '$mode'); + } + expect(buildToolRequest(template, {}).body, isNull); + }); + test('missing path parameters are reported', () { expect( () => @@ -327,6 +351,78 @@ void main() { }); } + test('stays cached when another origin answers 401', () async { + var fetches = 0; + final transport = HttpTransport( + client: MockClient((request) async { + if (request.url.path == '/token') { + return jsonResponse({'access_token': 'tok${++fetches}'}); + } + return request.url.host == 'a' + ? http.Response( + '', + 302, + headers: {'location': 'https://b.example/x'}, + ) + : http.Response('', 401); + }), + ); + addTearDown(transport.close); + for (var i = 0; i < 2; i++) { + final request = get('https://a/tool'); + await transport.authorize(request, auth, timeout: timeout); + await transport.send(request, context: 'test', timeout: timeout); + } + expect(fetches, 1); + }); + + test('a late 401 for an old token keeps the refreshed one', () async { + var fetches = 0; + final transport = HttpTransport( + client: MockClient((request) async { + if (request.url.path == '/token') { + return jsonResponse({'access_token': 'tok${++fetches}'}); + } + return http.Response('', 401); + }), + ); + addTearDown(transport.close); + Future authorized() async { + final request = get('https://a/tool'); + await transport.authorize(request, auth, timeout: timeout); + return request; + } + + Future send(HttpRequestSpec request) => + transport.send(request, context: 'test', timeout: timeout); + + final early = await authorized(); + final late = await authorized(); + await send(early); + expect((await authorized()).header('authorization'), 'Bearer tok2'); + await send(late); + expect((await authorized()).header('authorization'), 'Bearer tok2'); + expect(fetches, 2); + }); + + test('expires_in sent as a string sets the cache lifetime', () async { + var fetches = 0; + final transport = HttpTransport( + client: MockClient( + (_) async => jsonResponse({ + 'access_token': 'tok${++fetches}', + 'expires_in': ' 1 ', + }), + ), + ); + addTearDown(transport.close); + await transport.authorize(get('https://a/x'), auth, timeout: timeout); + await Future.delayed(const Duration(milliseconds: 1100)); + final request = get('https://a/x'); + await transport.authorize(request, auth, timeout: timeout); + expect(request.header('authorization'), 'Bearer tok2'); + }); + test('stays cached when the server accepts it', () async { var fetches = 0; final transport = HttpTransport( diff --git a/packages/utcp/test/unit/http/sse_test.dart b/packages/utcp/test/unit/http/sse_test.dart index 42f1553..d962d03 100644 --- a/packages/utcp/test/unit/http/sse_test.dart +++ b/packages/utcp/test/unit/http/sse_test.dart @@ -707,6 +707,7 @@ void main() { test('malformed fields are rejected', () { expect(() => template({'retry_timeout': -1}), throwsFormatException); + expect(() => template({'retry_timeout': 1e306}), throwsFormatException); expect(() => template({'reconnect': 'yes'}), throwsFormatException); expect(() => template({'url': null}), throwsFormatException); }); diff --git a/packages/utcp/test/unit/http/streamable_http_test.dart b/packages/utcp/test/unit/http/streamable_http_test.dart index 5cee1f9..76ff415 100644 --- a/packages/utcp/test/unit/http/streamable_http_test.dart +++ b/packages/utcp/test/unit/http/streamable_http_test.dart @@ -320,6 +320,18 @@ void main() { ); expect(requests, 0); }); + + test('a GET with a null body argument sends no body', () async { + late String sentBody; + final protocol = protocolFor((request, body) async { + sentBody = await utf8.decodeStream(body); + return streamedResponse(['ok'], contentType: 'text/plain'); + }); + await protocol.callTool(caller, 'm.export', { + 'data': null, + }, template({'body_field': 'data'})); + expect(sentBody, isEmpty); + }); }); group('security', () { @@ -468,6 +480,7 @@ void main() { {'chunk_size': 1.5}, {'timeout': -5}, {'timeout': double.infinity}, + {'timeout': 1e306}, {'chunk_size': 'big'}, ]) { expect( diff --git a/packages/utcp/test/unit/json_test.dart b/packages/utcp/test/unit/json_test.dart index 05e40a0..8a2bec3 100644 --- a/packages/utcp/test/unit/json_test.dart +++ b/packages/utcp/test/unit/json_test.dart @@ -53,6 +53,26 @@ void main() { throwsFormatException, ); }); + + test( + 'rejects milliseconds that overflow to infinity, naming the field', + () { + for (final value in [1e306, double.maxFinite, double.infinity, -1]) { + expect( + () => + {'timeout': value}.optMilliseconds('timeout'), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains("'timeout'"), + ), + ), + reason: '$value', + ); + } + }, + ); }); group('decodeYaml', () { @@ -282,7 +302,7 @@ items: }); }); - test('keeps a null const or default, and nulls inside values', () { + test('drops a null const or default but keeps nulls inside values', () { final schema = JsonSchema.fromJson({ 'const': null, 'default': null, @@ -291,8 +311,6 @@ items: 'properties': {'x': null}, }); expect(schema, { - 'const': null, - 'default': null, 'enum': ['a', null], 'examples': [null], 'properties': {'x': null}, diff --git a/packages/utcp/test/unit/text/text_test.dart b/packages/utcp/test/unit/text/text_test.dart index c2319f1..67f6f8f 100644 --- a/packages/utcp/test/unit/text/text_test.dart +++ b/packages/utcp/test/unit/text/text_test.dart @@ -176,6 +176,30 @@ tools: ); }); + test('registers a tool whose schema nests deeper than the stack', () async { + const depth = 50000; + final content = + '{"tools": [{"name": "deep", "inputs": ' + '${'{"items": ' * depth}{"type": null}${'}' * depth}, ' + '"tool_call_template": ' + '{"call_template_type": "text", "content": ""}}]}'; + final deep = await UtcpClient.create( + config: UtcpClientConfig( + environment: const {}, + manualCallTemplates: [TextCallTemplate(name: 'm', content: content)], + ), + ); + addTearDown(deep.close); + JsonSchema? schema = (await deep.getTools()).single.inputs; + var levels = -1; + JsonSchema? innermost; + for (; schema != null; schema = schema.items, levels++) { + innermost = schema; + } + expect(levels, depth); + expect(innermost, isEmpty); + }); + test('reports unparsable or invalid content as a failure', () async { for (final (content, error) in [ ('{"tools": [', 'Failed to parse content as JSON or YAML'), From 009bc93fafa4a638d6d8ab6f8daccf9380044eb6 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 3 Nov 2026 11:26:12 -0500 Subject: [PATCH 2/3] Reject timeouts too large for a Duration instead of wrapping --- packages/utcp/lib/src/json.dart | 8 ++++-- packages/utcp/test/unit/json_test.dart | 40 ++++++++++++++------------ 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/packages/utcp/lib/src/json.dart b/packages/utcp/lib/src/json.dart index 6f70864..b43e428 100644 --- a/packages/utcp/lib/src/json.dart +++ b/packages/utcp/lib/src/json.dart @@ -237,6 +237,9 @@ String _typeName(Object? value) => switch (value) { /// /// Every reader throws a [FormatException] naming the field when the value /// has the wrong type, so parsers never cast. +/// Below the largest `Duration` in microseconds (2^63 - 1). +const _maxMicroseconds = 9.2e18; + extension JsonReader on JsonMap { T? _optional(String key, String expected) { final value = this[key]; @@ -272,8 +275,9 @@ extension JsonReader on JsonMap { Duration? optMilliseconds(String key) { final value = optNum(key); if (value == null) return null; - final microseconds = value * 1000; - if (value < 0 || !microseconds.isFinite) { + // In doubles, so a large integer cannot wrap to a negative duration. + final microseconds = value.toDouble() * 1000; + if (value < 0 || !(microseconds < _maxMicroseconds)) { throw FormatException( "Field '$key' must be a non-negative number, got $value.", ); diff --git a/packages/utcp/test/unit/json_test.dart b/packages/utcp/test/unit/json_test.dart index 8a2bec3..053d544 100644 --- a/packages/utcp/test/unit/json_test.dart +++ b/packages/utcp/test/unit/json_test.dart @@ -54,25 +54,29 @@ void main() { ); }); - test( - 'rejects milliseconds that overflow to infinity, naming the field', - () { - for (final value in [1e306, double.maxFinite, double.infinity, -1]) { - expect( - () => - {'timeout': value}.optMilliseconds('timeout'), - throwsA( - isA().having( - (e) => e.message, - 'message', - contains("'timeout'"), - ), + test('rejects milliseconds too large for a Duration, naming the field', () { + for (final value in [ + 1e306, + 1e300, + double.maxFinite, + double.infinity, + double.nan, + 10000000000000000, + -1, + ]) { + expect( + () => {'timeout': value}.optMilliseconds('timeout'), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains("'timeout'"), ), - reason: '$value', - ); - } - }, - ); + ), + reason: '$value', + ); + } + }); }); group('decodeYaml', () { From 75a96b4c4cd75d8566075770ab21719911924fc6 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 3 Nov 2026 11:36:02 -0500 Subject: [PATCH 3/3] Polish: keep JsonReader docs attached, clearer duration error, trim changelog --- packages/utcp/CHANGELOG.md | 2 +- packages/utcp/lib/src/json.dart | 9 ++++--- .../test/unit/http/http_transport_test.dart | 26 ++++++++----------- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/packages/utcp/CHANGELOG.md b/packages/utcp/CHANGELOG.md index 0e3d50b..3e052fa 100644 --- a/packages/utcp/CHANGELOG.md +++ b/packages/utcp/CHANGELOG.md @@ -9,7 +9,7 @@ - Variables that start with `ref`, such as `$refresh_token`, are substituted; only a `$ref` not followed by a word character marks a JSON Schema reference, as in Python. - Manual names keep Unicode letters and numbers when sanitized, as in Python, so `café` keeps its name and variable namespace. - A client parses call templates with its own protocols first and no longer replaces parsers in `CallTemplate.registry`, so one client's protocols do not change parsing for other clients. Added `TypeRegistry.scoped`. -- A tool call that supplies a body to a GET `streamable_http` template fails with a clear error instead of sending it, as in the TypeScript SDK; `http` keeps sending it, as both reference SDKs do. A null body argument means no body. `buildToolRequest` takes `getWithBody` to choose. +- A tool call that supplies a body to a GET `streamable_http` template fails with a clear error instead of sending it, as in the TypeScript SDK; `http` keeps sending it, as both reference SDKs do. `buildToolRequest` takes `getWithBody` to choose. - The OAuth2 token request omits `scope` when it is unset or empty instead of sending `scope=`. - `streamable_http` reads `chunk_size: 0` and `timeout: 0` as the defaults, as the reference SDKs do, and `timeout` and `sse` `retry_timeout` accept fractional milliseconds. - Only the first 64 KiB of an HTTP error body is read (`HttpStreamedResult.maxErrorBodyBytes`), as in the Python SDK. diff --git a/packages/utcp/lib/src/json.dart b/packages/utcp/lib/src/json.dart index b43e428..57b9c86 100644 --- a/packages/utcp/lib/src/json.dart +++ b/packages/utcp/lib/src/json.dart @@ -233,13 +233,13 @@ String _typeName(Object? value) => switch (value) { _ => 'unsupported value', }; +/// Below the largest `Duration` in microseconds (2^63 - 1). +const _maxMicroseconds = 9.2e18; + /// Typed, path-aware field access for decoded JSON objects. /// /// Every reader throws a [FormatException] naming the field when the value /// has the wrong type, so parsers never cast. -/// Below the largest `Duration` in microseconds (2^63 - 1). -const _maxMicroseconds = 9.2e18; - extension JsonReader on JsonMap { T? _optional(String key, String expected) { final value = this[key]; @@ -279,7 +279,8 @@ extension JsonReader on JsonMap { final microseconds = value.toDouble() * 1000; if (value < 0 || !(microseconds < _maxMicroseconds)) { throw FormatException( - "Field '$key' must be a non-negative number, got $value.", + "Field '$key' must be a non-negative number of milliseconds below " + '9.2e15, got $value.', ); } return Duration(microseconds: microseconds.round()); diff --git a/packages/utcp/test/unit/http/http_transport_test.dart b/packages/utcp/test/unit/http/http_transport_test.dart index 65ed931..ef13b51 100644 --- a/packages/utcp/test/unit/http/http_transport_test.dart +++ b/packages/utcp/test/unit/http/http_transport_test.dart @@ -285,21 +285,17 @@ void main() { } }); - test('accepts expires_in sent as a string', () async { - for (final expiresIn in ['3600', 'soon']) { - final transport = HttpTransport( - client: MockClient( - (_) async => jsonResponse({ - 'access_token': 'tok', - 'expires_in': expiresIn, - }), - ), - ); - addTearDown(transport.close); - final request = get('https://a/x'); - await transport.authorize(request, auth, timeout: timeout); - expect(request.header('authorization'), 'Bearer tok'); - } + test('accepts an expires_in that is not a number', () async { + final transport = HttpTransport( + client: MockClient( + (_) async => + jsonResponse({'access_token': 'tok', 'expires_in': 'soon'}), + ), + ); + addTearDown(transport.close); + final request = get('https://a/x'); + await transport.authorize(request, auth, timeout: timeout); + expect(request.header('authorization'), 'Bearer tok'); }); test('is validated before it is cached', () async {