appport-sdk 0.1.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.
@@ -0,0 +1,98 @@
1
+ """AppPort SDK — define a tool once, expose it as an MCP server *and* a CLI.
2
+
3
+ >>> from appport_sdk import tool, ToolRegistry
4
+ >>> @tool(description="Say hello.")
5
+ ... def echo(text: str) -> str:
6
+ ... '''Echo the text back.'''
7
+ ... return text
8
+ >>> echo.definition.name
9
+ 'echo'
10
+
11
+ The same :class:`~appport_sdk.definition.ToolDefinition` drives
12
+ :func:`serve_mcp` (official ``mcp`` package, stdio) and :func:`serve_cli`
13
+ (Typer subcommands), so the two exits can never drift apart.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from .decorators import (
19
+ ToolRegistry,
20
+ build_definition,
21
+ definition_of,
22
+ is_tool,
23
+ tool,
24
+ )
25
+ from .definition import (
26
+ PARAM_TYPES,
27
+ RETURN_TYPES,
28
+ DefinitionError,
29
+ Example,
30
+ Param,
31
+ Returns,
32
+ ToolDefinition,
33
+ definitions_from,
34
+ )
35
+ from .errors import (
36
+ INTERNAL_ERROR,
37
+ INVALID_ARGUMENT,
38
+ MISSING_PARAMETER,
39
+ TOOL_ERROR,
40
+ UNKNOWN_PARAMETER,
41
+ UNKNOWN_TOOL,
42
+ ToolError,
43
+ failure,
44
+ success,
45
+ )
46
+ from .runner import invoke, invoke_async, validate_arguments
47
+
48
+ __version__ = "0.1.0"
49
+
50
+ __all__ = [
51
+ "INTERNAL_ERROR",
52
+ "INVALID_ARGUMENT",
53
+ "MISSING_PARAMETER",
54
+ "PARAM_TYPES",
55
+ "RETURN_TYPES",
56
+ "TOOL_ERROR",
57
+ "UNKNOWN_PARAMETER",
58
+ "UNKNOWN_TOOL",
59
+ "DefinitionError",
60
+ "Example",
61
+ "Param",
62
+ "Returns",
63
+ "ToolDefinition",
64
+ "ToolError",
65
+ "ToolRegistry",
66
+ "__version__",
67
+ "build_definition",
68
+ "definition_of",
69
+ "definitions_from",
70
+ "failure",
71
+ "invoke",
72
+ "invoke_async",
73
+ "is_tool",
74
+ "success",
75
+ "tool",
76
+ "validate_arguments",
77
+ ]
78
+
79
+
80
+ def __getattr__(name: str):
81
+ """Lazily import the exits so ``mcp``/``typer`` stay optional at import time."""
82
+ if name == "serve_mcp":
83
+ from .mcp_server import serve_mcp
84
+
85
+ return serve_mcp
86
+ if name == "build_mcp_server":
87
+ from .mcp_server import build_mcp_server
88
+
89
+ return build_mcp_server
90
+ if name == "serve_cli":
91
+ from .cli import serve_cli
92
+
93
+ return serve_cli
94
+ if name == "build_cli":
95
+ from .cli import build_cli
96
+
97
+ return build_cli
98
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
appport_sdk/cli.py ADDED
@@ -0,0 +1,215 @@
1
+ """CLI exit: expose the same tool definitions as a Typer command group.
2
+
3
+ Each tool becomes one subcommand; parameters are mapped from the
4
+ :class:`ToolDefinition` (``--name`` form, Python type, required/optional,
5
+ booleans as flags). Output is a single JSON document on stdout::
6
+
7
+ PS> appport-sdk --tools examples.demo_tools:TOOLS echo --text hello
8
+ {
9
+ "ok": true,
10
+ "data": "hello"
11
+ }
12
+
13
+ A tool that fails still prints JSON, but exits with status 1 so scripts can
14
+ branch on it. Invalid command-line syntax (missing required option, bad type)
15
+ is handled by Click and exits with status 2.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import inspect
21
+ import json
22
+ import os
23
+ import sys
24
+ from typing import Any, Callable, Iterable, Optional, Sequence
25
+
26
+ import typer
27
+
28
+ from .decorators import definition_of, python_type_for
29
+ from .definition import ToolDefinition, definitions_from
30
+ from .runner import invoke
31
+
32
+ APP_NAME = "appport-sdk"
33
+ #: Exit code when the tool itself returned ``{"ok": false, ...}``.
34
+ EXIT_TOOL_ERROR = 1
35
+ #: Exit code for usage problems detected before a tool ran.
36
+ EXIT_USAGE = 2
37
+
38
+ #: Environment variable holding ``module:attribute`` for console-script runs.
39
+ TOOLS_ENV_VAR = "APPPORT_TOOLS"
40
+
41
+
42
+ def _option_for(param: Any) -> Any:
43
+ """Map one spec param to a ``typer.Option`` default."""
44
+ option = param.option_string()
45
+ if param.type == "bool":
46
+ pair = option + "/--no-" + param.name.replace("_", "-")
47
+ if param.required:
48
+ return typer.Option(..., pair, help=param.description)
49
+ # ``None`` means "not given", so the ToolDefinition default (True or
50
+ # False) is applied by the runner instead of a guessed CLI default.
51
+ return typer.Option(None, pair, help=param.description)
52
+ if param.required:
53
+ return typer.Option(..., option, help=param.description)
54
+ return typer.Option(param.default, option, help=param.description)
55
+
56
+
57
+ def _annotation_for(param: Any) -> Any:
58
+ """CLI annotation; optional booleans must be ``bool | None`` for Typer."""
59
+ py_type = python_type_for(param.type)
60
+ if param.type == "bool" and not param.required:
61
+ return Optional[bool]
62
+ return py_type
63
+
64
+
65
+ def dumps(payload: dict[str, Any]) -> str:
66
+ """Serialize an envelope for the CLI (stable, UTF-8 friendly)."""
67
+ return json.dumps(payload, ensure_ascii=False, indent=2)
68
+
69
+
70
+ def _make_command(definition: ToolDefinition, func: Callable[..., Any]) -> Any:
71
+ """Build the Click callback for one tool."""
72
+
73
+ def command(**kwargs: Any) -> None:
74
+ result = invoke(definition, func, kwargs)
75
+ typer.echo(dumps(result))
76
+ if not result.get("ok", False):
77
+ raise typer.Exit(code=EXIT_TOOL_ERROR)
78
+
79
+ command.__name__ = f"cmd_{definition.name}"
80
+ command.__doc__ = definition.description
81
+ command.__signature__ = inspect.Signature( # type: ignore[attr-defined]
82
+ [
83
+ inspect.Parameter(
84
+ param.name,
85
+ inspect.Parameter.KEYWORD_ONLY,
86
+ default=_option_for(param),
87
+ annotation=_annotation_for(param),
88
+ )
89
+ for param in definition.params
90
+ ]
91
+ )
92
+ return command
93
+
94
+
95
+ def build_cli(
96
+ tools: Iterable[Any],
97
+ *,
98
+ name: str = APP_NAME,
99
+ version: str | None = None,
100
+ ) -> typer.Typer:
101
+ """Create (but do not run) the Typer app for ``tools``."""
102
+ from . import __version__ as package_version
103
+
104
+ app = typer.Typer(
105
+ name=name,
106
+ help="Call AppPort tools from the command line. Output is JSON.",
107
+ add_completion=False,
108
+ invoke_without_command=True,
109
+ pretty_exceptions_short=True,
110
+ )
111
+
112
+ @app.callback()
113
+ def _root(
114
+ ctx: typer.Context,
115
+ version_flag: bool = typer.Option(
116
+ False, "--version", help="Show the CLI version and exit.", is_eager=True
117
+ ),
118
+ ) -> None:
119
+ """AppPort SDK command line: one subcommand per tool."""
120
+ if version_flag:
121
+ typer.echo(version or package_version)
122
+ raise typer.Exit()
123
+ if ctx.invoked_subcommand is None:
124
+ typer.echo(ctx.get_help())
125
+ raise typer.Exit()
126
+
127
+ for item in tools:
128
+ if isinstance(item, (dict, ToolDefinition)):
129
+ definition = definitions_from([item])[0]
130
+ raise ValueError(
131
+ f"tool {definition.name!r} was given as a definition only; "
132
+ "the CLI needs an implementation to call"
133
+ )
134
+ definition = definition_of(item)
135
+ app.command(
136
+ name=definition.name,
137
+ help=definition.description,
138
+ short_help=definition.description.splitlines()[0][:60],
139
+ )(_make_command(definition, item))
140
+ return app
141
+
142
+
143
+ def serve_cli(tools: Iterable[Any], *, name: str = APP_NAME) -> None:
144
+ """Serve ``tools`` as CLI subcommands (blocking)."""
145
+ build_cli(tools, name=name)()
146
+
147
+
148
+ def load_tools(spec: str) -> Sequence[Any]:
149
+ """Resolve ``"package.module:attribute"`` to a tool collection."""
150
+ import importlib
151
+
152
+ if ":" not in spec:
153
+ raise SystemExit(
154
+ f"{TOOLS_ENV_VAR} must look like 'module.path:TOOLS', got {spec!r}"
155
+ )
156
+ module_name, _, attr = spec.partition(":")
157
+ module = importlib.import_module(module_name)
158
+ try:
159
+ target = getattr(module, attr)
160
+ except AttributeError as exc:
161
+ raise SystemExit(f"{module_name} has no attribute {attr!r}") from exc
162
+ if isinstance(target, dict) and "name" in target:
163
+ return [target]
164
+ try:
165
+ return list(target)
166
+ except TypeError as exc: # pragma: no cover - defensive
167
+ raise SystemExit(f"{spec!r} is not a tool collection") from exc
168
+
169
+
170
+ def split_tools_option(argv: Sequence[str]) -> tuple[str | None, list[str]]:
171
+ """Pull a leading ``--tools module:attr`` out of ``argv``."""
172
+ remaining: list[str] = []
173
+ spec: str | None = None
174
+ index = 0
175
+ while index < len(argv):
176
+ item = argv[index]
177
+ if item == "--tools":
178
+ if index + 1 >= len(argv):
179
+ raise SystemExit("--tools needs a 'module:attribute' value")
180
+ spec = argv[index + 1]
181
+ index += 2
182
+ continue
183
+ if item.startswith("--tools="):
184
+ spec = item.split("=", 1)[1]
185
+ index += 1
186
+ continue
187
+ remaining.append(item)
188
+ index += 1
189
+ return spec, remaining
190
+
191
+
192
+ def main(argv: Sequence[str] | None = None) -> int:
193
+ """Console-script entry point (``appport-sdk``)."""
194
+ args = list(sys.argv[1:] if argv is None else argv)
195
+ spec, args = split_tools_option(args)
196
+ spec = spec or os.environ.get(TOOLS_ENV_VAR)
197
+ if not spec:
198
+ typer.echo(
199
+ "appport-sdk: no tools given.\n\n"
200
+ "Pass --tools module:attribute (or set APPPORT_TOOLS), for example:\n"
201
+ " appport-sdk --tools examples.demo_tools:TOOLS echo --text hi",
202
+ err=True,
203
+ )
204
+ return EXIT_USAGE
205
+ if os.getcwd() not in sys.path:
206
+ sys.path.insert(0, os.getcwd())
207
+ # Pass the argument list as a single value: ``app(*args)`` would hand
208
+ # Click extra positionals and it would reinterpret the first flag as a
209
+ # command name.
210
+ build_cli(load_tools(spec))(args)
211
+ return 0
212
+
213
+
214
+ if __name__ == "__main__": # pragma: no cover - entry point
215
+ raise SystemExit(main())
@@ -0,0 +1,336 @@
1
+ """``@tool`` decorator: turn a plain Python function into a described tool.
2
+
3
+ The decorated function is returned unchanged (so it stays callable and
4
+ importable), with a ``.definition`` attribute holding its
5
+ :class:`~appport_sdk.definition.ToolDefinition`.
6
+
7
+ >>> from appport_sdk import tool
8
+ >>> @tool()
9
+ ... def add(a: int, b: int) -> int:
10
+ ... '''Add two integers.'''
11
+ ... return a + b
12
+ >>> add.definition.name
13
+ 'add'
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import inspect
19
+ import types
20
+ import typing
21
+ from typing import Any, Callable, Iterable, Iterator, Mapping, Sequence
22
+
23
+ from .definition import (
24
+ PARAM_TYPES,
25
+ DefinitionError,
26
+ Example,
27
+ Param,
28
+ Returns,
29
+ ToolDefinition,
30
+ )
31
+
32
+ _PY_TO_SPEC = {
33
+ str: "str",
34
+ int: "int",
35
+ float: "float",
36
+ bool: "bool",
37
+ }
38
+
39
+ _SPEC_TO_PY = {value: key for key, value in _PY_TO_SPEC.items()}
40
+
41
+ #: Attribute set on decorated functions.
42
+ DEFINITION_ATTR = "__appport_tool__"
43
+
44
+
45
+ def python_type_for(spec_type: str) -> type:
46
+ """Map a spec type (``"str"``…) back to the Python type."""
47
+ try:
48
+ return _SPEC_TO_PY[spec_type]
49
+ except KeyError as exc: # pragma: no cover - guarded by Param.validate
50
+ raise DefinitionError(f"unknown spec type {spec_type!r}") from exc
51
+
52
+
53
+ def _first_paragraph(doc: str | None) -> str:
54
+ """Return the first paragraph of a docstring, collapsed to one line."""
55
+ if not doc:
56
+ return ""
57
+ lines: list[str] = []
58
+ for line in inspect.cleandoc(doc).splitlines():
59
+ stripped = line.strip()
60
+ if not stripped:
61
+ if lines:
62
+ break
63
+ continue
64
+ lines.append(stripped)
65
+ return " ".join(lines)
66
+
67
+
68
+ def _docstring_params(doc: str | None) -> dict[str, str]:
69
+ """Parse an ``Args:``/``Arguments:`` block into ``{param: description}``."""
70
+ if not doc:
71
+ return {}
72
+ found: dict[str, str] = {}
73
+ in_args = False
74
+ for raw in inspect.cleandoc(doc).splitlines():
75
+ stripped = raw.strip()
76
+ if not in_args:
77
+ if stripped.rstrip(":").lower() in ("args", "arguments", "params"):
78
+ in_args = True
79
+ continue
80
+ if not stripped:
81
+ continue
82
+ if not raw[:1].isspace(): # a new, un-indented section header
83
+ in_args = False
84
+ continue
85
+ name, sep, description = stripped.partition(":")
86
+ if not sep:
87
+ continue
88
+ name = name.strip().split(" ")[0].strip("`")
89
+ if name:
90
+ found[name] = description.strip()
91
+ return found
92
+
93
+
94
+ def annotation_to_spec(annotation: Any) -> str | None:
95
+ """Map a Python annotation to a spec type, or ``None`` if unsupported."""
96
+ if annotation is inspect.Parameter.empty:
97
+ return None
98
+ if isinstance(annotation, str):
99
+ # ``from __future__ import annotations`` leaves raw strings behind.
100
+ text = annotation.strip()
101
+ resolved = {
102
+ "str": "str",
103
+ "int": "int",
104
+ "float": "float",
105
+ "bool": "bool",
106
+ "builtins.str": "str",
107
+ "builtins.int": "int",
108
+ "builtins.float": "float",
109
+ "builtins.bool": "bool",
110
+ }.get(text)
111
+ if resolved is not None:
112
+ return resolved
113
+ # ``Optional[int]`` / ``int | None`` spelled as a string.
114
+ bare = text.removeprefix("typing.")
115
+ for spec_name in PARAM_TYPES:
116
+ if bare in (f"Optional[{spec_name}]", f"{spec_name} | None",
117
+ f"None | {spec_name}"):
118
+ return spec_name
119
+ return None
120
+ origin = typing.get_origin(annotation)
121
+ if origin in (typing.Union, getattr(types, "UnionType", None)): # Optional[X]
122
+ args = [a for a in typing.get_args(annotation) if a is not type(None)]
123
+ if len(args) == 1:
124
+ return annotation_to_spec(args[0])
125
+ return None
126
+ return _PY_TO_SPEC.get(annotation)
127
+
128
+
129
+ def _describe_returns(func: Callable[..., Any]) -> Returns:
130
+ declared = getattr(func, "__appport_returns__", None)
131
+ if isinstance(declared, Returns):
132
+ return declared
133
+ if isinstance(declared, Mapping):
134
+ return Returns(
135
+ type=str(declared.get("type", "json")),
136
+ description=str(declared.get("description", "")),
137
+ )
138
+ try:
139
+ annotation = inspect.signature(func).return_annotation
140
+ except (TypeError, ValueError): # pragma: no cover - builtins
141
+ annotation = inspect.Signature.empty
142
+ if annotation is inspect.Signature.empty:
143
+ return Returns(type="json", description="")
144
+ spec = annotation_to_spec(annotation)
145
+ if spec == "str":
146
+ return Returns(type="str", description="")
147
+ return Returns(type="json", description="")
148
+
149
+
150
+ def build_definition(
151
+ func: Callable[..., Any],
152
+ *,
153
+ description: str | None = None,
154
+ name: str | None = None,
155
+ examples: Sequence[Example | Mapping[str, Any]] | None = None,
156
+ returns: Returns | Mapping[str, Any] | None = None,
157
+ ) -> ToolDefinition:
158
+ """Introspect ``func`` and build its :class:`ToolDefinition`."""
159
+ if not callable(func):
160
+ raise DefinitionError("@tool expects a callable")
161
+ signature = inspect.signature(func)
162
+ doc_params = _docstring_params(func.__doc__)
163
+ params: list[Param] = []
164
+ for parameter in signature.parameters.values():
165
+ if parameter.kind in (
166
+ inspect.Parameter.VAR_POSITIONAL,
167
+ inspect.Parameter.VAR_KEYWORD,
168
+ ):
169
+ raise DefinitionError(
170
+ f"{func.__name__}: *args/**kwargs are not supported by the shared "
171
+ "ToolDefinition spec"
172
+ )
173
+ if parameter.kind is inspect.Parameter.POSITIONAL_ONLY:
174
+ raise DefinitionError(
175
+ f"{func.__name__}: positional-only parameters are not supported"
176
+ )
177
+ spec_type = annotation_to_spec(parameter.annotation)
178
+ if spec_type is None:
179
+ hint = (
180
+ "missing annotation"
181
+ if parameter.annotation is inspect.Parameter.empty
182
+ else f"unsupported annotation {parameter.annotation!r}"
183
+ )
184
+ raise DefinitionError(
185
+ f"{func.__name__}: parameter {parameter.name!r} has {hint}; "
186
+ f"annotate it with one of {', '.join(PARAM_TYPES)}"
187
+ )
188
+ has_default = parameter.default is not inspect.Parameter.empty
189
+ params.append(
190
+ Param(
191
+ name=parameter.name,
192
+ type=spec_type,
193
+ description=doc_params.get(parameter.name, ""),
194
+ required=not has_default,
195
+ default=parameter.default if has_default else None,
196
+ )
197
+ )
198
+
199
+ if description is not None:
200
+ effective_description = description.strip()
201
+ else:
202
+ effective_description = _first_paragraph(func.__doc__)
203
+
204
+ if returns is not None:
205
+ returns_obj = (
206
+ returns
207
+ if isinstance(returns, Returns)
208
+ else Returns(
209
+ type=str(returns.get("type", "json")),
210
+ description=str(returns.get("description", "")),
211
+ )
212
+ )
213
+ else:
214
+ returns_obj = _describe_returns(func)
215
+
216
+ example_objs = tuple(
217
+ ex if isinstance(ex, Example) else Example(
218
+ args=dict(ex.get("args", {})), result_hint=str(ex.get("result_hint", ""))
219
+ )
220
+ for ex in (examples or ())
221
+ )
222
+
223
+ definition = ToolDefinition(
224
+ name=name or func.__name__,
225
+ description=effective_description or func.__name__,
226
+ params=tuple(params),
227
+ returns=returns_obj,
228
+ examples=example_objs,
229
+ )
230
+ definition.validate()
231
+ return definition
232
+
233
+
234
+ def tool(
235
+ _func: Callable[..., Any] | None = None,
236
+ *,
237
+ description: str | None = None,
238
+ name: str | None = None,
239
+ returns: Returns | Mapping[str, Any] | None = None,
240
+ examples: Sequence[Example | Mapping[str, Any]] | None = None,
241
+ ) -> Callable[..., Any]:
242
+ """Declare a function as a tool.
243
+
244
+ Usable bare (``@tool``) or with keywords (``@tool(description="…")``).
245
+ """
246
+
247
+ def decorate(func: Callable[..., Any]) -> Callable[..., Any]:
248
+ definition = build_definition(
249
+ func,
250
+ description=description,
251
+ name=name,
252
+ returns=returns,
253
+ examples=examples,
254
+ )
255
+ setattr(func, DEFINITION_ATTR, definition)
256
+ setattr(func, "definition", definition)
257
+ return func
258
+
259
+ if _func is not None:
260
+ if not callable(_func):
261
+ raise TypeError("@tool expects a callable or keyword arguments")
262
+ return decorate(_func)
263
+ return decorate
264
+
265
+
266
+ def definition_of(func: Any) -> ToolDefinition:
267
+ """Return the definition attached to ``func`` (or build one on the fly)."""
268
+ existing = getattr(func, DEFINITION_ATTR, None)
269
+ if isinstance(existing, ToolDefinition):
270
+ return existing
271
+ if isinstance(func, ToolDefinition): # convenience for tests
272
+ return func
273
+ return build_definition(func)
274
+
275
+
276
+ def is_tool(func: Any) -> bool:
277
+ return isinstance(getattr(func, DEFINITION_ATTR, None), ToolDefinition)
278
+
279
+
280
+ class ToolRegistry:
281
+ """An ordered collection of tools, ready for either exit."""
282
+
283
+ def __init__(self, tools: Iterable[Callable[..., Any]] = ()) -> None:
284
+ self._tools: dict[str, Callable[..., Any]] = {}
285
+ for item in tools:
286
+ self.add(item)
287
+
288
+ def add(self, func: Callable[..., Any]) -> Callable[..., Any]:
289
+ definition = definition_of(func)
290
+ if definition.name in self._tools:
291
+ raise DefinitionError(f"duplicate tool name {definition.name!r}")
292
+ self._tools[definition.name] = func
293
+ return func
294
+
295
+ #: Alias so ``@registry.register`` works as a decorator too.
296
+ register = add
297
+
298
+ def remove(self, name: str) -> None:
299
+ del self._tools[name]
300
+
301
+ def get(self, name: str) -> Callable[..., Any]:
302
+ return self._tools[name]
303
+
304
+ def definitions(self) -> list[ToolDefinition]:
305
+ return [definition_of(func) for func in self._tools.values()]
306
+
307
+ @property
308
+ def tools(self) -> list[Callable[..., Any]]:
309
+ return list(self._tools.values())
310
+
311
+ def __iter__(self) -> Iterator[Callable[..., Any]]:
312
+ return iter(self._tools.values())
313
+
314
+ def __len__(self) -> int:
315
+ return len(self._tools)
316
+
317
+ def __contains__(self, name: object) -> bool:
318
+ return name in self._tools
319
+
320
+ def __getitem__(self, name: str) -> Callable[..., Any]:
321
+ return self._tools[name]
322
+
323
+ def __repr__(self) -> str: # pragma: no cover - trivial
324
+ return f"ToolRegistry({', '.join(self._tools)})"
325
+
326
+
327
+ __all__ = [
328
+ "DEFINITION_ATTR",
329
+ "ToolRegistry",
330
+ "annotation_to_spec",
331
+ "build_definition",
332
+ "definition_of",
333
+ "is_tool",
334
+ "python_type_for",
335
+ "tool",
336
+ ]