incur-cli 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
incur/_openapi.py ADDED
@@ -0,0 +1,640 @@
1
+ """OpenAPI documents: commands generated from operations, and the CLI described as one."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import urllib.parse
7
+ from collections.abc import Callable, Mapping
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Literal
10
+
11
+ from . import _gateway, _js
12
+ from ._command import Command, Context, ToolMeta
13
+ from ._errors import Error
14
+ from ._http import FetchHandler, Headers, Request, call, fetch, join_url, parse_json
15
+ from ._js import Json
16
+ from ._jsonschema import coerce, convert, describe, optional
17
+ from ._schema import Field, Type, json_schema, object_type
18
+ from ._tree import Alias, Entry, Gateway, Group, Spec
19
+
20
+ #: An OpenAPI document as parsed JSON, or its URL. A relative URL resolves against the URL of a
21
+ #: hosted fetch source.
22
+ OpenapiSource = Mapping[str, Any] | str
23
+
24
+ _METHODS = ("delete", "get", "head", "options", "patch", "post", "put", "trace")
25
+ _VERSION = re.compile(r"^/v(\d+)(?=/|$)")
26
+ _COMPACT_PATTERN_LIMIT = 100
27
+ _DATE_TIME_FORMATS = frozenset({"date", "date-time", "duration", "time"})
28
+
29
+
30
+ @dataclass
31
+ class OpenapiOperation:
32
+ """An operation that `OpenapiConfig.include` decides on."""
33
+
34
+ method: str
35
+ """The lowercase HTTP method, such as `get`."""
36
+ path: str
37
+ """The path template, such as `/users/{id}`."""
38
+ operation: dict[str, Json]
39
+ """The operation object."""
40
+
41
+
42
+ @dataclass
43
+ class OpenapiConfig:
44
+ """How commands are generated from an OpenAPI document.
45
+
46
+ >>> OpenapiConfig(mode="namespace", groups={"users": "Manage users"}).versions
47
+ 'all'
48
+ """
49
+
50
+ compact: bool = False
51
+ """Strips `example(s)`, oversized `pattern` regexes, and date and time formats from schemas,
52
+ shrinking MCP tool listings."""
53
+ forward_headers: list[str] = field(default_factory=list[str])
54
+ """Headers copied from the inbound HTTP request onto upstream requests when not set."""
55
+ groups: dict[str, str] = field(default_factory=dict[str, str])
56
+ """Descriptions of generated groups, keyed by space-separated command path."""
57
+ include: Callable[[OpenapiOperation], bool] | None = None
58
+ """Generates commands only for operations this returns `True` for."""
59
+ mode: Literal["namespace", "operation"] = "operation"
60
+ """`operation` names commands by operation ID; `namespace` nests them by path segment."""
61
+ security: bool = True
62
+ """Whether the document's security requirements generate credential options."""
63
+ versions: Literal["all", "latest"] = "all"
64
+ """`latest` keeps only the highest version of path-versioned operations (`/v2/users`)."""
65
+
66
+
67
+ # --- The CLI as an OpenAPI document ---------------------------------------------------------
68
+
69
+
70
+ def from_cli(spec: Spec) -> dict[str, Json]:
71
+ """Describes a CLI's commands as an OpenAPI 3.2 document."""
72
+ paths: dict[str, Json] = {}
73
+ root = spec.root_command()
74
+ if root is not None:
75
+ _add_command(paths, [], root, spec.globals)
76
+ for name, entry in spec.commands.items():
77
+ _add_entry(paths, name.split(), entry, spec.globals)
78
+ info: dict[str, Json] = {"title": spec.name, "version": spec.version or "0.0.0"}
79
+ if spec.description:
80
+ info["description"] = spec.description
81
+ return {"openapi": "3.2.0", "info": info, "paths": paths}
82
+
83
+
84
+ def _add_entry(
85
+ paths: dict[str, Json], segments: list[str], entry: Entry, globals_: Type | None
86
+ ) -> None:
87
+ if isinstance(entry, (Alias, Gateway)):
88
+ return
89
+ if isinstance(entry, Group):
90
+ if entry.root is not None:
91
+ _add_command(paths, segments, entry.root, globals_)
92
+ for name, child in entry.commands.items():
93
+ _add_entry(paths, [*segments, *name.split()], child, globals_)
94
+ return
95
+ _add_command(paths, segments, entry, globals_)
96
+
97
+
98
+ def _merge(options: Type | None, globals_: Type | None) -> Type | None:
99
+ """Merges options and globals; a same-named global replaces the option in place."""
100
+ if globals_ is None:
101
+ return options
102
+ fields = {f.name: f for f in options.fields} if options else {}
103
+ fields.update((f.name, f) for f in globals_.fields)
104
+ return object_type(list(fields.values()))
105
+
106
+
107
+ def _add_command(
108
+ paths: dict[str, Json], segments: list[str], command: Command, globals_: Type | None
109
+ ) -> None:
110
+ options = _merge(command.options, globals_)
111
+ args_schema = json_schema(command.args) if command.args else {}
112
+ options_schema = json_schema(options) if options else None
113
+ args = _js.as_object(args_schema.get("properties", {}))
114
+ required_args = set(_js.as_list(args_schema.get("required", [])))
115
+ method = _infer_method(segments)
116
+ names = list(args)
117
+ count = next((i for i, n in enumerate(names) if n not in required_args), len(names))
118
+ variants = [names[:n] for n in range(count, len(names) + 1)]
119
+ for included in variants:
120
+ parts = [*segments, *(f"{{{n}}}" for n in included)]
121
+ route = "/" + "/".join(_encode_segment(p) for p in parts)
122
+ parameters: list[Json] = [
123
+ {"name": n, "in": "path", "required": True, "schema": args.get(n, {"type": "string"})}
124
+ for n in included
125
+ ]
126
+ if options_schema is not None and method in ("get", "delete"):
127
+ required = _js.as_list(options_schema.get("required", []))
128
+ for name, schema in _js.as_object(options_schema["properties"]).items():
129
+ parameter: dict[str, Json] = {"name": name, "in": "query"}
130
+ if name in required:
131
+ parameter["required"] = True
132
+ parameter["schema"] = schema
133
+ parameters.append(parameter)
134
+ operation: dict[str, Json] = {"operationId": _operation_id(segments, method, included)}
135
+ if command.description:
136
+ operation["summary"] = command.description
137
+ if parameters:
138
+ operation["parameters"] = parameters
139
+ if options_schema is not None and method not in ("get", "delete"):
140
+ operation["requestBody"] = {
141
+ "required": bool(options_schema.get("required")),
142
+ "content": {"application/json": {"schema": options_schema}},
143
+ }
144
+ output = json_schema(command.output) if command.output else None
145
+ operation["responses"] = _responses(output)
146
+ item = paths.get(route)
147
+ item = item if isinstance(item, dict) else {}
148
+ item[method] = operation
149
+ paths[route] = item
150
+
151
+
152
+ def _infer_method(segments: list[str]) -> str:
153
+ text = " ".join(re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", s) for s in segments).lower()
154
+ for method, words in (
155
+ ("delete", "delete|remove|rm|destroy|clear"),
156
+ ("patch", "update|edit|modify|set|enable|disable|rename|patch"),
157
+ ("get", "get|list|show|read|search|find|status|describe|info|health|check"),
158
+ ):
159
+ if re.search(rf"\b(?:{words})\b", text, re.ASCII):
160
+ return method
161
+ return "post"
162
+
163
+
164
+ def _operation_id(segments: list[str], method: str, args: list[str]) -> str:
165
+ raw = " ".join([*segments, *([" ".join(args)] if args else [])])
166
+ pascal = re.sub(r"(?:^|[\s_-]+)(\w)", lambda m: m[1].upper(), raw, flags=re.ASCII)
167
+ return f"{method}{pascal}"
168
+
169
+
170
+ def _encode_segment(segment: str) -> str:
171
+ if segment.startswith("{") and segment.endswith("}"):
172
+ return segment
173
+ return urllib.parse.quote(segment, safe="-_.!~*'()")
174
+
175
+
176
+ def _meta_schema() -> dict[str, Json]:
177
+ return {
178
+ "type": "object",
179
+ "required": ["command", "duration"],
180
+ "properties": {"command": {"type": "string"}, "duration": {"type": "string"}},
181
+ }
182
+
183
+
184
+ def _error_response(description: str) -> dict[str, Json]:
185
+ error: dict[str, Json] = {
186
+ "type": "object",
187
+ "required": ["code", "message"],
188
+ "properties": {
189
+ "code": {"type": "string"},
190
+ "message": {"type": "string"},
191
+ "hint": {"type": "string"},
192
+ "retryable": {"type": "boolean"},
193
+ },
194
+ }
195
+ schema: dict[str, Json] = {
196
+ "type": "object",
197
+ "required": ["ok", "error", "meta"],
198
+ "properties": {"ok": {"const": False}, "error": error, "meta": _meta_schema()},
199
+ }
200
+ return {"description": description, "content": {"application/json": {"schema": schema}}}
201
+
202
+
203
+ def _responses(output: dict[str, Json] | None) -> dict[str, Json]:
204
+ schema: dict[str, Json] = {
205
+ "type": "object",
206
+ "required": ["ok", "data", "meta"],
207
+ "properties": {"ok": {"const": True}, "data": output or {}, "meta": _meta_schema()},
208
+ }
209
+ return {
210
+ "200": {
211
+ "description": "Command completed successfully.",
212
+ "content": {"application/json": {"schema": schema}},
213
+ },
214
+ "400": _error_response("Validation error."),
215
+ "500": _error_response("Command failed."),
216
+ }
217
+
218
+
219
+ # --- Commands generated from an OpenAPI document ---------------------------------------------
220
+
221
+
222
+ async def resolve(source: OpenapiSource, base: str | None) -> dict[str, Json]:
223
+ """Returns an OpenAPI document, fetching it when the source is a URL.
224
+
225
+ Raises:
226
+ ValueError: When a relative URL has no base, or the document cannot be fetched.
227
+ """
228
+ if not isinstance(source, str):
229
+ return _js.as_object(_js.normalize(dict(source)))
230
+ if urllib.parse.urlsplit(source).scheme:
231
+ url = source
232
+ else:
233
+ if base is None:
234
+ raise ValueError(f"Relative OpenAPI spec URL requires a fetch URL base: {source}")
235
+ parts = urllib.parse.urlsplit(base)
236
+ if not parts.path.endswith("/"):
237
+ base = urllib.parse.urlunsplit(parts._replace(path=f"{parts.path}/"))
238
+ url = join_url(base, source)
239
+ response = await fetch(Request(url))
240
+ if not response.ok:
241
+ raise ValueError(f"Failed to fetch OpenAPI spec from {source}: {response.status}")
242
+ return _js.as_object(parse_json(await response.text()))
243
+
244
+
245
+ def _dereference(root: Json) -> Json:
246
+ """Replaces local `$ref` pointers with what they point to."""
247
+ cache: dict[str, Json] = {}
248
+
249
+ def pointer(ref: str) -> Json:
250
+ current = root
251
+ fragment = ref[1:]
252
+ if fragment in ("", "/"):
253
+ return root
254
+ for raw in fragment[1:].split("/"):
255
+ part = raw.replace("~1", "/").replace("~0", "~")
256
+ if not isinstance(current, dict) or part not in current:
257
+ raise ValueError(f'Cannot resolve $ref "{ref}": "{part}" not found')
258
+ current = current[part]
259
+ return current
260
+
261
+ def walk(node: Json) -> Json:
262
+ if isinstance(node, list):
263
+ return [walk(item) for item in node]
264
+ if not isinstance(node, dict):
265
+ return node
266
+ ref = node.get("$ref")
267
+ if isinstance(ref, str) and ref.startswith("#"):
268
+ if ref in cache:
269
+ return cache[ref]
270
+ target = pointer(ref)
271
+ if not isinstance(target, dict):
272
+ cache[ref] = walk(target)
273
+ return cache[ref]
274
+ placeholder: dict[str, Json] = {}
275
+ cache[ref] = placeholder
276
+ resolved = walk(target)
277
+ if not isinstance(resolved, dict):
278
+ cache[ref] = resolved
279
+ return resolved
280
+ placeholder.update(resolved)
281
+ return placeholder
282
+ return {key: walk(value) for key, value in node.items()}
283
+
284
+ return walk(root)
285
+
286
+
287
+ @dataclass
288
+ class _Operation:
289
+ method: str
290
+ path: str
291
+ route: str
292
+ operation: dict[str, Json]
293
+
294
+
295
+ def _params(operation: dict[str, Json], location: str) -> list[dict[str, Json]]:
296
+ listed = operation.get("parameters")
297
+ items = listed if isinstance(listed, list) else []
298
+ return [p for p in items if isinstance(p, dict) and p.get("in") == location]
299
+
300
+
301
+ def _str(value: Json | None) -> str | None:
302
+ return value if isinstance(value, str) else None
303
+
304
+
305
+ def commands(
306
+ document: dict[str, Json],
307
+ fetch: FetchHandler,
308
+ config: OpenapiConfig | None,
309
+ base_path: str | None,
310
+ ) -> dict[str, Entry]:
311
+ """Generates commands, one per operation, that call `fetch`."""
312
+ config = config or OpenapiConfig()
313
+ resolved = _js.as_object(_dereference(document))
314
+ paths = resolved.get("paths")
315
+ operations = [
316
+ _Operation(method, path, path, _js.as_object(op))
317
+ for path, methods in (paths if isinstance(paths, dict) else {}).items()
318
+ if isinstance(methods, dict)
319
+ for method, op in methods.items()
320
+ if method in _METHODS and isinstance(op, dict)
321
+ ]
322
+ if config.include is not None:
323
+ include = config.include
324
+ operations = [
325
+ o for o in operations if include(OpenapiOperation(o.method, o.path, o.operation))
326
+ ]
327
+ if config.versions == "latest":
328
+ operations = _latest(operations)
329
+ counts: dict[str, int] = {}
330
+ parents: set[str] = set()
331
+ for o in operations:
332
+ counts[o.route] = counts.get(o.route, 0) + 1
333
+ names = [n for n, _ in _namespace(o.route, None)]
334
+ parents.update("/" + "/".join(names[:i]) for i in range(1, len(names)))
335
+ if config.compact:
336
+ for o in operations:
337
+ _compact_operation(o.operation)
338
+
339
+ out: dict[str, Entry] = {}
340
+ for o in operations:
341
+ segments = _segments(o, config.mode, counts, parents)
342
+ command = _command(o, resolved, fetch, config, base_path)
343
+ _place(out, segments, command)
344
+ for path, description in config.groups.items():
345
+ entries = out
346
+ group: Group | None = None
347
+ for name in path.split():
348
+ entry = entries.get(name)
349
+ group = entry if isinstance(entry, Group) else None
350
+ if group is None:
351
+ break
352
+ entries = group.commands
353
+ if group is not None:
354
+ group.description = description
355
+ return out
356
+
357
+
358
+ def _latest(operations: list[_Operation]) -> list[_Operation]:
359
+ """Keeps the highest version of each operation; unversioned paths count as version 0."""
360
+ latest: dict[str, tuple[_Operation, int]] = {}
361
+ for o in operations:
362
+ match = _VERSION.match(o.path)
363
+ version = int(match[1]) if match else 0
364
+ route = (o.path[match.end() :] or "/") if match else o.path
365
+ key = f"{o.method} {re.sub(r'{[^}]+}', '{}', route)}"
366
+ existing = latest.get(key)
367
+ if existing is None or version > existing[1]:
368
+ latest[key] = (_Operation(o.method, o.path, route, o.operation), version)
369
+ return [o for o, _ in latest.values()]
370
+
371
+
372
+ def _compact(schema: dict[str, Json], seen: dict[int, dict[str, Json]]) -> dict[str, Json]:
373
+ """Strips examples, oversized patterns, and date and time formats from a schema."""
374
+ if id(schema) in seen:
375
+ return seen[id(schema)]
376
+ out = dict(schema)
377
+ seen[id(schema)] = out
378
+ out.pop("example", None)
379
+ out.pop("examples", None)
380
+ pattern = out.get("pattern")
381
+ if isinstance(pattern, str) and _js.utf16_len(pattern) > _COMPACT_PATTERN_LIMIT:
382
+ del out["pattern"]
383
+ if out.get("format") in _DATE_TIME_FORMATS:
384
+ del out["format"]
385
+ for key in ("allOf", "anyOf", "oneOf", "prefixItems"):
386
+ value = out.get(key)
387
+ if isinstance(value, list):
388
+ entries = [_compact(e, seen) for e in value if isinstance(e, dict)]
389
+ entries = [e for e in entries if e]
390
+ if entries:
391
+ out[key] = list[Json](entries)
392
+ else:
393
+ del out[key]
394
+ for key in ("additionalProperties", "contains", "items", "not", "propertyNames"):
395
+ value = out.get(key)
396
+ if isinstance(value, dict):
397
+ out[key] = _compact(value, seen)
398
+ for key in ("$defs", "patternProperties", "properties"):
399
+ value = out.get(key)
400
+ if isinstance(value, dict):
401
+ out[key] = {
402
+ k: _compact(v, seen) if isinstance(v, dict) else v for k, v in value.items()
403
+ }
404
+ return out
405
+
406
+
407
+ def _compact_operation(operation: dict[str, Json]) -> None:
408
+ seen: dict[int, dict[str, Json]] = {}
409
+ for parameter in (
410
+ _params(operation, "path") + _params(operation, "query") + _params(operation, "header")
411
+ ):
412
+ schema = parameter.get("schema")
413
+ if isinstance(schema, dict):
414
+ parameter["schema"] = _compact(schema, seen)
415
+ body = _body(operation)
416
+ if body is not None:
417
+ body["schema"] = _compact(_js.as_object(body["schema"]), seen)
418
+
419
+
420
+ def _body(operation: dict[str, Json]) -> dict[str, Json] | None:
421
+ """The `application/json` request body media object, when it has a schema."""
422
+ request = operation.get("requestBody")
423
+ content = request.get("content") if isinstance(request, dict) else None
424
+ media = content.get("application/json") if isinstance(content, dict) else None
425
+ if isinstance(media, dict) and isinstance(media.get("schema"), dict):
426
+ return media
427
+ return None
428
+
429
+
430
+ def _namespace(route: str, operation: dict[str, Json] | None) -> list[tuple[str, str | None]]:
431
+ """The command names of a path's segments, with path parameter descriptions."""
432
+ out: list[tuple[str, str | None]] = []
433
+ for segment in route.split("/"):
434
+ if not segment:
435
+ continue
436
+ name = segment[1:-1] if segment.startswith("{") and segment.endswith("}") else segment
437
+ description = None
438
+ if operation is not None:
439
+ found = next((p for p in _params(operation, "path") if p.get("name") == name), None)
440
+ description = _str(found.get("description")) if found else None
441
+ out.append((re.sub(r"[^\w.-]+", "-", name, flags=re.ASCII), description or None))
442
+ return out
443
+
444
+
445
+ def _segments(
446
+ o: _Operation, mode: str, counts: dict[str, int], parents: set[str]
447
+ ) -> list[tuple[str, str | None]]:
448
+ """Names the command of an operation, with group descriptions along its path."""
449
+ op = o.operation
450
+ if mode == "operation":
451
+ name = _str(op.get("operationId")) or f"{o.method}_{re.sub(r'[/{}]', '_', o.path)}"
452
+ return [(name, None)]
453
+ segments = _namespace(o.route, op)
454
+ path = "/" + "/".join(n for n, _ in segments)
455
+ needs_method = not segments or path in parents or counts.get(o.route, 0) > 1
456
+ description = _str(op.get("summary")) or _str(op.get("description"))
457
+ if description and segments and segments[-1][1] is None:
458
+ segments[-1] = (segments[-1][0], description)
459
+ return [*(segments or [("root", None)]), *([(o.method, None)] if needs_method else [])]
460
+
461
+
462
+ def _place(
463
+ commands: dict[str, Entry], segments: list[tuple[str, str | None]], command: Command
464
+ ) -> None:
465
+ (name, description), *rest = segments
466
+ if not rest:
467
+ commands[name] = command
468
+ return
469
+ existing = commands.get(name)
470
+ if isinstance(existing, Group):
471
+ if not existing.description and description:
472
+ existing.description = description
473
+ group = existing
474
+ else:
475
+ group = Group({}, description)
476
+ commands[name] = group
477
+ _place(group.commands, rest, command)
478
+
479
+
480
+ def _security_headers(
481
+ document: dict[str, Json], operation: dict[str, Json]
482
+ ) -> list[dict[str, Json]]:
483
+ """Header parameters for the credentials an operation's security requirements name."""
484
+ components = document.get("components")
485
+ schemes = components.get("securitySchemes") if isinstance(components, dict) else None
486
+ schemes = schemes if isinstance(schemes, dict) else {}
487
+ requirements = operation.get("security", document.get("security"))
488
+ headers: list[dict[str, Json]] = []
489
+ for requirement in requirements if isinstance(requirements, list) else []:
490
+ for name in requirement if isinstance(requirement, dict) else {}:
491
+ scheme = schemes.get(name)
492
+ if not isinstance(scheme, dict):
493
+ continue
494
+ kind, where, header = scheme.get("type"), scheme.get("in"), _str(scheme.get("name"))
495
+ description = _str(scheme.get("description"))
496
+ http = _str(scheme.get("scheme")) or ""
497
+ if kind == "apiKey" and where == "header" and header:
498
+ headers.append(_header(header, description or f"{header} header"))
499
+ elif kind == "http" and http.lower() in ("basic", "bearer"):
500
+ headers.append(
501
+ _header("authorization", description or f"{name} authorization header")
502
+ )
503
+ return headers
504
+
505
+
506
+ def _header(name: str, description: str) -> dict[str, Json]:
507
+ return {
508
+ "description": description,
509
+ "in": "header",
510
+ "name": name,
511
+ "required": False,
512
+ "schema": {"type": "string"},
513
+ }
514
+
515
+
516
+ def _param_type(parameter: dict[str, Json], required: bool) -> Type:
517
+ schema = parameter.get("schema")
518
+ ty = convert(schema) if isinstance(schema, dict) else Type("string", raw={"type": "string"})
519
+ if not required:
520
+ ty = optional(ty)
521
+ description = _str(parameter.get("description"))
522
+ return describe(ty, description) if description else ty
523
+
524
+
525
+ def _command(
526
+ o: _Operation,
527
+ document: dict[str, Json],
528
+ fetch: FetchHandler,
529
+ config: OpenapiConfig,
530
+ base_path: str | None,
531
+ ) -> Command:
532
+ op = o.operation
533
+ path_params = _params(op, "path")
534
+ query_params = _params(op, "query")
535
+ declared = _params(op, "header") + (_security_headers(document, op) if config.security else [])
536
+ headers: list[tuple[str, dict[str, Json]]] = []
537
+ seen: set[str] = set()
538
+ for parameter in declared:
539
+ normalized = str(parameter.get("name")).lower()
540
+ if normalized not in seen:
541
+ seen.add(normalized)
542
+ headers.append((normalized, parameter))
543
+ body = _body(op)
544
+ body_schema = _js.as_object(body["schema"]) if body else {}
545
+ body_props = body_schema.get("properties")
546
+ body_props = body_props if isinstance(body_props, dict) else {}
547
+ body_required = body_schema.get("required")
548
+ body_required = body_required if isinstance(body_required, list) else []
549
+
550
+ used = {str(p.get("name")) for p in query_params} | set(body_props)
551
+ header_options: list[tuple[str, dict[str, Json]]] = []
552
+ for normalized, parameter in headers:
553
+ option = normalized
554
+ if option in used:
555
+ prefix = f"header-{option}"
556
+ option = prefix
557
+ index = 2
558
+ while option in used:
559
+ option = f"{prefix}-{index}"
560
+ index += 1
561
+ used.add(option)
562
+ header_options.append((option, parameter))
563
+
564
+ args = (
565
+ object_type([Field(str(p.get("name")), coerce(_param_type(p, True))) for p in path_params])
566
+ if path_params
567
+ else None
568
+ )
569
+ fields: dict[str, Field] = {}
570
+ for p in query_params:
571
+ name = str(p.get("name"))
572
+ fields[name] = Field(name, coerce(_param_type(p, p.get("required") is True)))
573
+ for key, schema in body_props.items():
574
+ ty = convert(schema)
575
+ fields[key] = Field(key, ty if key in body_required else optional(ty))
576
+ for option, p in header_options:
577
+ ty = _param_type({**p, "description": None}, p.get("required") is True)
578
+ description = _str(p.get("description")) or f"{p.get('name')} header"
579
+ fields[option] = Field(option, coerce(describe(ty, description)))
580
+ options = object_type(list(fields.values())) if fields else None
581
+
582
+ summary, description = _str(op.get("summary")), _str(op.get("description"))
583
+ read_only = o.method in ("get", "head", "options", "trace")
584
+ annotations: dict[str, Json] = {
585
+ "destructiveHint": not read_only,
586
+ "idempotentHint": read_only or o.method in ("delete", "put"),
587
+ "openWorldHint": True,
588
+ "readOnlyHint": read_only,
589
+ }
590
+ # Help keeps the short summary; MCP tools surface the full prose.
591
+ prose = (
592
+ f"{summary}\n\n{description}"
593
+ if summary and description and summary != description
594
+ else None
595
+ )
596
+ method = o.method.upper()
597
+
598
+ async def handler(c: Context[Any, Any]) -> Json:
599
+ args_in: dict[str, Json] = c.args or {}
600
+ options_in: dict[str, Json] = c.options or {}
601
+ url_path = (base_path or "") + o.path
602
+ for p in path_params:
603
+ name = str(p.get("name"))
604
+ if name in args_in:
605
+ url_path = url_path.replace(f"{{{name}}}", _js.to_string(args_in[name]), 1)
606
+ query: list[tuple[str, str]] = []
607
+ for p in query_params:
608
+ name = str(p.get("name"))
609
+ if options_in.get(name) is not None:
610
+ query.append((name, _js.to_string(options_in[name])))
611
+ payload = {k: options_in[k] for k in body_props if options_in.get(k) is not None}
612
+ request_headers = Headers()
613
+ for option, p in header_options:
614
+ if options_in.get(option) is not None:
615
+ request_headers.set(str(p.get("name")), _js.to_string(options_in[option]))
616
+ incoming = c.request
617
+ for name in config.forward_headers:
618
+ value = incoming.headers.get(name) if incoming is not None else None
619
+ if name not in request_headers and value is not None:
620
+ request_headers.set(name, value)
621
+ data = _gateway.Input(
622
+ url_path,
623
+ method,
624
+ request_headers,
625
+ _js.stringify(payload) if payload else None,
626
+ query,
627
+ )
628
+ response = await call(fetch, _gateway.build_request(data))
629
+ result = await _gateway.read(response)
630
+ if not response.ok:
631
+ raise Error(*_gateway.error_of(result, response.status))
632
+ return result
633
+
634
+ return Command(
635
+ handler=handler,
636
+ args=args,
637
+ options=options,
638
+ description=summary or description,
639
+ mcp=ToolMeta(description=prose, annotations=annotations),
640
+ )