Skip to content
Merged
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
10 changes: 5 additions & 5 deletions packages/utcp/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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. `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.
Expand Down
44 changes: 27 additions & 17 deletions packages/utcp/lib/src/data/json_schema.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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 = <String, Object?>{};
final pending = [(root, result)];
JsonMap copy(JsonMap schema) {
final target = <String, Object?>{};
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<Object?> 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');

Expand Down
43 changes: 31 additions & 12 deletions packages/utcp/lib/src/http/http_transport.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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);
Expand All @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion packages/utcp/lib/src/http/sse_communication_protocol.dart
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,11 @@ class SseCommunicationProtocol extends CommunicationProtocol {
SseCallTemplate template,
Future<void> 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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ class StreamableHttpCommunicationProtocol extends CommunicationProtocol {
StreamableHttpCallTemplate template,
Future<void> cancel,
) async* {
final request = buildToolRequest(template, arguments);
final request = buildToolRequest(
template,
arguments,
getWithBody: GetWithBody.reject,
);
final stop = Completer<void>();
var timedOut = false;
final deadline = Timer(template.timeout, () {
Expand Down
12 changes: 9 additions & 3 deletions packages/utcp/lib/src/json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ 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
Expand Down Expand Up @@ -272,12 +275,15 @@ extension JsonReader on JsonMap {
Duration? optMilliseconds(String key) {
final value = optNum(key);
if (value == null) return null;
if (value < 0 || !value.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.",
"Field '$key' must be a non-negative number of milliseconds below "
'9.2e15, got $value.',
);
}
return Duration(microseconds: (value * 1000).round());
return Duration(microseconds: microseconds.round());
}

JsonMap object(String key) =>
Expand Down
10 changes: 10 additions & 0 deletions packages/utcp/test/integration/http_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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});
});
Expand Down
30 changes: 12 additions & 18 deletions packages/utcp/test/unit/http/http_communication_protocol_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <http.Request>[];
final protocol = HttpCommunicationProtocol(
transport: HttpTransport(
Expand All @@ -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<UtcpException>().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);
});
});
}
Loading
Loading