Metadata-Version: 2.4
Name: appport-sdk
Version: 0.1.0
Summary: Define once, expose twice: turn one Python tool definition into an MCP server and a CLI.
Author: AppPort contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/RookieApe-tao/appport-sdk
Project-URL: Companion, https://github.com/RookieApe-tao/appport-bridge
Keywords: mcp,cli,tools,llm,json-schema
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: mcp<3,>=2
Requires-Dist: anyio>=4.9
Requires-Dist: typer>=0.12
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: jsonschema>=4; extra == "test"
Dynamic: license-file

# appport-sdk

[![CI](https://github.com/RookieApe-tao/appport-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/RookieApe-tao/appport-sdk/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12-blue)](https://github.com/RookieApe-tao/appport-sdk)

**Define once, expose twice.** Write a Python function, get an MCP server *and* a
command-line tool from the same definition — no duplicated schemas, no drifting
help text.

```text
                    ┌──────────────────────────┐
  Python function → │  @tool  →  ToolDefinition │ → MCP server  (stdio, tools/list + tools/call)
  (one definition)  └──────────────────────────┘ → CLI         (one subcommand per tool, JSON out)
```

Both exits are generated from the **same** `ToolDefinition`:
`to_json_schema()` feeds the MCP `inputSchema`, `to_cli_args()` feeds the Typer
options. Every call — from either exit — returns the shared envelope, so an LLM
and a shell script see identical results.

## Quick start

```powershell
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ".[test]"
```

Requires **`mcp>=2,<3`** and `typer>=0.12` on Python 3.11+. The MCP exit is built
on the mcp 2.x low-level `Server` API (`on_list_tools` / `on_call_tool`); the
older 1.x `mcp.server.fastmcp` API no longer exists in 2.x. `appport-bridge`
already runs on mcp v2, so both repositories pin the same `mcp>=2,<3` window and
stay installable side by side.

Define a tool (`examples/demo_tools.py` has three):

```python
from appport_sdk import Returns, ToolRegistry, tool

@tool(returns=Returns(type="str", description="The echoed text."))
def echo(text: str, loud: bool = False) -> str:
    """Echo text back.

    Args:
        text: Text to echo.
        loud: Upper-case the result.
    """
    return text.upper() if loud else text

TOOLS = ToolRegistry([echo])
```

### Exit 1 — CLI

```powershell
appport-sdk --tools examples.demo_tools:TOOLS echo --text "hi" --loud
```
```json
{
  "ok": true,
  "data": "HI"
}
```

Each tool becomes a subcommand; parameters become `--kebab-case` options, bools
become `--flag/--no-flag` pairs, and required params are enforced by Click. A
call that reaches the tool prints the JSON envelope on stdout and exits `0` (or
`1` when the tool itself fails). A Click-level usage or type error — a missing
required option, an unparseable value — is reported by Click as usual and exits
`2` without JSON. Without `--tools` the CLI reads `APPPORT_TOOLS`.

### Exit 2 — MCP

```powershell
appport-sdk-mcp --tools examples.demo_tools:TOOLS     # or: python -m appport_sdk.mcp_server
```

Add it to any MCP client (Claude Desktop / Cursor / …):

```json
{
  "mcpServers": {
    "appport-demo": {
      "command": "appport-sdk-mcp",
      "args": ["--tools", "examples.demo_tools:TOOLS"]
    }
  }
}
```

`tools/list` advertises exactly the shared `ToolDefinition` schema
(`additionalProperties: false`), and `tools/call` returns the envelope:

```json
{"ok": true, "data": "HI"}
```

### Both exits at once

```powershell
python examples/demo_tools.py
```

This drives the CLI through real subprocesses and then starts the MCP server as a
real stdio subprocess and calls it with the official `mcp` client — the single
definition, exercised twice.

## The shared ToolDefinition spec (v0.1)

```python
{
  "name": "snake_case_unique",
  "description": "what the LLM reads",
  "params": [{"name": str, "type": "str|int|float|bool",
              "description": str, "required": bool, "default": any}],
  "returns": {"type": "str|json", "description": str},
  "examples": [{"args": {...}, "result_hint": str}],   # optional
}
```

Result envelope — success `{"ok": true, "data": ...}`, failure
`{"ok": false, "error": {"code": ..., "message": ...}}`. Every call that reaches
the SDK — from MCP or from the CLI — returns that envelope, and the SDK converts
missing/invalid arguments and any exception raised by your function into the
failure form; it never lets a raw traceback escape.

One caveat on the CLI: Click parses arguments *before* the SDK sees them, so an
unknown option or an unparseable value is rejected by Click itself with a usage
message and exit code `2` — no JSON for those. Failures after parsing
(validation against the definition, your function raising, a `ToolError`) are
always JSON with exit `1`. MCP calls always go through the SDK, so they get the
envelope in every case.

Error codes: `MISSING_PARAMETER`, `INVALID_ARGUMENT`, `UNKNOWN_PARAMETER`
(CLI/local calls), `UNKNOWN_TOOL` (an MCP `tools/call` for a name that is not
registered), `TOOL_ERROR` (your `ToolError`), `INTERNAL_ERROR`.

## API notes

| Piece | Where | Notes |
| --- | --- | --- |
| `ToolDefinition`, `Param`, `Returns`, `Example` | `appport_sdk.definition` | immutable; `to_json_schema()`, `to_cli_args()`, `to_dict()`, `from_dict()` |
| `@tool(...)` | `appport_sdk.decorators` | returns the *original* function with `.definition` attached; `ToolRegistry` collects them |
| `invoke()` / `invoke_async()` | `appport_sdk.runner` | validation, coercion, envelope wrapping |
| `build_cli()` / `serve_cli()` | `appport_sdk.cli` | Typer app; `build_cli` returns an app you can test |
| `build_mcp_server()` / `serve_mcp()` | `appport_sdk.mcp_server` | mcp v2 low-level `Server` over stdio |

* Type mapping: `str → string`, `int → integer`, `float → number`,
  `bool → boolean`. A parameter with a default is `required: false` and its
  default lands in the JSON Schema.
* `description` comes from `@tool(description=...)`, else the first paragraph of
  the docstring, else the function name.
* `Optional[str]`-style annotations unwrap to their base type.
* `mcp>=2,<3` (v2 low-level `Server` API); `typer>=0.12`. Python 3.11+.

## Relation to appport-bridge

[AppPort Bridge](https://github.com/RookieApe-tao/appport-bridge) gives an
existing Windows desktop app an MCP port; **this SDK is the other half — it
produces `ToolDefinition`s in the exact same v0.1 shape**, so tools built here
and definitions produced by the bridge are interchangeable.

## Development

```powershell
.\.venv\Scripts\python.exe -m pytest -q
```

## License

MIT

Business model: open core with enterprise features.
