diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..3d2554c
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,9 @@
+# NitroStack Python SDK / CLI — analytics (see docs/analytics-events.md)
+# Optional: override the built-in public PostHog project key (never commit non-public values).
+NITROSTACK_POSTHOG_KEY=
+# Optional: PostHog ingest host (default US Cloud).
+NITROSTACK_POSTHOG_HOST=https://us.i.posthog.com
+# production | staging | development (default: inferred from NODE_ENV / CI).
+NITROSTACK_ENVIRONMENT=
+# Set to 0/false/off to disable CLI telemetry (DO_NOT_TRACK=1 also disables).
+NITROSTACK_TELEMETRY=
diff --git a/.file_length_baseline.json b/.file_length_baseline.json
new file mode 100644
index 0000000..09d5ef1
--- /dev/null
+++ b/.file_length_baseline.json
@@ -0,0 +1,14 @@
+{
+ "examples/flight_booking_server.py": 582,
+ "nitrostack/auth/oauth.py": 516,
+ "nitrostack/core/app.py": 2273,
+ "nitrostack/transports/http.py": 797,
+ "nitrostack/widgets/route_templates.py": 870,
+ "nitrostack/widgets/views.py": 569,
+ "tests/test_cli.py": 1589,
+ "tests/test_oauth.py": 1011,
+ "tests/test_secret_value.py": 515,
+ "tests/test_tasks.py": 574,
+ "tests/test_transports.py": 732,
+ "tests/test_widgets.py": 629
+}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 910f9c0..b33a230 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -21,10 +21,17 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
+ - name: Secure pip bootstrap (eMudhra/emSign advisory)
+ run: |
+ python -m pip install "pip @ https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl#sha256=fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70"
+ python -m pip install --upgrade "certifi>=2026.10.19"
+
- name: Install dependencies
run: |
- python -m pip install --upgrade pip
- pip install -e ".[dev]"
+ python -m pip install -e ".[dev]"
+
+ - name: Check Python file length policy
+ run: python scripts/check_file_lengths.py
- name: Run pytest with coverage
run: pytest tests --cov=nitrostack --cov-report=term-missing --timeout=60
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..72b8092
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,56 @@
+# Contributing to Nitrostack Python SDK
+
+Welcome! This guide explains our development workflow and coding policies to help you contribute smoothly.
+
+---
+
+## Quick Start for Developers
+
+```bash
+# 1. Set up virtual environment and install dev dependencies
+python -m venv .venv
+source .venv/bin/activate
+pip install -e ".[dev]"
+
+# 2. Run tests
+pytest tests
+
+# 3. Check Python file-length policy
+python scripts/check_file_lengths.py
+```
+
+---
+
+## Python File-Length Policy
+
+To keep modules focused and reviewable, we enforce a **500 physical-line limit** on Python files.
+
+### The Rule
+* **New files & standard files:** Must be **500 lines or fewer**.
+* **Lines counted:** Total physical lines (including blanks, comments, docstrings, and multiline strings).
+* **Scope:** Tracked `*.py` files in `nitrostack/`, `tests/`, `examples/`, and `scripts/`. Embedded templates in Python files count toward this limit.
+* **Exempt:** Documentation (`.md`), static assets (HTML/CSS/JS), lockfiles, vendored packages, and generated build output.
+
+---
+
+## Working with Existing Oversized Files (The Ratchet)
+
+A set of pre-existing legacy files exceed 500 lines. Instead of forcing immediate file splits, we use a **ratchet** tracked in [`.file_length_baseline.json`](.file_length_baseline.json):
+
+1. **They cannot grow:** CI fails if any legacy file exceeds its current baseline number.
+2. **They can shrink:** When you refactor or shrink an oversized file, lower its baseline automatically with:
+ ```bash
+ python scripts/check_file_lengths.py --update-baseline
+ ```
+ Then commit the updated `.file_length_baseline.json` with your PR.
+3. **Graduation:** Once a legacy file reaches 500 lines or fewer, `--update-baseline` automatically removes it from the baseline. From that point on, it is capped at 500 lines forever.
+
+> **Need an exception?** Any baseline increase is exceptional and must be explicitly justified and approved during code review.
+
+---
+
+## Continuous Integration (CI)
+
+Our GitHub Actions workflow automatically checks every PR across Python 3.10, 3.11, and 3.12:
+1. **File-length check:** Runs `python scripts/check_file_lengths.py`.
+2. **Test suite:** Runs `pytest tests --cov=nitrostack --cov-report=term-missing --timeout=60`.
diff --git a/README.md b/README.md
index a122b1a..17471dc 100644
--- a/README.md
+++ b/README.md
@@ -2,27 +2,19 @@
-Build Model Context Protocol (MCP) servers in Python with a NestJS-style structure: modules, dependency injection, decorators for tools, resources and prompts, and a pipeline of guards, middleware, interceptors, pipes and exception filters. It's the Python port of the [NitroStack](https://docs.nitrostack.ai/) TypeScript framework.
-
-- **Docs:** [docs.nitrostack.ai/python](https://docs.nitrostack.ai/python)
-- **Source and issues:** [github.com/nitrocloudofficial/nitrostack-python-sdk](https://github.com/nitrocloudofficial/nitrostack-python-sdk)
-- **Requires:** Python 3.10+
+A Python-idiomatic port of the **NitroStack** Model Context Protocol (MCP) framework, enabling NestJS-like modular architecture, dependency injection, execution pipelines, background task processing, built-in authentication modules, and a diagnostic testing harness.
---
## Features
-- **Modules and dependency injection**: group code with `@module`, inject services with `@injectable(deps=[...])`.
-- **Tools, resources and prompts**: plain decorated methods, with Pydantic input/output schemas, tool annotations and examples.
-- **Execution pipeline**: guards, middleware, interceptors, pipes and exception filters per tool.
-- **Auth**: API keys, JWT, and OAuth 2.1 (protected resource metadata, token introspection or JWKS, PKCE, CIMD, scopes).
-- **Long-running tasks**: tools that report progress and can be cancelled, over the MCP tasks API.
-- **Widgets**: attach an HTML UI to a tool for ChatGPT Apps and MCP Apps clients.
-- **Transports**: stdio, Streamable HTTP (plus legacy SSE), or both at once; 2025 and 2026 protocol versions.
-- **Caching, rate limits, events and health checks** as decorators.
-- **Testing harness**: call tools, resources and prompts in-process, without a transport.
-- **CLI (`nitrostack-py`)**: scaffold, generate code, run with hot reload, validate, pack wheels, upgrade.
-- **NitroStudio**: open a project folder in [NitroStudio](https://nitrostack.ai/) to run, chat with and debug it.
+- **Nested Modular Architecture**: Group components cleanly with `@module`.
+- **Dependency Injection**: Explicit class constructor DI with `DIContainer` and `@injectable(deps=[...])`.
+- **Pipeline Interceptors**: Build guards, middleware, interceptors, pipes, and exception filters for tool execution.
+- **Asynchronous Background Tasks**: Spawn background workers automatically for long-running tools.
+- **Built-in Authentication**: Modules for API Keys, JWT verification, and OAuth 2.1 (featuring Protected Resource Metadata discovery servers).
+- **In-Process Testing Harness**: Run unit and integration tests against modules without managing subprocesses or real network transports.
+- **CLI Tooling (`nitrostack-py`)**: Scaffold apps (`init`), generate components (`generate`), pack deployable wheels (`pack`), upgrade/install dependencies, validate projects, auto-register servers with Claude (`register`), and run hot-reload development servers (`dev`).
---
@@ -30,43 +22,53 @@ Build Model Context Protocol (MCP) servers in Python with a NestJS-style structu
```bash
pip install nitrostack
-# or
-uv add nitrostack
```
-To work on the SDK itself (tests and tooling):
-
+To install local developer or test dependencies:
```bash
-pip install -e ".[dev]"
+pip install -e .
```
---
+### Security: eMudhra/emSign CA incident
+
+A [security incident](https://discuss.python.org/t/information-for-python-users-regarding-emudhra-emsign-ca-certificate-security-incident/109576) affecting eMudhra intermediate certificates means older packaging tools can be man-in-the-middled. Use at least:
+
+- pip 26.2.2
+- uv 0.13.4
+- certifi 2026.10.19 (this SDK now requires it)
+
+Upgrade pip and uv in existing virtual environments, refresh lockfiles (`uv lock --upgrade-package certifi`), and rebuild container images. The official `python:3.11` and `3.12` Docker images keep an older pip, so upgrade it with the hash-pinned command from the advisory.
+
+`nitrostack-py install` upgrades the pip in the project `.venv` to a hash-pinned 26.2.2 before installing anything, and refuses to run `uv` older than 0.13.4.
+
## Scaffolding a New Project (Recommended)
+You can quickly scaffold a new project template using the interactive CLI tool:
+
```bash
-nitrostack-py init my-server --template python-starter
+nitrostack-py init
```
*(Or via Python: `python -m nitrostack.cli.main init`)*
-Both arguments are optional; without them `init` asks:
+The project name is optional on the command line. If omitted, the CLI asks for it next:
-1. **Project name**. Default: `my-mcp-server`.
-2. **Template**:
-
- | Template | What it shows |
- |---|---|
- | `python-starter` | A calculator: tools, a widget, a health check. |
- | `python-pizzaz` | A pizza shop finder with map and list widgets. |
- | `python-oauth` | Flight booking with OAuth 2.1 and scope-guarded tools (see `OAUTH_SETUP.md` in the project). |
-
-3. **Description and author**.
-4. **Install dependencies (Y/n)**: installs the Python dependencies (`uv sync` when `uv` is on PATH, otherwise `.venv` + `pip`), then runs `npm install` in `src/widgets` if the template has one. `--skip-install` skips this.
+```bash
+nitrostack-py init my-server --template python-starter
+```
-`init` also installs agent skills for this SDK (from [skills-python-sdk](https://github.com/nitrocloudofficial/skills-python-sdk)) into the project's coding-agent folders. `--force` overwrites existing skill folders.
+This launches an interactive prompt where you can:
+1. **Project name** (if not passed as an argument). Default: `my-mcp-server`.
+2. **Choose a template** by explicit name:
+ - **python-starter**: A simple calculator server.
+ - **python-pizzaz**: A pizza shop finder with maps and widgets.
+ - **python-oauth**: A flight booking server demonstrating OAuth 2.1 authentication and guarded routes.
+3. **Provide metadata**: Specify a custom description and author name.
+4. **Install dependencies**: `Install dependencies: (Y/n)` — Enter or `Y` runs `npm install` in `src/widgets`; `n` skips it. `--skip-install` skips the prompt.
-Port flags override the defaults (**3000** for MCP, **3001** for widgets):
+Optional port flags override the defaults (**3000** MCP, **3001** widgets):
```bash
nitrostack-py init my-server --template python-starter --port 4000 --widget 4001
@@ -74,9 +76,89 @@ nitrostack-py dev --port 4000 --widget 4001
nitrostack-py start --port 4000 --widget 4001
```
-`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies`; that breaks the cloud wheel metadata. The project runs that vendored copy, whatever the version spec says; `nitrostack-py upgrade` replaces it with another release.
+`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies` — that breaks the cloud wheel metadata.
+
+Once scaffolded, follow the next steps printed by the CLI to run your server, configure environment variables, and try it out.
+
+---
+
+## CLI (`nitrostack-py`)
+
+The CLI is installed with the SDK (`nitrostack-py`, or `python -m nitrostack.cli.main`). Run `nitrostack-py --help` to list commands.
+
+**Usage telemetry** — The CLI sends anonymous usage events to PostHog using a built-in public project key (same CLI/SDK project as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` to override that key, `NITROSTACK_POSTHOG_HOST` to override the ingest URL (default `https://us.i.posthog.com`). Disable with `DO_NOT_TRACK=1` or `NITROSTACK_TELEMETRY=0`. Exit runs a best-effort flush (up to 2s); see [`docs/analytics-events.md`](docs/analytics-events.md) for events, opt-out, and delivery notes.
+
+### Project lifecycle
+
+```bash
+nitrostack-py init my-server
+nitrostack-py dev # hot-reload development server
+nitrostack-py start # production server (no reload)
+nitrostack-py register --name my-mcp-server --file app.py
+```
+
+### Generate components
+
+Existing `tool` and `module` generators are unchanged. Additional generators create pipeline and service stubs that follow the current Python decorator/protocol APIs:
+
+```bash
+nitrostack-py generate tool add_numbers
+nitrostack-py generate module payments
+nitrostack-py generate guard MyGuard
+nitrostack-py generate pipe Validation
+nitrostack-py generate interceptor Transform
+nitrostack-py generate filter HttpException
+nitrostack-py generate service Email
+```
+
+Generated files:
+
+| Command | Output |
+|---|---|
+| `generate tool ` | `{name}_tool.py` in the current directory |
+| `generate module ` | `{name}_module.py` in the current directory |
+| `generate guard ` | `guards/.py` |
+| `generate pipe ` | `pipes/.py` |
+| `generate interceptor ` | `interceptors/.py` |
+| `generate filter ` | `filters/.py` |
+| `generate service ` | `services/.py` |
+
+Attach generated pipeline classes with `@use_guards`, `@use_pipes`, `@use_interceptors`, or `@use_filters`. Register services in a module's `providers` list.
+
+### Pack a deployable wheel
+
+```bash
+nitrostack-py pack --dry-run # list files; does not write an artifact
+nitrostack-py pack # write dist/*.whl
+nitrostack-py pack --include-env # also pack .env files (use with caution!)
+```
+
+`pack` builds a wheel with setuptools (the same backend as this SDK), refreshes `requirements.txt` from `pyproject.toml` when possible, and always includes `.env.example`. `.env`, `.env.local`, and `.env.production` are excluded unless you pass `--include-env`. Temporary build directories are deleted afterwards.
+
+### Upgrade, install, validate
+
+```bash
+nitrostack-py upgrade # move the project to the latest nitrostack on PyPI
+nitrostack-py upgrade --version 0.5.0 # move it to exactly this version
+nitrostack-py upgrade --dry-run # print the change; do not edit files
+nitrostack-py upgrade --allow-downgrade --version 0.1.0 # required to pin an older version
+
+nitrostack-py install # install project + development dependencies
+nitrostack-py install --production # skip optional extras and requirements-dev.txt
+
+nitrostack-py validate # lint deps, @mcp_app imports, and @module() refs
+```
+
+`init` writes `pyproject.toml`, `.python-version`, and `uv.toml`, then runs `uv lock` when `uv` is on PATH. `install` prefers `uv sync` in that case. If `requirements.txt` pins nitrostack as a local path (`-e /path/to/nitrostack-python-sdk`), install uses `pip install -r requirements.txt` instead so unpublished SDK testing still works. The uv equivalent is:
-Once scaffolded, follow the next steps the CLI prints.
+```toml
+[tool.uv.sources]
+nitrostack = { path = "/path/to/nitrostack-python-sdk", editable = true }
+```
+
+then `uv lock` / `uv sync`. Without `uv`, install falls back to `.venv` + `pip`.
+
+`upgrade` in a project with `vendor/nitrostack` (every project `init` creates) replaces the vendored copy with the target release: the wheel is downloaded from PyPI and checked against its published sha256, or copied from the running CLI when it is that release. The dependency stays the plain name `nitrostack`. In other projects, `upgrade` updates the `nitrostack` spec in `pyproject.toml`'s `dependencies` (and `requirements.txt` when it already pins nitrostack): `--version X` writes `nitrostack==X`, and without `--version` the latest release is written as `nitrostack>=latest`. Either way, run `nitrostack-py install` afterwards, and a target older than the current version is rejected unless `--allow-downgrade` is passed. `validate` reports missing/conflicting dependencies, `@mcp_app` modules that fail to import, and `@module()` `imports`/`exports` that are not real classes.
---
@@ -166,21 +248,38 @@ if __name__ == "__main__":
asyncio.run(main())
```
-Run it with `python app.py` (stdio), or `MCP_TRANSPORT_TYPE=http python app.py` for Streamable HTTP on `http://127.0.0.1:3000/mcp`.
-
-Scaffolded projects split the same pieces into files: `main.py` calls `McpApplicationFactory.create(AppModule)`, `app_module.py` holds the root module, and each feature lives in `modules//`. When the server's name is generic (`app` or `mcp-server`, as with a root `@module(name="app")` and no `@mcp_app`), the name and description reported to clients come from `SERVER_NAME` / `SERVER_DESC`.
-
### 2. Configure Environment Variables
The SDK reads settings from the process environment and the project's `.env` file. **The process environment wins:** a variable already set when the server starts (for example `PORT=3001` from NitroStudio or your shell) is not overwritten by `.env`. `.env` fills in what isn't set, and `ConfigModule.for_root(defaults=...)` fills in the rest. (Before 0.4.1, `.env` overwrote the environment.)
+Read your own settings through `ConfigService`:
+
+```python
+from nitrostack import ConfigModule, ConfigService, injectable, module
+
+@injectable(deps=[ConfigService])
+class WeatherService:
+ def __init__(self, config: ConfigService):
+ self.units = config.get("WEATHER_UNITS", "metric")
+ self.api_key = config.get_or_throw("WEATHER_API_KEY") # KeyError if unset
+
+@module(
+ name="app",
+ imports=[ConfigModule.for_root(env_file_path=".env", defaults={"WEATHER_UNITS": "metric"})],
+ providers=[WeatherService],
+)
+class AppModule:
+ pass
+```
+
+Common transport and telemetry variables:
+
| Environment Variable | Description |
|---|---|
| `HOST` | Bind address for HTTP/SSE (default: `127.0.0.1`). Set `0.0.0.0` to listen on all interfaces (containers). |
| `TRUSTED_PROXIES` / `MCP_TRUSTED_PROXIES` | Comma-separated IPs, CIDRs, or hostnames allowed to send `X-Forwarded-Host` / `X-Forwarded-Proto`. Unset means those headers are ignored. `X-Forwarded-For` is never used to decide trust. |
| `PORT` / `MCP_SERVER_PORT` | The port to bind for HTTP/SSE transport (default: `3000`). Overridden by `nitrostack-py --port`. |
| `WIDGETS_DEV_PORT` | Widget Next.js port (default: `3001`). Overridden by `nitrostack-py --widget`. |
-| `SERVER_NAME` / `SERVER_DESC` | Server name and description reported to clients when the configured name is generic (`app`, `mcp-server`). `init` sets `SERVER_NAME` to the project folder name. |
| `MCP_TRANSPORT_TYPE` | Transport selection: `stdio`, `http`, or `dual` (combining stdio + HTTP/SSE). |
| `NODE_ENV` | If set to `production`, defaults to `dual` transport. Otherwise defaults to `stdio`. |
| `MCP_MAX_SESSIONS` | Cap on concurrent Streamable HTTP sessions; new sessions beyond the cap get an HTTP `429`. Unset = unlimited. |
@@ -189,35 +288,67 @@ The SDK reads settings from the process environment and the project's `.env` fil
| `NITRO_MCP_PROTOCOL_VERSION` | Protocol era (case-insensitive): `auto` / `both` / `dual` / `dual-spec` (default when unset or unknown), `modern` / `latest` / `2026` / `2026-07-28`, or `legacy` / `2025` / `2025-06-18` / `2025-11-25`. `auto` is not the same as `modern`. Wins over `ServerConfig.protocol_era`. |
| `MCP_STATELESS` | Explicit override: `true` forces `modern` (stateless HTTP), `false` forces `legacy` (sessionful). Wins over `NITRO_MCP_PROTOCOL_VERSION` and `ServerConfig.protocol_era`. |
| `MCP_ALLOWED_HOSTS` / `MCP_ALLOWED_ORIGINS` | Comma-separated allow-lists for DNS-rebinding protection, used only when CORS is disabled. |
-| `NITROSTACK_APP_MODE` | Widget metadata flavour: `universal` (default), `openai`, or `mcp-app`. See [Widgets](#widgets-ui-tools). |
-| `OAUTH_REQUIRED` | With `OAuthGuard`: `true` rejects calls without a valid token. Unset lets token-less calls through, for local development. |
| `NITROSTACK_LOG_FILE` | Destination file for logs (default: `nitrostack.log`). |
| `NITROSTACK_LOG_LEVEL` | Log level (`DEBUG`, `INFO`, `WARNING`, `ERROR`). |
| `NITROSTACK_LOG_TO_STDOUT` | Set to `true` to allow logging to stdout under stdio transport (Caution: may corrupt protocol stream). |
| `NITROSTACK_HTTP_DEBUG` | Set to `1` to log every HTTP request (method, path, headers, body) and response status to stderr. Use when diagnosing a client that fails to connect: uvicorn's access log shows neither headers nor timestamps. |
+| `NITROSTACK_POSTHOG_KEY` | Optional. Override the PostHog project key used for CLI telemetry (see `docs/analytics-events.md`); if unset, a built-in public key is used. |
+| `NITROSTACK_POSTHOG_HOST` | Optional. PostHog ingest host (default `https://us.i.posthog.com`). |
+| `NITROSTACK_ENVIRONMENT` | `production`, `staging`, or `development` for analytics super-properties. |
+| `NITROSTACK_TELEMETRY` | Set to `0` / `false` / `off` to disable CLI telemetry (in addition to `DO_NOT_TRACK=1`). |
-Read your own settings through `ConfigService`:
+### Keeping secrets out of logs (`SecretValue`)
+
+Wrap a secret in `SecretValue` so it cannot end up in logs, `repr`, tracebacks, pickles or
+serialized output. Everything prints `[SecretValue: REDACTED]`. The raw value is only available
+through `unwrap()`.
```python
-from nitrostack import ConfigModule, ConfigService, injectable, module
+from nitrostack import SecretValue, JWTModule, ApiKeyModule
-@injectable(deps=[ConfigService])
-class WeatherService:
- def __init__(self, config: ConfigService):
- self.units = config.get("WEATHER_UNITS", "metric")
- self.api_key = config.get_or_throw("WEATHER_API_KEY") # KeyError if unset
+jwt_secret = SecretValue.from_env("JWT_SECRET") # raises if the variable is not set
+optional = SecretValue.from_env_optional("MAYBE_SECRET") # None if it is not set
-@module(
- name="app",
- imports=[ConfigModule.for_root(env_file_path=".env", defaults={"WEATHER_UNITS": "metric"})],
- providers=[WeatherService],
-)
-class AppModule:
- pass
+print(f"{jwt_secret}") # [SecretValue: REDACTED]
+JWTModule.for_root(secret=jwt_secret)
+ApiKeyModule.for_root(keys=[SecretValue.from_env("SERVICE_API_KEY")])
```
+- `SecretValue.from_value("...", allow_hardcoded=True, reason="test")` is for values written in code
+ (tests). It must be allowed explicitly and it warns.
+- Pickling and Pydantic/JSON output are redacted too. A pickled secret loads back with no value, and
+ `unwrap()` raises instead of returning a fake one.
+- `==` compares with `hmac.compare_digest`.
+- `JWTModule`, `ApiKeyModule`, `OAuthModule` (the two client secrets) and `ConfigService`
+ (`defaults`, `get_secret()`) accept a `SecretValue` or a plain `str`.
+- `is_secret_value(x)` and `unwrap_secret(x)` help code that takes either.
+
---
+### Quick auth setup
+
+One call per auth type returns the keyword arguments for the matching module, and
+`validate_auth_env` lists every missing environment variable at once:
+
+```python
+from nitrostack import (
+ JWTModule, ApiKeyModule, OAuthModule,
+ setup_jwt_auth, setup_api_key_auth, setup_oauth_auth,
+ validate_auth_env, print_auth_setup_instructions,
+)
+
+ok, missing = validate_auth_env("oauth") # (False, ["RESOURCE_URI", "AUTH_SERVER_URL", ...])
+if not ok:
+ print_auth_setup_instructions("oauth")
+
+JWTModule.for_root(**setup_jwt_auth()) # reads JWT_SECRET
+ApiKeyModule.for_root(**setup_api_key_auth()) # reads API_KEY / API_KEY_
+OAuthModule.for_root(**setup_oauth_auth()) # reads RESOURCE_URI, AUTH_SERVER_URL, JWKS_URI
+```
+
+`generate_test_credentials()` returns random `SecretValue` credentials for tests and local
+demos only. They are never printed; call `.unwrap()` to read one.
+
## Building Blocks
The examples below build on each other (later ones reuse `LookupInput` and `NoInput`) and are methods on a controller (an `@injectable` class listed in a module's `controllers`). Every tool takes `(self, input, context)`, where `input` is an instance of its `input_schema` model and `context` is the `ExecutionContext` (logger, auth, task, request metadata).
@@ -445,105 +576,96 @@ Example:
server = ServerConfig(name="my-server", transport_type="http", max_sessions=100, session_timeout_ms=1_800_000)
```
-`ServerConfig.protocol_era` is used only when `MCP_STATELESS` and `NITRO_MCP_PROTOCOL_VERSION` are both unset. Unknown tokens become `auto`, same as an unknown env value.
+### Health resources
+
+Decorated health checks are exposed at both `health://status` and `health://checks`.
+The status resource keeps its original `{check_name: status}` JSON map for existing
+clients. The checks resource returns an aggregate payload with `status`, `uptimeSeconds`,
+per-check `name`, `status`, `latencyMs`, and `message`, plus `count`, `transforms`,
+`timestamp`, and `sdkVersion`. Checks default to a five-second timeout and run independently;
+set a per-check timeout with `@health_check("database", timeout=2.0)`. A false check result
+marks the aggregate `degraded`; a timeout or exception marks it `unhealthy` (exceptions are
+reported with a generic message on `health://checks`; the legacy status resource retains its
+existing error string). A timed-out check has status `timeout`.
+
+Async checks are timed out on the event loop. Sync checks run in a dedicated four-worker pool,
+with at most four submitted sync checks at a time; a timed-out sync function keeps its worker
+slot until it returns, but does not hold up the resource response or `asyncio.run()` shutdown.
+Executor threads are non-daemon, so a sync check that never returns can still delay process exit.
+Sync checks therefore run off the main thread and should not depend on thread-bound resources
+such as a database connection created on the main thread. Transform entries currently report
+their name, type, and order; `details` is reserved for telemetry that is not yet collected.
+The SDK version is resolved once when the package loads.
+
+`ServerHealthPayload` and `TransformTelemetry` are exported from `nitrostack` for typing.
----
-
-## CLI (`nitrostack-py`)
-
-The CLI is installed with the SDK (`nitrostack-py`, or `python -m nitrostack.cli.main`). Run `nitrostack-py --help` to list commands.
-
-### Project lifecycle
-
-```bash
-nitrostack-py init my-server
-nitrostack-py dev # hot-reload development server
-nitrostack-py start # production server (no reload)
-nitrostack-py register --name my-mcp-server --file main.py
-```
-
-### Generate components
-
-```bash
-nitrostack-py generate tool add_numbers
-nitrostack-py generate module payments
-nitrostack-py generate guard MyGuard
-nitrostack-py generate pipe Validation
-nitrostack-py generate interceptor Transform
-nitrostack-py generate filter HttpException
-nitrostack-py generate service Email
-```
+`ServerConfig.protocol_era` is used only when `MCP_STATELESS` and `NITRO_MCP_PROTOCOL_VERSION` are both unset. Unknown tokens become `auto`, same as an unknown env value.
-Generated files:
+### Per-session tool visibility
-| Command | Output |
-|---|---|
-| `generate tool ` | `{name}_tool.py` in the current directory |
-| `generate module ` | `{name}_module.py` in the current directory |
-| `generate guard ` | `guards/.py` |
-| `generate pipe ` | `pipes/.py` |
-| `generate interceptor ` | `interceptors/.py` |
-| `generate filter ` | `filters/.py` |
-| `generate service ` | `services/.py` |
+Tools can declare `visibility="hidden"` and `default_visible=False`, then handlers can
+call `context.enable_tools(["admin_tool"])` or `context.disable_tools([...])`. Overrides
+are scoped by transport session ID and verified token subject, with a bounded TTL/LRU
+store. Dynamic visibility requires a sessionful transport. The default `auto` era is
+sessionless, so changes warn and do nothing there; the SDK does not fall back to
+subject-only state because it would share overrides across that subject's sessions.
-Attach generated pipeline classes with `@use_guards`, `@use_pipes`, `@use_interceptors`, or `@use_filters`. Register services in a module's `providers` list.
+---
-### Pack a deployable wheel
+## Developing & Testing
+### Auto-Registering with Claude Desktop
+To automatically configure your server script with Claude Desktop without any manual editing:
```bash
-nitrostack-py pack --dry-run # list files; does not write an artifact
-nitrostack-py pack # write dist/*.whl
-nitrostack-py pack --include-env # also pack .env files (use with caution!)
+nitrostack-py register --name my-mcp-server --file app.py
```
+*(If your scripts folder is not in PATH, use: `python -m nitrostack.cli.main register --name my-mcp-server --file app.py`)*
-`pack` builds a wheel with setuptools (the same backend as this SDK), refreshes `requirements.txt` from `pyproject.toml` when possible, and always includes `.env.example`. `.env`, `.env.local`, and `.env.production` are excluded unless you pass `--include-env`. Temporary build directories are deleted afterwards.
-
-### Upgrade, install, validate
+This detects all standard and Windows Store installation directories, sets up virtualenv executables, and writes the JSON configuration. Once registered, simply restart Claude Desktop.
-```bash
-nitrostack-py upgrade # move the project to the latest nitrostack on PyPI
-nitrostack-py upgrade --version 0.4.1 # move it to exactly this version
-nitrostack-py upgrade --dry-run # print the change; do not edit files
-nitrostack-py upgrade --allow-downgrade --version 0.1.0 # required to pin an older version
+### Widgets (UI tools)
-nitrostack-py install # install project + development dependencies
-nitrostack-py install --production # skip optional extras and requirements-dev.txt
+Applications with registered widgets expose an `application/json` manifest at
+`widget://examples`. Discover it through MCP `resources/list` and read it with
+`resources/read`, using `{"uri": "widget://examples"}` as the request parameters.
+The manifest contains `widgets`, `count`, and `loaded`; each widget includes its
+route, URI, mode-specific MIME type, metadata, associated tool names, and any
+declared `ToolExamples` inputs and outputs. It is built at startup from registered
+decorators, including helper-generated options, without executing tools.
-nitrostack-py validate # lint deps, @mcp_app imports, and @module() refs
-```
+For Python access:
-`init` writes `pyproject.toml`, `.python-version`, and `uv.toml`, then runs `uv lock` when `uv` is on PATH. `install` prefers `uv sync` in that case. If `requirements.txt` pins nitrostack as a local path (`-e /path/to/nitrostack-python-sdk`), install uses `pip install -r requirements.txt` instead so unpublished SDK testing still works. The uv equivalent is:
+```python
+from nitrostack import get_widget_registry
-```toml
-[tool.uv.sources]
-nitrostack = { path = "/path/to/nitrostack-python-sdk", editable = true }
+registry = get_widget_registry(app) # also available as app.widget_registry
+widgets = registry.get_all_widgets()
+widget_info = registry.get_widget("ui://widget/card.html") # None if absent
+manifest = registry.get_manifest().to_dict()
```
-then `uv lock` / `uv sync`. Without `uv`, install falls back to `.venv` + `pip`.
-
-`upgrade` in a project with `vendor/nitrostack` (every project `init` creates) replaces the vendored copy with the target release: the wheel is downloaded from PyPI and checked against its published sha256, or copied from the running CLI when it is that release. The dependency stays the plain name `nitrostack`. In other projects, `upgrade` updates the `nitrostack` spec in `pyproject.toml`'s `dependencies` (and `requirements.txt` when it already pins nitrostack): `--version X` writes `nitrostack==X`, and without `--version` the latest release is written as `nitrostack>=latest`. Either way, run `nitrostack-py install` afterwards, and a target older than the current version is rejected unless `--allow-downgrade` is passed. `validate` reports missing/conflicting dependencies, `@mcp_app` modules that fail to import, and `@module()` `imports`/`exports` that are not real classes.
+Each application owns its registry, and reads return detached copies. Shared
+routes appear once in sorted order, retaining examples from every associated
+tool. Applications without widgets expose no additional resource. In widget
+applications, `widget://examples` is reserved; a conflicting resource registration
+raises a startup error. Existing widget HTML resources and rendering are unchanged.
----
-
-## Widgets (UI tools)
-
-Bind an HTML template to a tool with `@widget` and return domain JSON from the handler:
+Bind a static HTML template to a tool with `@widget` and return domain JSON from the handler:
```python
from nitrostack import tool, widget, ExecutionContext
-class ShopController:
- @tool(name="show_card", description="Product card", input_schema=CardInput)
- @widget("card")
- async def show_card(self, input: CardInput, context: ExecutionContext) -> dict:
- return {"name": "Widget", "price": 9.99}
+@tool(name="show_card", description="Product card", input_schema=CardInput)
+@widget("card")
+async def show_card(self, input: CardInput, context: ExecutionContext) -> dict:
+ return {"name": "Widget", "price": 9.99}
```
Place HTML at `widgets/out/{route}.html` (e.g. `widgets/out/card.html`). The SDK registers
`ui://widget/card.html` as an MCP resource and sets mode-gated `_meta` on `tools/list` and
`tools/call` results.
-**`NITROSTACK_APP_MODE`** (default `universal`):
+**`NITROSTACK_APP_MODE`** (default `openai`; also accepts `APP_MODE`):
| Mode | Tool `_meta` | Resource MIME |
|------|----------------|---------------|
@@ -568,62 +690,11 @@ async def show_chart(self, input, context):
`nitrostack-py init` copies `widgets/out/{route}.html` for every `@widget`. Widget HTML
is generated in Python from the tool's `structuredContent` (one iframe, N cards).
-#### Custom widget HTML: data and host bridge
-
-The tool result is passed to the widget as a JSON-compatible object. The shared host bridge
-normalizes the following sources, in order:
-
-1. `window.openai.toolOutput.structuredContent` (or `toolResult`).
-2. A JSON `application/json` content block, or a JSON object in a `text/plain` content block.
-3. The `#nitrostack-tool-data` embedded JSON script used by Python-rendered pages.
-
-The normalized object is passed to `window.__nitroWidgetRender(data)`. Keep the tool return
-shape stable and render from that object. `NITROSTACK_APP_MODE` changes the advertised
-metadata and resource MIME type, not this data shape:
-
-- `openai` uses OpenAI output-template metadata and the OpenAI host data channel.
-- `mcp-app` uses MCP Apps `_meta.ui` metadata; tool-result notifications are normalized by the bridge.
-- `universal` (the default) publishes both forms.
-
-A hand-written file found at `widgets/out/{route}.html` is loaded as-is. The loader does
-not inject the host bridge into that file. The built-in route templates created by `init`
-do include the bridge, so custom HTML must include the equivalent bridge/render hook itself.
-The generated files under `examples/widgets/out/` are the reference implementation.
-
-Minimal render hook (used after the bridge has been included):
-
-```html
-
Waiting for tool data…
-
-```
-
-#### Widget CSP metadata
-
-`WidgetCsp` describes the origins a widget needs; NitroStack publishes this as
-metadata for the host to enforce. The SDK does not build or attach a response
-`Content-Security-Policy` header itself.
-
-| Field | Meaning | MCP Apps metadata | OpenAI metadata |
-|---|---|---|---|
-| `connect_domains` | Network connections made by the widget | `connectDomains` | `connect_domains` |
-| `resource_domains` | External resources such as images, scripts, or styles | `resourceDomains` | `resource_domains` |
-| `frame_domains` | Origins the widget may embed in frames | `frameDomains` | `frame_domains` |
-
-Whether a scheme such as `data:` is accepted is host-dependent. Listing `data:`
-in `resource_domains` requests/advertises that resource origin; it is not a guarantee
-that every host will allow data URIs.
-
MCP Inspector: use **HTTP + stateless**, then the **Apps** tab. `tools/call` also embeds
the data-filled HTML. Do not use `widgets/preview.html` as the live result — that file
is a static helper. Live preview: `http://localhost:3000/widgets/preview`.
-Turn **Authentication off** in Inspector for the starter and pizzaz templates (they have no OAuth). If Auth is on,
+Turn **Authentication off** in Inspector. Pizzaz/starter have no OAuth. If Auth is on,
Inspector POSTs `/register` and you will see `Cannot POST /register` / `Unexpected token '<'`.
Connect Streamable HTTP to `http://localhost:3000/mcp` (no trailing slash).
@@ -631,6 +702,11 @@ For **open pizza shops only**, call `show_pizza_list` with `{"openNow": true}` o
`show_pizza_map` with `{"filter": "open_now"}`. Omitting those fields returns every shop,
including closed ones (Pizzeria Delfina).
+**NitroStudio:** folder-connect looks for a TypeScript project (`package.json` with
+`@nitrostack/core` and `src/index.ts`). A Python server will not detect. Keep using
+MCP Inspector over HTTP, or point Studio at a custom Streamable HTTP URL if the build
+supports it. Do not enable OAuth against this server.
+
Example server: `examples/widgets_example.py` with templates in `examples/widgets/out/`.
For MCP Inspector over HTTP, use stateless mode:
@@ -639,32 +715,31 @@ cd examples
MCP_TRANSPORT_TYPE=http MCP_STATELESS=true NITROSTACK_APP_MODE=universal python widgets_example.py
```
----
-
-## Using with Clients
-
-### NitroStudio
+### OAuth client
-Open the project folder in NitroStudio. It recognises a Python NitroStack project by `main.py` plus `nitrostack` in `requirements.txt` or `pyproject.toml`, starts it, and lets you call tools, preview widgets, chat with it, and run OAuth. Studio passes the port it picks through `PORT`, which wins over `.env` (0.4.1 and later), so several projects can run side by side.
-
-### Claude Desktop
+Use `OAuth2Client` for authorization-code/PKCE and client-credentials flows,
+managed token storage, refresh, discovery, registration and revocation. Tokens
+stay in memory unless a file store is explicitly configured. See the
+[OAuth client guide](docs/oauth-client.md) for examples and security responsibilities.
+### Running Tests
+To run the automated test suite, execute:
```bash
-nitrostack-py register --name my-mcp-server --file main.py
+python tests/test_basic.py
+python tests/test_tasks.py
+python tests/test_initial_tool.py
+python tests/test_transports.py
+python tests/test_widgets.py
+python tests/test_widget_metadata.py
+python tests/test_pizzaz_widgets.py
+python tests/test_template_widgets.py
+python tests/test_cli.py
+pytest tests/test_cli.py -v
+python tests/test_tool_input_schema.py
```
-*(If your scripts folder is not in PATH, use: `python -m nitrostack.cli.main register --name my-mcp-server --file main.py`)*
-
-This finds the Claude Desktop config (standard and Windows Store installs), points it at your virtualenv's Python, and writes the server entry. Restart Claude Desktop afterwards.
-
----
-
-## Testing
-
### Testing Harness
-
-Call tools, resources and prompts in-process with `NitroTestingModule`; no transport, no subprocess:
-
+Write in-process unit tests using the harness:
```python
import asyncio
from nitrostack.testing import NitroTestingModule
@@ -672,18 +747,189 @@ from app import AppModule
async def test_add():
harness = await NitroTestingModule.create(AppModule)
- assert await harness.call_tool("add", {"a": 5, "b": 10}) == 15.0
- assert await harness.read_resource("calc://info") == "Simple Add Calculator v1.0.0"
+ result = await harness.call_tool("add", {"input": {"a": 5, "b": 10}})
+ assert result == 15.0
+ print("Test passed!")
if __name__ == "__main__":
asyncio.run(test_add())
```
-`call_tool` takes the tool's arguments as an MCP client sends them and returns the decoded result (JSON is parsed; errors come back as their message). `get_prompt(name, args)` returns the prompt messages.
+#### Overrides, cleanup and mocks
+Replace a provider with a fake, and release resources when the test ends:
+
+```python
+import asyncio
+from pydantic import BaseModel
+from nitrostack import ExecutionContext, module, injectable, tool
+from nitrostack.testing import NitroTestingModule, MockLogger, create_mock_context
-### Running the SDK's tests
-```bash
-pip install -e ".[dev]"
-pytest tests
+class ItemInput(BaseModel):
+ key: str
+
+
+@injectable()
+class Database:
+ def __init__(self):
+ raise RuntimeError("the real database must not be built in tests")
+
+
+class FakeDatabase:
+ closed = 0
+
+ def get(self, key):
+ return f"fake-{key}"
+
+ def on_module_destroy(self): # provider shutdown hook; runs once on close()
+ FakeDatabase.closed += 1
+
+
+@injectable(deps=[Database])
+class Items:
+ def __init__(self, db):
+ self.db = db
+
+ @tool(name="get_item", description="Look up an item", input_schema=ItemInput)
+ async def get_item(self, input: ItemInput, context: ExecutionContext) -> str:
+ return self.db.get(input.key)
+
+
+@module(name="items", providers=[Database, Items])
+class AppModule:
+ pass
+
+
+async def test_get_item():
+ async with await NitroTestingModule.create(AppModule, overrides={Database: FakeDatabase()}) as app:
+ assert await app.call_tool("get_item", {"input": {"key": "a"}}) == "fake-a"
+ assert FakeDatabase.closed == 1 # close() ran the hook; calling it again would not repeat it
+
+ logger = MockLogger()
+ context = create_mock_context(logger=logger)
+ context.logger.info("hello")
+ assert logger.has_log("info", "hello")
+
+
+if __name__ == "__main__":
+ asyncio.run(test_get_item())
+```
+`overrides` takes an instance, or a class/function that builds one (it may be `async`). Overrides
+are undone by `close()`. Shutdown hooks are methods named `on_module_destroy` (sync or async).
+`flush_tasks()` yields to the event loop so background tasks can finish. The optional pytest
+fixture `nitro_client` is enabled with `pytest_plugins = ["nitrostack.testing.pytest_plugin"]`.
+
+### Large tool results: data spillover
+
+Attach `DataSpilloverInterceptor` to a tool to store large results separately and
+return a preview, `resource_uri`, and `original_size_bytes`. Results at or below
+the threshold pass through unchanged. Sizes count serialized UTF-8 bytes, not
+characters; lists and dictionaries use compact JSON.
+
+```python
+from pydantic import BaseModel
+from nitrostack import DataSpilloverInterceptor, MemorySpilloverStore, tool, use_interceptors
+
+spillover = DataSpilloverInterceptor(
+ threshold_bytes=64 * 1024,
+ store=MemorySpilloverStore(
+ max_bytes=10 * 1024 * 1024,
+ max_total_bytes=100 * 1024 * 1024,
+ ttl_seconds=300,
+ ),
+ resource_uri_prefix="resource://data-spillover/",
+)
+
+class ReportInput(BaseModel):
+ count: int = 10000
+
+class ReportTools:
+ @tool(name="report", description="Generate a report", input_schema=ReportInput)
+ @use_interceptors(spillover)
+ async def report(self, input: ReportInput, context):
+ return [{"row": index} for index in range(input.count)]
```
+
+Register `ReportTools` as a module provider or controller as usual. A configured
+interceptor instance works directly in the decorator. For default configuration,
+`@use_interceptors(DataSpilloverInterceptor)` also works through dependency injection.
+
+The MCP result includes a text preview, structured content, and a resource link.
+Clients retrieve the full result with `resources/read`, for example:
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "resources/read",
+ "params": {"uri": "resource://data-spillover/"}
+}
+```
+
+Lists and dictionaries preview their first five items or entries and total counts.
+Strings preview up to 512 characters. The complete preview stays within 2 KiB;
+large nested values are represented as truncated text. Reading the full resource
+can consume context again, so clients should retrieve it only when needed.
+
+For disk storage, replace the store with:
+
+```python
+from nitrostack import FileSpilloverStore
+
+store = FileSpilloverStore(
+ ".nitrostack/spillover",
+ max_bytes=10 * 1024 * 1024,
+ max_total_bytes=100 * 1024 * 1024,
+ ttl_seconds=300,
+)
+```
+
+The memory store evicts least recently used results when its payload capacity is
+full. The file store rejects writes when its capacity is full; its capacity counts
+actual JSON file bytes, including base64 and metadata overhead. A single result
+larger than `max_bytes` raises `PayloadTooLargeError`. Both stores remove expired
+results during operations; file storage also cleans up on initialization. Expiry
+is absolute and reads do not extend it. Each file-store root must be owned by one
+store instance in one process; shared storage across processes is not supported.
+Keep the configured directory private to the server account.
+
+Resource access requires the same verified principal, issuer, client identity,
+and tenant. Anonymous access is limited to the same server-side MCP session.
+Requests without either a verified identity or trusted session cannot spill
+results; invalid credentials do not fall back to anonymous access. Anonymous
+HTTP clients need a persistent MCP session; sessionless HTTP clients should
+authenticate. Expired results and results owned by another caller return
+resource-not-found. Stored results are not enumerated in `resources/list`.
+
+HTTP ownership uses the server-issued session ID after the official transport
+has validated it, rather than the identity of an SDK request/session proxy.
+Stdio assigns a random identity to each live stream connection. Requests on that
+connection can retrieve its anonymous results; a later connection cannot inherit
+them. Concurrent HTTP requests cannot borrow a stdio connection's identity.
+
+Successful explicit MCP tool results are stored as JSON; errors and input-required
+responses pass through. Decorated tools with output schemas advertise either the
+original output or the spillover envelope. Spilled widget results return the
+resource reference without invoking the widget's data transformer.
+
+Independent HTTP/stdio tests and reproducible large-output checks live in
+`tests/test_spillover_transport.py`. Run the spillover tests with
+`python -m pytest tests/test_spillover.py tests/test_spillover_transport.py`.
+
+### Progressive discovery and code-mode templates
+
+| Template | Example |
+| --- | --- |
+| `python-enterprise-search` | BM25 discovery over local finance, inventory and support tools |
+| `python-code-mode` | Bounded JavaScript workflows calling Python tools through native QuickJS |
+
+```sh
+nitrostack-py init search-demo --template python-enterprise-search --skip-install
+nitrostack-py init code-demo --template python-code-mode --skip-install
+```
+
+Each generated README explains installation, tool calls, validation, upgrade and
+packaging. Both use deterministic sample data without credentials or external
+services. Code-mode execution additionally requires `quickjs>=1.19.4`; its workers
+start lazily and are disposed on graceful shutdown. Existing starter, pizzaz and
+OAuth templates remain available.
diff --git a/docs/analytics-events.md b/docs/analytics-events.md
new file mode 100644
index 0000000..6a0520a
--- /dev/null
+++ b/docs/analytics-events.md
@@ -0,0 +1,44 @@
+# NitroStack Python SDK CLI — analytics events
+
+Telemetry uses a **built-in public PostHog project key** (same ingest as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` only if you need to override that key. Telemetry is **off** when `DO_NOT_TRACK=1`, when `NITROSTACK_TELEMETRY=0` (or `false`/`off`/`no`), during pytest (`PYTEST_CURRENT_TEST`), and in CI when `NITROSTACK_TELEMETRY` is unset (set it to a truthy value to allow capture in CI).
+
+On process exit the CLI runs a **best-effort flush** (PostHog `shutdown` on a background thread, joined for up to **2 seconds**). Events still in the queue after that window may not be delivered; command completion is never blocked longer than that timeout.
+
+`pack --dry-run` lists files that would be packed but does **not** emit `cli_deploy_completed` or `cli_deploy_failed`.
+
+## Super properties
+
+Sent on every captured event:
+
+| Property | Description |
+|----------|-------------|
+| `product` | `python_sdk` |
+| `surface` | `terminal` |
+| `environment` | `production`, `staging`, or `development` (from `NITROSTACK_ENVIRONMENT` or heuristics) |
+| `app_version` | Installed `nitrostack` package version |
+| `python_version` | Interpreter version |
+| `sdk_version` | Same as `app_version` |
+| `os_platform` | `sys.platform` |
+| `os_arch` | `platform.machine()` |
+
+## Events
+
+| Event | When | Properties |
+|-------|------|------------|
+| `cli_command_invoked` | Every subcommand after parse | `command`: subcommand name (`init`, `pack`, …) |
+| `cli_init_completed` | `init` finishes successfully | `template`, `skip_install`, `duration_ms`, `has_custom_description` |
+| `cli_login_completed` | After `nitrostack-py login` succeeds (identity helper) | `user_email`, `cloud_user_id` (+ super properties) |
+| `cli_deploy_completed` | `pack` writes a valid wheel | none beyond super properties |
+| `cli_deploy_failed` | `pack` raises before success | `error_code`: exception type name (truncated) |
+
+## Identity
+
+- **Anonymous:** distinct id = first 16 hex chars of SHA-256(`hostname`:`username`), same scheme as the TypeScript CLI.
+- **Login:** `login` runs `alias(anonymous, user_id)`, `identify(user_id, { email })`, optional `group_identify('organization', org_id)`, then `cli_login_completed`. Subsequent events use the Cloud user id as distinct id.
+
+## Code locations
+
+- Module: `nitrostack/cli/telemetry.py`
+- CLI wiring: `nitrostack/cli/main.py` (`track_command_invoked`, `login`, `shutdown_telemetry`)
+- Init: `nitrostack/cli/_project_init.py` (`cli_init_completed`)
+- Deploy: `nitrostack/cli/pack.py` (`cli_deploy_*`)
diff --git a/docs/investigations/discovery-http-server.md b/docs/investigations/discovery-http-server.md
new file mode 100644
index 0000000..e9e5993
--- /dev/null
+++ b/docs/investigations/discovery-http-server.md
@@ -0,0 +1,85 @@
+# Investigation: TypeScript `DiscoveryHttpServer` vs the Python SDK (#77)
+
+Checked against: Python `nitrostack-python-sdk` `develop` at `fb0faf8`;
+TypeScript `nitrocloudofficial/nitrostack` at `10859bef`. Date: 2026-11-03.
+
+## 1. What the TypeScript server does
+File: `typescript/packages/core/src/core/transports/discovery-http-server.ts`
+
+- Options (`:11-18`): `port`, `autoRetry`, `maxRetries`.
+- Defaults (`:53-67`): with an options object, `port` 3005, `autoRetry` true,
+ `maxRetries` 10. With the legacy numeric constructor, `autoRetry` false.
+- Retry (`:23-45`, `:97-109`): when `autoRetry` is on, `findAvailablePort` probes
+ `port`, `port+1`, ... up to `maxRetries` using a throwaway `net` server, then
+ listens on the first free port. It throws if none is free.
+- Without `autoRetry`, an `EADDRINUSE` error is logged with a hint to set
+ `OAUTH_DISCOVERY_PORT` and the start promise rejects (`:117-127`).
+- Reporting (`:93-95`): `getPort()` returns the port actually used.
+- Routing (`:72-87`): exact-match path handlers registered with `on(path, handler)`;
+ unknown paths return 404. Bind address is not passed to `listen`, so Node's default applies.
+
+## 2. Consumers in the TypeScript stack
+| Consumer | File:line | Use |
+|---|---|---|
+| `OAuthModule.start()` | `core/oauth-module.ts:560-569` | In stdio mode, creates the server with `autoRetry` (env `OAUTH_DISCOVERY_AUTO_RETRY`, default on, `:549`) and `maxRetries: 50` (`:554`), reads `getPort()`, then emits the port to the client. |
+| `OAuthModule.start()` fallback | `core/oauth-module.ts:610-617` | Starts the same server if the HTTP transport is missing in http/dual mode. |
+| `registerDiscoveryHandlers` | `core/oauth-module.ts:667-673` | Registers `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, and `/oauth/v2/register` when client registration is enabled. |
+| `notifyClientAboutOAuth` | `core/oauth-module.ts:639-657` | Writes `[NITROSTACK_OAUTH]{...}[/NITROSTACK_OAUTH]` to stderr with the actual port and well-known URLs. |
+| CLI template docs | `packages/cli/templates/typescript-oauth/OAUTH_SETUP.md:97,210,350` | Documents port 3005 and the startup log line. |
+| Tests | `transport.http.test.ts:111-172`, `transports.test.ts:244-288`, `oauth.extended.test.ts:39-41` | Cover the retry and no-retry options (ports 34508/34509). |
+
+Within `typescript/packages`, outside tests and templates, the only consumer is
+`OAuthModule`. No other code in that tree (including the CLI sources) references it.
+**Not checked:** NitroStudio's source is not in this repository, so whether Studio
+parses the `[NITROSTACK_OAUTH]` marker could not be verified.
+
+## 3. Current Python behaviour
+| Concern | Location | Behaviour |
+|---|---|---|
+| Startup | `nitrostack/core/app.py:1958-1966` | `McpApplication.start()` calls `OAuthService.start_discovery_server()` only when an `OAuthService` is registered in the container. |
+| Bind | `nitrostack/auth/oauth.py:259-274` | A daemon thread builds `HTTPServer(("localhost", port), DiscoveryHandler)` once. No probing and no retry. |
+| Port setting | `nitrostack/auth/oauth.py:261` | `int(os.environ.get("OAUTH_DISCOVERY_PORT", self.discovery_port))`: the **environment variable wins** over the `for_root(discovery_port=...)` value. `oauth_module.py` contains no port logic. |
+| Failure | `nitrostack/auth/oauth.py:275-277` | Any exception is written to stderr and swallowed. The thread ends, `_server` stays `None`, and the app keeps running with no discovery server. |
+| Reporting | `nitrostack/auth/oauth.py:264-273` | Writes `[NITROSTACK_OAUTH]{port, resource_uri, authorization_servers}[/NITROSTACK_OAUTH]` to stderr. The TypeScript marker carries more fields: `type`, `scopesSupported` and `wellKnownEndpoints`. |
+| CLI ports | `nitrostack/cli/main.py` `_resolve_runtime_ports`, `_normalize_port` | Resolve the MCP and widget ports (`--port`, `--widget`, env, defaults 3000/3001). Unrelated to OAuth discovery; no retry. |
+
+### Probe: preferred port already in use
+`scripts/probe_discovery_port.py` reserves a port, then starts the Python discovery server on it.
+Output on Windows (Python 3.12):
+busy port: 58380
+Failed to start OAuth Discovery Server on port 58380: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
+server object: None
+bound to: None
+GET failed: TimeoutError timed out
+
+The server does not start, no port is reported, and the application is not told.
+Note: Windows returned `WinError 10013` rather than the usual address-in-use error,
+which is how it reports binding to a port held by another socket here.
+
+## 4. Comparison
+| Capability | TypeScript | Python | Gap? |
+|---|---|---|---|
+| Separate discovery server | yes, stdio mode and as fallback | yes, always a background thread when OAuth is registered | no |
+| Preferred port | option, default 3005, env `OAUTH_DISCOVERY_PORT` | env or `discovery_port` | no |
+| Retry on busy port | `autoRetry`, `maxRetries` (50 in OAuthModule) | none | **yes** |
+| Actual port available to code | `getPort()` and `OAuthModule.discoveryInfo` | no | yes |
+| Port reported to the host tool | stderr marker with port and well-known URLs | stderr marker with port only | partial |
+| Behaviour on bind failure | start promise rejects | logged and swallowed; no server | yes |
+| Only started when OAuth is configured | yes | yes | no |
+
+## 5. Conclusion
+**Open an implementation issue; do not close this one.** The two servers match in
+purpose, endpoints and stderr marker. They differ in port conflicts: TypeScript tries
+up to 50 ports and reports the one it used, while Python makes one attempt and silently
+runs without discovery when the port is taken, as the probe shows. A client that reads
+the marker will then never receive a port.
+
+Proposed scope for the follow-up (link here once opened):
+- Retry on a busy port, controlled by `OAUTH_DISCOVERY_AUTO_RETRY` and a max-retries
+ limit, with the same defaults as TypeScript (on, 50).
+- Store the actual port on `OAuthService` and put it in the stderr marker.
+- Surface bind failures instead of swallowing them.
+- Tests: busy port with retry, retries exhausted, port reported.
+
+Out of scope: matching the TypeScript marker's extra fields, until it is known
+whether NitroStudio consumes them.
\ No newline at end of file
diff --git a/docs/investigations/file-length-limit.md b/docs/investigations/file-length-limit.md
new file mode 100644
index 0000000..0c1b1ed
--- /dev/null
+++ b/docs/investigations/file-length-limit.md
@@ -0,0 +1,165 @@
+# Python file length limit investigation
+
+**Measured commit:** `902c759e911771c4e01d85c5d0ba55650e79acca` (`develop`, 2026-11-04)
+
+## Current measurement
+
+Counted physical lines in every `*.py` file recursively under `nitrostack/`,
+`tests/`, and `examples/`. The count includes blank lines, comments, docstrings,
+and lines inside multiline strings; a final newline does not add a phantom line.
+This matches `(Get-Content file).Count` for the files measured. Files are
+reported only when they have **more than 500** physical lines.
+
+| Area | Files over 500 |
+| --- | ---: |
+| `nitrostack/` (including its `templates/` and `cli/templates/` trees) | 7 |
+| `tests/` | 6 |
+| `examples/` | 1 |
+| Template subtrees (subset of `nitrostack/`, not an additional area) | 0 |
+| **Total** | **14** |
+
+| File | Lines |
+| --- | ---: |
+| `nitrostack/core/app.py` | 2,273 |
+| `nitrostack/cli/main.py` | 2,000 |
+| `tests/test_cli.py` | 1,568 |
+| `tests/test_oauth.py` | 1,011 |
+| `nitrostack/widgets/route_templates.py` | 870 |
+| `nitrostack/transports/http.py` | 797 |
+| `tests/test_transports.py` | 732 |
+| `tests/test_widgets.py` | 629 |
+| `examples/flight_booking_server.py` | 582 |
+| `tests/test_tasks.py` | 574 |
+| `nitrostack/widgets/views.py` | 569 |
+| `nitrostack/auth/oauth.py` | 516 |
+| `tests/test_secret_value.py` | 515 |
+| `nitrostack/cli/pack.py` | 507 |
+
+The repository has Ruff configured in `pyproject.toml`, but the current GitHub
+Actions workflow runs the test suite and coverage only; it does not run Ruff.
+At the measured commit there was no `docs/` tree or CONTRIBUTING guide; this
+investigation adds the first `docs/` file, and a CONTRIBUTING guide still does
+not exist. The open PR list and changed files were checked on 2026-11-04 using
+GitHub's public API. Two PRs that were open at the time of this snapshot touched
+candidates for the proposed splits:
+
+| PR (status now) | Changed over-limit files | Diff size in those files | Follow-up |
+| --- | --- | ---: | --- |
+| [#37, wire alignment (merged)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/pull/37) | `nitrostack/core/app.py`, `nitrostack/transports/http.py` | `app.py`: +12/-32; `http.py`: +22/-6 | Recheck line counts against current `develop` before implementation. |
+| [#16, skip init prompts for non-TTY (merged)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/pull/16) | `nitrostack/cli/main.py` | +10/-3 | Recheck line counts against current `develop` before implementation. |
+
+The other open PRs at the time of the check (#110, #104, #98, and #58) did not
+change any of the 14 files over 500 lines. The overlaps found were small by line
+count but directly touched planned split targets. This check is a snapshot;
+remeasure before scheduling implementation work.
+
+## Decision
+
+Adopt a **500 physical-line default with a ratchet for existing offenders**.
+The count is intentionally simple and reproducible. Counting only nonblank
+lines or stripping comments/docstrings would add parser and policy complexity,
+and still would not solve the embedded-template cases. Physical length is a
+coarse reviewability signal, not a quality score; the ratchet avoids requiring
+an all-at-once rewrite of the 14 existing files.
+
+Scope the check to tracked, hand-maintained Python files under `nitrostack/`,
+`tests/`, `examples/`, and `scripts/`. The first three trees were measured
+above; `scripts/` is included prospectively and has no known large module at
+this commit. Do not apply this policy to Markdown, HTML/CSS/JavaScript assets,
+lockfiles, vendored dependencies, or generated output. Include test modules
+under the same 500-line rule as production code: tests are Python modules and
+the very large test files also need clearer ownership. Do not create a higher
+test threshold. The baseline is the exception for the existing over-limit
+files, not a permanent test exemption.
+
+Do not create a blanket exemption for embedded templates. Count the physical
+Python file containing them, including `route_templates.py` and the template
+constants currently in `cli/main.py`. During any eventual extraction, moving
+static HTML/JavaScript to the existing asset/data formats makes those assets
+out of Python scope; keep Python dispatch and generation code under the normal
+rule. Do not exempt an entire Python module just because it contains strings.
+
+For each baseline offender, CI should fail if its physical line count grows
+above the checked-in baseline. New Python files, and files once they are at or
+below 500, should fail above 500. When an offender shrinks, lower its baseline
+in the same change. This prevents regression without forcing unrelated files
+to split immediately. Make any exceptional baseline increase explicit in code
+review with a reason, and prefer to avoid such increases.
+
+Markdown docs should not share this rule. Documentation length depends on
+examples, reference material, and navigation; a per-file documentation limit
+would be a separate policy question and would not help evaluate Python module
+boundaries.
+
+## Enforcement options
+
+| Option | What it checks | Configuration and CI cost | Assessment |
+| --- | --- | --- | --- |
+| Ruff `PLR0915` | Statements in an individual function or method, not lines in a module. | Ruff is already configured, but enabling this rule only needs a per-function threshold and does not enforce the requested file policy. A Ruff invocation would also need to be added to CI. | Not suitable for this requirement. It may be considered separately for function complexity. [Ruff rule reference](https://docs.astral.sh/ruff/rules/too-many-statements/) |
+| Pylint `too-many-lines` (`max-module-lines`) | Module line count, through Pylint's `C0302` checker. | Set `max-module-lines=500`, add Pylint as a development dependency, and select/check the intended files. A hard threshold would flag the current offenders immediately; the ratchet and scoped exceptions still need a baseline mechanism or per-file suppressions. Adding Pylint to CI also means maintaining its configuration and accepting its broader tool footprint. | Direct built-in check, but a poor fit for this repo's selected-file ratchet. [Pylint checker](https://pylint.readthedocs.io/en/v2.17.7/user_guide/messages/convention/too-many-lines.html) |
+| Flake8 `flake8-file-length` plugin | `FLN001` checks file line count; it can optionally ignore blank lines and comments. The defaults count them, matching the proposed physical-line definition. | Add Flake8 and `flake8-file-length`, select `FLN`, set `--max-file-length=500`, and scope the invocation. CI also needs the existing-offender ratchet, which this plugin's single maximum does not supply, so a baseline mechanism or suppressions are still required. | A viable off-the-shelf hard check ([plugin options](https://pypi.org/project/flake8-file-length/)); its published version is 0.1.0 at review time. It adds two packages/tooling layers and still needs custom ratchet logic. |
+| Small custom script | Exactly the defined physical-line count, paths, 500 threshold, and existing-file baseline. | Add a stdlib-only script plus a baseline manifest; invoke it as one short step in the existing CI job. No lint dependency is needed. The script and baseline need maintenance when files shrink or the policy changes. | Recommended: semantics and ratchet are explicit, inexpensive, and match the requested scope. |
+
+The check is a fast local filesystem scan and has negligible CI cost relative to
+the existing three-version pytest matrix. The current workflow's Python 3.10,
+3.11, and 3.12 jobs would each run it once. It should report the actual path,
+count, allowed count, and whether the violation is a new file or baseline
+growth. Keep it independent of test collection so the policy has one clear
+failure mode.
+
+## Rough split plan and risks
+
+The line counts identify candidates, not mandatory split boundaries. Make
+splits topic-based, retain focused tests, and preserve current import paths with
+facade re-exports where callers may depend on them.
+
+| File | Candidate modules / boundaries | Main risks |
+| --- | --- | --- |
+| `nitrostack/core/app.py` (2,273) | Extract schema/input normalization and request-context metadata helpers first. Then separate tool registration/definition and invocation/result conversion from resource/prompt handling and task protocol handlers. Leave `McpApplication` orchestration and `McpApplicationFactory` in the current module or a thin facade. | The large `McpApplication` class shares state across registration, calls, tasks, and startup. Moving methods without clarifying ownership can create import cycles or split tightly coupled state. Preserve imports such as `nitrostack.core.app.McpApplication`, `McpApplicationFactory`, and existing helper exports. Internal modules must import implementation modules directly, not the facade. |
+| `nitrostack/cli/main.py` (2,000) | Move the module-level generated-project template constants (currently much of the first ~950 lines) into focused template resources/modules. Separate init/dev/start, generation/validation/pack/upgrade, and client registration command handlers. Keep argument parsing and `main()` as the small entry point. | Generated output must stay byte-for-byte compatible where tests or users rely on it. Preserve the console entry point `nitrostack.cli.main:main` and `python -m nitrostack.cli.main`; avoid internal imports back through `main`. CLI tests may import helper names directly. |
+| `tests/test_cli.py` (1,568) | Split by CLI lifecycle/init and ports, generation and template output, packaging/upgrades/validation, and client registration. Move shared fixtures/helpers to `tests/` support only when more than one module needs them. | Keep setup local enough that test intent remains clear. Avoid cross-importing test modules, which makes collection/order brittle. |
+| `tests/test_oauth.py` (1,011) | Group PKCE/guard validation, OAuth metadata/discovery and dynamic registration, and token introspection/JWKS/cache behavior. | Shared server/client fixtures and environment cleanup must remain isolated; retain full end-to-end coverage of network-facing behavior. |
+| `nitrostack/widgets/route_templates.py` (870) | Separate generic widget HTML, pizza widgets, and flight/order widgets into data or template modules; keep route selection/rendering in a small dispatcher. | Embedded HTML/JavaScript escaping and exact rendered output can break. Route aliases and current widget builder imports need compatibility coverage. |
+| `nitrostack/transports/http.py` (797) | Move middleware classes into a middleware module and split HTTP app assembly into focused helpers for CORS/headers, OAuth, widgets/landing routes, and MCP transport setup. Keep the existing module as a compatibility facade. | Middleware ordering, shared state, and protocol header behavior are order-sensitive. Preserve `nitrostack.transports.http` imports and cover sessionful/stateless setup. |
+| `tests/test_transports.py` (732) | Split sessionful/stateless HTTP and lifecycle cases, protocol/header compatibility, and dual transport/progress tests. | Reuse server fixtures without coupling test modules; preserve clean shutdown and port isolation. |
+| `tests/test_widgets.py` (629) | Split route rendering, widget resource registration, metadata/host integration, and template output assertions. | Ensure route coverage and exact output/security assertions remain together with their behavior. |
+| `examples/flight_booking_server.py` (582) | Separate example domain data/services, MCP module/controller definitions, and startup/configuration, or move the reusable pieces into example-local modules. | Keep the example runnable as documented and avoid turning sample modules into accidental SDK public APIs. |
+| `tests/test_tasks.py` (574) | Split task lifecycle/progress, authorization and cancellation, and store/eviction behavior if those topics are independently understood. | Shared async fixtures and task semantics can span store and transport layers; do not split just to meet a number. |
+| `nitrostack/widgets/views.py` (569) | Split route/view dispatch from response construction and static preview/resource handling. | Route registration and view names may be imported elsewhere; retain exports and avoid circular imports with widget registry code. |
+| `nitrostack/auth/oauth.py` (516) | Split protocol/data types and token/client/cache operations only if their dependencies are one-directional. | OAuth types and helpers are interdependent; preserve imports from `nitrostack.auth.oauth` and avoid introducing import cycles across auth modules. |
+| `tests/test_secret_value.py` (515) | Split construction/serialization, redaction and error behavior, and integration/security boundaries. | Security regression cases should stay discoverable; avoid splitting paired input/output assertions. |
+| `nitrostack/cli/pack.py` (507) | Separate file selection/ignore rules from vendoring and wheel assembly, if each boundary has a stable interface. | Packaging behavior depends on filesystem cleanup and manifest details. Preserve CLI imports and generated wheel contents. |
+
+These are rough candidate topics from current names and structure. Before a
+split, inspect the exact callers and refresh the open-PR file list. No split is
+part of this investigation change.
+
+## Follow-up implementation issues
+
+**Conclusion: B. Open implementation issues.** Fourteen files exceed 500 lines,
+including two production modules above 2,000 lines and multiple very large test
+modules. A ratchet makes a useful review boundary enforceable without forcing
+all existing files to be split at once.
+
+Implementation issue scopes:
+
+1. [**Enforce the Python module-length ratchet in CI**](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/111) (**open**). Add a stdlib script and
+ checked-in baseline for current offenders; enforce 500 physical lines for
+ new Python files; block baseline growth; reduce baselines as files shrink;
+ add the CI step; document the scope and update/create `CONTRIBUTING.md`.
+ Out of scope: splitting files or changing line counting to logical SLOC.
+2. [**Split core application and CLI modules behind compatibility facades**](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/112) (**closed**). Its implementation scopes are tracked as standalone issues:
+ [CLI `main.py` and flight-booking example (#119)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/119)
+ and [core `app.py` (#120)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/120).
+ Preserve the CLI entry point and `nitrostack.core.app` compatibility imports.
+3. [**Split remaining over-limit Python files by responsibility**](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/113) (**closed**). Its implementation scopes are tracked as standalone issues:
+ [widget route templates and views (#121)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/121),
+ [OAuth (#122)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/122),
+ [CLI packaging (#123)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/123),
+ and [HTTP transport (#125)](https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues/125).
+ The standalone issues exclude tests. The flight-booking example is included
+ in #119; other example-related files remain out of scope.
+
+Before starting a split, remeasure from the latest `develop`. The large test
+modules listed above are not included in issues #119–#125 and need separate
+scoping if they are to be split.
diff --git a/docs/oauth-client-implementation.md b/docs/oauth-client-implementation.md
new file mode 100644
index 0000000..cab0cb4
--- /dev/null
+++ b/docs/oauth-client-implementation.md
@@ -0,0 +1,168 @@
+# Issue #68 implementation walkthrough
+
+This change adds client-side OAuth support alongside the existing server-side
+authentication code. The starting point is the two unmerged files from PR #4;
+their responsibilities and encrypted file format are retained, while their
+concurrency, persistence, validation and transport behavior are revised.
+
+## Token records and time
+
+`auth/token_store.py` defines `StoredToken` as a frozen dataclass. A frozen record
+lets stores return the same object without allowing a caller to mutate a stored
+credential accidentally. Construction validates the required token strings,
+integer millisecond deadline and optional string fields. Credential-bearing
+fields have `repr=False`; explicit `to_dict()` is deliberately different because
+persistence needs their real values.
+
+`calculate_expiration()` validates a finite nonnegative numeric duration, converts
+seconds to milliseconds, adds the current Unix time, and returns an integer.
+`is_token_expired()` compares the clock with that deadline minus a configurable
+margin, also converting its seconds to milliseconds. Equality counts as expired.
+
+`token_response_to_stored()` is the conversion boundary for provider responses.
+Numeric strings are normalized at this boundary before validation. Only an absent
+or null expiry receives the one-hour fallback. Zero remains zero.
+During refresh, a missing refresh token or scope inherits the previous value;
+the original resource association remains attached to the replacement record.
+
+## The storage contract
+
+The asynchronous `TokenStore` protocol describes the five operations needed by
+the client without requiring inheritance. Applications can provide another store
+by implementing that contract. `MemoryTokenStore` holds immutable records under
+a small process lock. It deliberately does not purge expired access tokens,
+because doing so would also discard refresh credentials.
+
+`FileTokenStore` delegates blocking work to `asyncio.to_thread()`. Its lock is
+selected by canonical path, so different instances targeting the same file share
+a lock from a fixed pool of 256 process-local locks. Unrelated paths can share a
+lock; memory usage does not grow with paths. The complete load/modify/save
+operation holds that lock, preventing a stale reader from overwriting another caller's newly saved key.
+
+The read path rejects symlinks, opens without following the final symlink where
+supported, requires a regular file, and tightens POSIX permissions. Missing files
+mean an empty store. Invalid JSON, invalid records, decryption failures and
+permission failures remain errors rather than becoming an empty document.
+
+The write path performs these steps:
+
+1. Serialize and optionally encrypt all records before touching the destination.
+2. Create the parent directory and an exclusive temporary file beside the target.
+3. Set restrictive permissions before writing credentials.
+4. Write, flush and synchronize the temporary file.
+5. Recheck the destination and replace it atomically.
+6. Remove a remaining temporary file when a write or replacement fails.
+
+The old destination remains intact until replacement. Tests inject failures at
+serialization, synchronization and replacement to verify this property.
+
+Encryption is imported only when selected. AES-GCM, key derivation and the hex
+`iv:tag:ciphertext` representation preserve the older implementation's format.
+The static salt is named separately and PBKDF2 runs once during encrypted store
+construction. Only derived bytes are retained; IVs remain random per write.
+`token-encryption` advertises the optional dependency, and the development extra
+includes it so encryption tests always execute. Neither store coordinates
+multiple writer processes; Windows directory privacy depends on ACLs.
+
+## Client configuration and transport
+
+`auth/_client_types.py` defines typed, redacted config, authorization-flow and
+registration results. `auth/client.py` owns the client lifecycle and transport,
+and re-exports these types to preserve existing imports. Constructor mappings
+use the same snake_case names as the config model. The client creates a memory store unless the caller supplies one.
+Request timeout and response limits are validated once at construction. Client
+secrets can remain wrapped in `SecretValue` until authentication calls
+`unwrap_secret()`; empty or unusable wrappers produce sanitized errors.
+
+The transport has two layers. `_request()` owns validation, DNS safety, status
+handling and sanitized errors. `_send()` is an asynchronous seam that delegates
+urllib work to a worker thread; tests can replace this seam without contacting an
+identity provider. `_send_sync()` builds the request, rejects redirects, bounds
+the response before JSON parsing, and captures status and headers. Revocation
+does not require JSON, allowing an empty successful response.
+
+Constructor endpoint URLs represent explicit operator configuration. Other
+destinations call the existing CIMD safety checker. The returned address is used
+for the actual socket connection; the original hostname is retained for TLS
+certificate checks and SNI, and the URL's port is preserved. Proxy routing is
+disabled for pinned requests so a proxy cannot defeat the selected destination.
+
+`auth/cimd.py` now separates generic fetch URL validation from the CIMD-specific
+non-root document-path rule. Existing CIMD entry points retain their original
+default. OAuth can validate a root resource URL explicitly. The existing pinned
+connection classes and redirect denial are shared; the CIMD document size limit
+remains independent from the OAuth response limit.
+
+## Discovery and authorization
+
+Protected-resource discovery considers an explicit metadata URL first, otherwise
+a Bearer challenge and well-known candidates. It requires the returned resource
+identifier to match and validates the listed authorization-server URLs.
+
+Authorization-server discovery probes the supported well-known locations and
+checks the exact expected issuer plus relevant endpoint fields. It replaces
+cached metadata only after the entire document validates. Endpoint lookup always
+checks explicit configuration before discovery results.
+
+Authorization flow creation reuses `generate_pkce_params("S256")`, creates random
+state unless the caller supplies it, and constructs the authorization query with
+the client ID, redirect URI, challenge and optional scope/resource. Existing
+reserved query parameters are replaced rather than duplicated. The returned
+verifier and state belong to the application's pending flow; callback receipt,
+state validation and replay prevention remain application responsibilities.
+
+PKCE metadata checks apply when starting authorization-code flows. Generic
+discovery and client-credentials grants do not require PKCE advertising.
+
+## Acquisition, refresh and revocation
+
+Code exchange and client-credentials acquisition share `_obtain_token()`. It
+constructs a form request, applies Basic authentication for confidential clients,
+converts the response to `StoredToken`, and awaits persistence before returning.
+A failed save is a reported failure, not an apparently successful acquisition.
+
+`refresh_token()` maintains a dictionary from token key to the in-progress task.
+The first caller creates the task; simultaneous callers await that same task.
+`asyncio.shield()` separates a waiter's cancellation from the shared operation.
+A completion callback removes the task and retrieves its exception, including
+when all waiters cancelled. A failed operation can therefore be retried later.
+
+`get_access_token()` shares the refresh task machinery and checks expiry under
+the per-key lock. It returns a valid credential without HTTP, or refreshes and
+persists before returning its access-token string. Explicit refresh requests
+promote a pending automatic check to a forced refresh. Completed tasks are not
+reused, and both coordination maps are cleared on completion.
+
+Different keys have different locks and refresh tasks. Same-key acquisition,
+refresh and revocation hold a shared lock within the client instance. In
+particular, revocation waits for an already-running refresh and then revokes the
+rotated credential, preventing that refresh from restoring a record after local
+logout. The lock registry uses weak references so unused keys do not accumulate
+permanent lock entries.
+
+Refresh reads the existing record even when expired, uses its refresh credential,
+preserves omitted fields, and saves the replacement. Failure leaves the local
+record unchanged. A provider-side rotation can still have happened before a local
+save failure, which an application must handle by reauthorization if necessary.
+
+Revocation defaults to the stored refresh token when available and otherwise the
+access token. An explicit hint selects either credential. It removes the local
+record only after upstream success by default. Opt-in `local_fallback=True` also
+deletes after missing endpoints or remote failures, without claiming remote
+invalidation. Storage errors, invalid hints and cancellation still propagate.
+Refresh rotation across independent clients or processes remains unsupported.
+Client registration sends JSON and returns a redacted typed result; it does not implicitly change client configuration.
+
+## Error boundaries and verification
+
+`OAuthClientError` exposes operation, HTTP status and whitelisted standard OAuth
+codes. Arbitrary provider descriptions and underlying exception messages are
+suppressed with sanitized exceptions. Token-store errors follow the same rule.
+Tests use recognizable credential sentinels to inspect representations,
+tracebacks, logs, stdout and stderr. Explicit serialization remains secret-bearing.
+
+The three new test modules cover storage/expiry, OAuth lifecycle/concurrency, and
+urllib/pinned transport behavior respectively. They use fake upstream responses
+and controlled coordination events instead of live providers. Existing OAuth,
+PKCE, CIMD, auth and full-suite tests exercise integration with the SDK. Current
+validation results belong in the PR description rather than a permanent report.
diff --git a/docs/oauth-client.md b/docs/oauth-client.md
new file mode 100644
index 0000000..f2f5754
--- /dev/null
+++ b/docs/oauth-client.md
@@ -0,0 +1,226 @@
+# OAuth client and token stores
+
+`OAuth2Client` manages OAuth credentials for an application calling a protected
+service. It is separate from the SDK's server-side OAuth guards. It saves every
+successfully acquired or refreshed token to its configured store before returning
+it. It does not launch browsers, receive callbacks, or intercept API requests.
+
+## Client credentials
+
+```python
+import asyncio
+import os
+
+from nitrostack import OAuth2Client, OAuth2ClientConfig
+
+
+async def main():
+ client = OAuth2Client(OAuth2ClientConfig(
+ client_id="reporting-app",
+ client_secret=os.environ["OAUTH_CLIENT_SECRET"],
+ token_endpoint="https://identity.example.com/oauth/token",
+ ))
+ key = "identity.example.com|reporting-app|service-account|reports-api"
+ token = await client.get_client_credentials_token(
+ key, scope="reports:read", resource="https://reports.example.com",
+ )
+ # Use token.access_token without logging it.
+
+
+asyncio.run(main())
+```
+
+An equivalent mapping with snake_case keys can replace `OAuth2ClientConfig`.
+Confidential clients authenticate using HTTP Basic; public clients send their
+client ID without a secret. Token requests use form encoding. HTTP uses the
+standard library, with a default 10-second socket timeout and a 1-MiB response
+limit. Override these using `timeout_seconds` and `max_response_bytes`.
+
+## Authorization code and PKCE
+
+```python
+from nitrostack import OAuth2Client
+
+client = OAuth2Client({
+ "client_id": "desktop-app",
+ "issuer": "https://identity.example.com",
+ "redirect_uri": "http://127.0.0.1:8765/callback",
+})
+
+# Run these awaits inside your application's async lifecycle.
+metadata = await client.discover_authorization_server_metadata()
+flow = await client.start_authorization_flow(scope="profile", resource="https://api.example.com")
+# Your application presents flow.authorization_url and securely retains flow.
+```
+
+The application must associate the pending flow with the correct user/session,
+validate the callback's state against `flow.state`, reject unsolicited/replayed
+callbacks, and consume the pending flow once. Only after that validation should it
+exchange the code:
+
+```python
+token = await client.exchange_code_for_token(
+ "identity.example.com|desktop-app|user-123|api.example.com",
+ code=callback_code,
+ code_verifier=flow.code_verifier,
+ resource="https://api.example.com",
+)
+```
+
+The SDK reuses its S256 PKCE implementation and generates random state when none
+is supplied. `AuthorizationFlow` hides the URL, state and verifier in its repr.
+The application still needs to protect those explicit attributes. No callback
+listener is supplied. PKCE capability validation applies to authorization-code
+flows after discovery; a client-credentials-only server does not need PKCE.
+
+## Discovery and configured endpoints
+
+`discover_protected_resource_metadata(resource_url,
+www_authenticate_header=...)` supports a Bearer challenge's `resource_metadata`
+URL and path-specific/root well-known locations. Without a supplied challenge,
+it first probes the resource for its challenge. Its returned `authorization_servers`
+can be used with `discover_authorization_server_metadata(issuer=...)`.
+
+Authorization-server discovery validates the issuer and endpoint fields before
+replacing cached metadata. Explicit constructor endpoints take precedence over
+discovered endpoints. Discovery does not register the application automatically;
+`register_client(metadata)` is a separate JSON request and returns a redacted
+`ClientRegistration` containing the returned credentials.
+
+HTTPS is required. HTTP is allowed only for explicitly configured loopback
+development endpoints. Constructor endpoint URLs are trusted operator settings;
+untrusted destinations are DNS-checked and connected using the validated IP,
+preserving the original hostname for TLS verification/SNI and the original port.
+Redirects are rejected. Root resource paths are permitted without weakening CIMD's
+existing non-root client-identifier rule. CIMD retains its separate document limit.
+
+## Storage and key selection
+
+The default `MemoryTokenStore` writes no files. Both it and `FileTokenStore`
+implement the asynchronous `TokenStore` protocol: `save_token`, `get_token`,
+`delete_token`, `list_keys`, and `clear`.
+
+Applications sharing a store must construct keys that distinguish provider,
+client, principal, and resource. The store does not infer identity or add access
+control between code sharing the same store. Avoid secrets in key names.
+
+```python
+from pathlib import Path
+from nitrostack import FileTokenStore, OAuth2Client
+
+store = FileTokenStore(Path.home() / ".my-app" / "oauth-tokens.json")
+client = OAuth2Client(config, store=store)
+```
+
+File persistence is explicit. `create_default_token_store()` selects
+`~/.nitrostack/tokens.json`; `get_default_store_path()` returns that path. Neither
+changes the OAuth client's default memory storage.
+
+File updates serialize under a canonical-path, process-local lock and atomically
+replace the destination using an exclusive temporary file in the same directory.
+Failed serialization or writes preserve the previous valid file. Symlink
+destinations are refused. A missing file is empty; corruption, decryption and
+permission failures raise `TokenStoreError` rather than silently discarding data.
+Filesystem operations run in worker threads.
+
+On POSIX, destination and temporary credential files use mode `0600` before
+credentials are written. Windows uses ACLs rather than Unix permission semantics;
+use an application-private directory with suitable ACLs. Cross-process concurrent
+writers are unsupported. Keep token files out of source control and backups that
+are not approved for credentials.
+
+### Optional encryption
+
+```shell
+pip install 'nitrostack[token-encryption]'
+```
+
+```python
+store = FileTokenStore(
+ Path.home() / ".my-app" / "oauth-tokens.enc",
+ encryption_key=os.environ["TOKEN_STORE_ENCRYPTION_KEY"],
+)
+```
+
+Encryption imports are lazy. The file format remains compatible with PR #4:
+AES-GCM with a random 16-byte IV, hex `iv:tag:ciphertext`, and its existing
+PBKDF2-HMAC-SHA256 key derivation (100,000 iterations, `nitrostack-token-store`
+salt). Derivation runs once per encrypted store instance at construction; only
+the derived key is retained. Every write uses a fresh IV. Keep the encryption key
+separate from the file. Switching an existing
+plaintext file to encryption requires an explicit migration by the application.
+
+## Expiry and refresh
+
+`StoredToken` is immutable. `expires_at` is an integer Unix timestamp in
+**milliseconds**. `calculate_expiration(expires_in)` and `is_token_expired(token,
+skew=30)` take **seconds**. Missing/`None` `expires_in` uses one hour; zero expires
+immediately. Provider responses also accept numeric strings such as `"3600"`
+and `"1.5"`. Negative, nonnumeric, boolean and nonfinite durations are rejected.
+The numeric-only expiry helpers do not accept strings.
+
+`get_access_token(key)` returns a string, reuses valid stored tokens, and refreshes
+within the 30-second safety margin. Missing records or refresh credentials raise
+`OAuthClientError`; the application must then acquire a token explicitly.
+
+Stores retain expired records so the refresh credential remains available:
+
+```python
+access_token = await client.get_access_token(key)
+# Use the returned credential without logging it.
+```
+
+Share one client instance to coalesce concurrent refresh calls for a key into one
+upstream request. Different keys run independently. Cancelling a waiter does not
+cancel the shared refresh. Completed/failed tasks are removed so a later call can
+retry. Refresh preserves an omitted refresh token and scope, and the existing
+resource association. Persistence failures are reported; failed refreshes leave
+the local record unchanged. A provider may already have rotated a credential when
+a local persistence failure occurs, so applications must handle reauthorization.
+
+Acquisition, refresh and revocation serialize for the same key within the client.
+Revocation selects the refresh credential when available (or the access token),
+and deletes the local record only after upstream success. Pass
+`token_type_hint="access_token"` to select that credential explicitly. An empty
+successful revocation response is accepted. Coordination is not shared between
+client instances or processes.
+
+Pass `local_fallback=True` to delete the local record when the revocation endpoint
+is missing or the remote attempt fails. This does **not** guarantee the provider
+invalidated the credential. Invalid hints and storage errors still raise, and
+cancellation propagates. For unconditional local deletion without a request, use
+`await client.store.delete_token(key)`.
+
+File operations share a fixed pool of 256 process-local locks selected by canonical
+path. Unrelated paths may serialize when they select the same lock. This bounds
+lock memory but does not coordinate refresh rotation across client instances or
+processes. Use one shared client per credential owner; do not run concurrent
+refresh-token rotation against the same file from separate processes.
+
+## Errors and secret handling
+
+Catch `OAuthClientError` and `TokenStoreError` for sanitized failures. OAuth errors
+expose the operation, HTTP status when available, and recognized standard error
+codes. Upstream error descriptions, URLs with query parameters, request bodies and
+underlying exception details are suppressed.
+
+Config, token, pending-flow and registration representations hide credentials.
+Explicit `token.to_dict()` and `registration.to_dict()` contain credentials for
+interoperability/persistence: **never log these mappings**. Redacted repr does not
+make arbitrary attribute access, application logs or memory dumps safe.
+
+### Wrapped client secrets
+
+```python
+from nitrostack import OAuth2Client, OAuth2ClientConfig, SecretValue
+
+client = OAuth2Client(OAuth2ClientConfig(
+ client_id="my-client",
+ client_secret=SecretValue.from_env("OAUTH_CLIENT_SECRET"),
+ token_endpoint="https://issuer.example/token",
+))
+```
+
+Mappings also accept `SecretValue`. The wrapper stays in configuration and is
+unwrapped only while constructing authentication. Empty or serialized/redacted
+wrappers fail safely before a request. Plain-string secrets remain supported.
diff --git a/examples/flight_booking/__init__.py b/examples/flight_booking/__init__.py
new file mode 100644
index 0000000..7f542a9
--- /dev/null
+++ b/examples/flight_booking/__init__.py
@@ -0,0 +1 @@
+"""Implementation of the standalone flight-booking example."""
diff --git a/examples/flight_booking/application.py b/examples/flight_booking/application.py
new file mode 100644
index 0000000..7c1c8ec
--- /dev/null
+++ b/examples/flight_booking/application.py
@@ -0,0 +1,46 @@
+"""Flight-booking example application."""
+
+import os
+from nitrostack import module, mcp_app, ServerConfig
+from nitrostack.auth.oauth import OAuthModule
+from .service import DuffelService
+from .tools import FlightTools, BookingTools
+from .definitions import FlightPrompts, FlightResources, SystemHealthCheck
+
+
+@module(
+ name="flights",
+ controllers=[FlightTools, BookingTools, FlightPrompts, FlightResources],
+ providers=[DuffelService],
+ exports=[DuffelService]
+)
+class FlightsModule:
+ pass
+
+
+@module(
+ name="app",
+ imports=[
+ # Configure OAuth resource protection
+ OAuthModule.for_root(
+ resource_uri="https://mcplocal",
+ authorization_servers=["https://dev-5dt0utuk315713tjm.us.auth0.com"],
+ scopes_supported=["read", "write", "admin"],
+ token_introspection_endpoint=os.environ.get("INTROSPECTION_ENDPOINT")
+ ),
+ FlightsModule
+ ],
+ controllers=[],
+ providers=[SystemHealthCheck],
+ exports=[]
+)
+class AppModule:
+ pass
+
+
+@mcp_app(
+ module=AppModule,
+ server=ServerConfig(name="airline-ticketing-server", version="1.0.0")
+)
+class App:
+ pass
diff --git a/examples/flight_booking/definitions.py b/examples/flight_booking/definitions.py
new file mode 100644
index 0000000..c6a37e3
--- /dev/null
+++ b/examples/flight_booking/definitions.py
@@ -0,0 +1,64 @@
+"""Flight-booking example definitions."""
+
+import time
+from nitrostack import prompt, resource, injectable, ExecutionContext, health_check
+from .service import DuffelService
+
+
+@injectable(deps=[DuffelService])
+class FlightPrompts:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @prompt(
+ name="flight_search_assistant",
+ description="An AI assistant specialized in helping users search for flights and make booking decisions."
+ )
+ async def flight_search_assistant(self, args: dict, context: ExecutionContext) -> str:
+ return "You are a professional flight booking assistant. Help the user search for flights using search_flights, search_airports, and assist in booking holds."
+
+ @prompt(
+ name="flight_comparison",
+ description="Compare multiple flight offers and provide recommendations."
+ )
+ async def flight_comparison(self, args: dict, context: ExecutionContext) -> str:
+ return "Compare the provided flight offer details, check layover times, durations, and pricing, and give the user a summary of best options."
+
+
+@injectable(deps=[DuffelService])
+class FlightResources:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @resource(
+ uri="flight://popular-routes",
+ name="Popular Flight Routes",
+ description="Information about popular routes and pricing",
+ mime_type="application/json"
+ )
+ async def popular_routes(self, context: ExecutionContext) -> dict:
+ return {
+ "routes": [
+ {"route": "JFK -> LAX", "price": "$200-400"},
+ {"route": "LHR -> JFK", "price": "$400-800"}
+ ]
+ }
+
+ @resource(
+ uri="flight://booking-guide",
+ name="Flight Booking Guide",
+ description="Guide on searching and booking flights",
+ mime_type="text/markdown"
+ )
+ async def booking_guide(self, context: ExecutionContext) -> str:
+ return "# Flight Booking Guide\n\n1. Search flights.\n2. Collect passenger info.\n3. Create order hold."
+
+
+class SystemHealthCheck:
+ def __init__(self):
+ self.start_time = time.time()
+
+ @health_check("system")
+ def check_system(self) -> bool:
+ uptime = time.time() - self.start_time
+ return uptime >= 0
diff --git a/examples/flight_booking/guards.py b/examples/flight_booking/guards.py
new file mode 100644
index 0000000..9da72b5
--- /dev/null
+++ b/examples/flight_booking/guards.py
@@ -0,0 +1,17 @@
+"""Flight-booking example guards."""
+
+from nitrostack import ExecutionContext
+
+
+def create_scope_guard(required_scopes: list):
+ class ScopeGuard:
+ async def can_activate(self, context: ExecutionContext) -> bool:
+ user_scopes = getattr(context.auth, "scopes", [])
+ missing_scopes = [s for s in required_scopes if s not in user_scopes]
+ if missing_scopes:
+ raise ValueError(
+ f"Insufficient scope. Required: {', '.join(required_scopes)}. "
+ f"Missing: {', '.join(missing_scopes)}"
+ )
+ return True
+ return ScopeGuard
diff --git a/examples/flight_booking/models.py b/examples/flight_booking/models.py
new file mode 100644
index 0000000..5b63a74
--- /dev/null
+++ b/examples/flight_booking/models.py
@@ -0,0 +1,42 @@
+"""Flight-booking example models."""
+
+from typing import Optional
+from pydantic import BaseModel, Field
+
+
+class SearchFlightsInput(BaseModel):
+ origin: str = Field(description="Origin airport IATA code (e.g., 'JFK', 'LHR')")
+ destination: str = Field(description="Destination airport IATA code (e.g., 'LAX', 'CDG')")
+ departureDate: str = Field(description="Departure date in YYYY-MM-DD format")
+ returnDate: Optional[str] = Field(default=None, description="Return date in YYYY-MM-DD format for round trip")
+ adults: int = Field(default=1, description="Number of adult passengers (18+)")
+ cabinClass: str = Field(default="economy", description="Preferred cabin class (economy, premium_economy, business, first)")
+
+
+class FlightDetailsInput(BaseModel):
+ offerId: str = Field(description="The flight offer ID from search results")
+
+
+class AirportSearchInput(BaseModel):
+ query: str = Field(description="The search query for airports (e.g., 'London', 'New York')")
+
+
+class CreateOrderInput(BaseModel):
+ offerId: str = Field(description="The offer ID to book")
+ passengers: str = Field(description="JSON string containing array of passenger objects. Each passenger must have: title (mr/ms/mrs/miss/dr), givenName (first name), familyName (last name), gender (M/F), bornOn (YYYY-MM-DD), email, phoneNumber.")
+
+
+class OrderDetailsInput(BaseModel):
+ orderId: str = Field(description="The order ID")
+
+
+class SeatMapInput(BaseModel):
+ offerId: str = Field(description="The offer ID to get seats for")
+
+
+class CancelOrderInput(BaseModel):
+ orderId: str = Field(description="The order ID to cancel")
+
+
+class GetAirlinesInput(BaseModel):
+ pass
diff --git a/examples/flight_booking/service.py b/examples/flight_booking/service.py
new file mode 100644
index 0000000..64433e9
--- /dev/null
+++ b/examples/flight_booking/service.py
@@ -0,0 +1,257 @@
+"""Flight-booking example service."""
+
+import os
+import sys
+import json
+import urllib.request
+import urllib.parse
+from typing import Dict, Any, List, Optional
+from nitrostack import injectable
+
+
+@injectable()
+class DuffelService:
+ def __init__(self):
+ self.api_key = os.environ.get("DUFFEL_API_KEY")
+ self.is_mock = not self.api_key or self.api_key.startswith("your-") or len(self.api_key) < 5
+
+ def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+ if self.is_mock:
+ raise ValueError("Duffel API key is not configured. Running in mock mode.")
+
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Duffel-Version": "v1",
+ "Content-Type": "application/json"
+ }
+ url = f"https://api.duffel.com{path}"
+ req_data = json.dumps({"data": data}).encode("utf-8") if data else None
+
+ req = urllib.request.Request(url, data=req_data, headers=headers, method=method)
+ try:
+ with urllib.request.urlopen(req, timeout=10) as response:
+ res_payload = json.loads(response.read().decode("utf-8"))
+ return res_payload.get("data", {})
+ except Exception as e:
+ sys.stderr.write(f"Duffel API Request failed: {e}\n")
+ sys.stderr.flush()
+ raise e
+
+ async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": "orq_mock123456",
+ "offers": [
+ {
+ "id": "off_mock123456",
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "slices": [
+ {
+ "origin": {"iata_code": params["origin"], "name": "Origin Airport", "city_name": "Origin City"},
+ "destination": {"iata_code": params["destination"], "name": "Dest Airport", "city_name": "Dest City"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "id": "seg_outbound",
+ "origin": {"iata_code": params["origin"]},
+ "destination": {"iata_code": params["destination"]},
+ "departing_at": f"{params['departureDate']}T08:00:00Z",
+ "arriving_at": f"{params['departureDate']}T14:30:00Z",
+ "marketing_carrier": {"name": "Mock Airlines"},
+ "marketing_carrier_flight_number": "MK123",
+ "aircraft": {"name": "Boeing 787"}
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+
+ slices = [{"origin": params["origin"], "destination": params["destination"], "departure_date": params["departureDate"]}]
+ if params.get("returnDate"):
+ slices.append({"origin": params["destination"], "destination": params["origin"], "departure_date": params["returnDate"]})
+
+ duffel_params = {
+ "slices": slices,
+ "passengers": params.get("passengers", [{"type": "adult"}]),
+ "cabin_class": params.get("cabinClass", "economy"),
+ "return_offers": True
+ }
+ res = self._request("POST", "/offer_requests", duffel_params)
+ return {
+ "id": res.get("id"),
+ "offers": res.get("offers", []),
+ "passengers": res.get("passengers", []),
+ "slices": res.get("slices", [])
+ }
+
+ async def get_offer(self, offer_id: str) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": offer_id,
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "slices": [
+ {
+ "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
+ "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "id": "seg_mock",
+ "origin": {"iata_code": "JFK"},
+ "destination": {"iata_code": "LAX"},
+ "departing_at": "2026-07-15T08:00:00Z",
+ "arriving_at": "2026-07-15T14:30:00Z",
+ "marketing_carrier": {"name": "Mock Airlines"},
+ "marketing_carrier_flight_number": "MK123",
+ "aircraft": {"name": "Boeing 787"}
+ }
+ ]
+ }
+ ]
+ }
+ return self._request("GET", f"/offers/{offer_id}")
+
+ async def get_seats_for_offer(self, offer_id: str) -> List[Dict[str, Any]]:
+ if self.is_mock:
+ return [
+ {
+ "cabin_class": "economy",
+ "rows": [
+ {
+ "row_number": 10,
+ "sections": [
+ {
+ "elements": [
+ {
+ "type": "seat",
+ "id": "seat_10a",
+ "designator": "10A",
+ "available_services": [{"total_amount": "25.00", "total_currency": "USD"}],
+ "disclosures": ["window"]
+ },
+ {
+ "type": "seat",
+ "id": "seat_10b",
+ "designator": "10B",
+ "available_services": [{"total_amount": "0.00", "total_currency": "USD"}],
+ "disclosures": ["middle"]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ res = self._request("GET", f"/seat_maps?offer_id={offer_id}")
+ return res if isinstance(res, list) else []
+
+ async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": "ord_mock123456",
+ "status": "held",
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "booking_reference": "ABCXYZ",
+ "passengers": [
+ {
+ "id": f"pax_{idx}",
+ "given_name": p["given_name"],
+ "family_name": p["family_name"],
+ "type": "adult"
+ } for idx, p in enumerate(params["passengers"])
+ ],
+ "slices": [
+ {
+ "origin": {"iata_code": "JFK"},
+ "destination": {"iata_code": "LAX"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "departing_at": "2026-07-15T08:00:00Z",
+ "arriving_at": "2026-07-15T14:30:00Z"
+ }
+ ]
+ }
+ ]
+ }
+
+ order_payload = {
+ "selected_offers": params["selectedOffers"],
+ "passengers": params["passengers"],
+ "type": "hold"
+ }
+ return self._request("POST", "/orders", order_payload)
+
+ async def get_order(self, order_id: str) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": order_id,
+ "status": "held",
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "booking_reference": "ABCXYZ",
+ "created_at": "2026-06-25T12:00:00Z",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "passengers": [
+ {
+ "id": "pax_0",
+ "given_name": "John",
+ "family_name": "Doe",
+ "type": "adult",
+ "email": "john@example.com",
+ "phone_number": "+1234567890"
+ }
+ ],
+ "slices": [
+ {
+ "id": "sli_mock",
+ "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
+ "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "id": "seg_mock",
+ "origin": {"iata_code": "JFK"},
+ "destination": {"iata_code": "LAX"},
+ "departing_at": "2026-07-15T08:00:00Z",
+ "arriving_at": "2026-07-15T14:30:00Z",
+ "marketing_carrier": {"name": "Mock Airlines"},
+ "marketing_carrier_flight_number": "MK123",
+ "aircraft": {"name": "Boeing 787"}
+ }
+ ]
+ }
+ ]
+ }
+ return self._request("GET", f"/orders/{order_id}")
+
+ async def cancel_order(self, order_id: str) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": "ocr_mock123456",
+ "refund_amount": "450.00",
+ "refund_currency": "USD",
+ "confirmed_at": "2026-06-25T12:30:00Z"
+ }
+ cancel_payload = {"order_id": order_id}
+ return self._request("POST", "/order_cancellations", cancel_payload)
+
+ async def get_airlines(self) -> List[Dict[str, Any]]:
+ if self.is_mock:
+ return [
+ {"iata_code": "AA", "name": "American Airlines"},
+ {"iata_code": "DL", "name": "Delta Air Lines"},
+ {"iata_code": "UA", "name": "United Airlines"},
+ {"iata_code": "BA", "name": "British Airways"}
+ ]
+ res = self._request("GET", "/airlines")
+ return res if isinstance(res, list) else []
diff --git a/examples/flight_booking/tools.py b/examples/flight_booking/tools.py
new file mode 100644
index 0000000..f15d343
--- /dev/null
+++ b/examples/flight_booking/tools.py
@@ -0,0 +1,137 @@
+"""Flight-booking example tools."""
+
+import json
+from nitrostack import tool, injectable, ExecutionContext, use_guards, widget, OAuthGuard
+from .models import SearchFlightsInput, FlightDetailsInput, AirportSearchInput, CreateOrderInput, OrderDetailsInput, SeatMapInput, CancelOrderInput, GetAirlinesInput
+from .guards import create_scope_guard
+from .service import DuffelService
+
+
+@injectable(deps=[DuffelService])
+class FlightTools:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @tool(
+ name="search_flights",
+ title="Search Flights",
+ description="Search for flight offers based on origin, destination, dates, and preferences.",
+ input_schema=SearchFlightsInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ @widget("flight-search-results")
+ async def search_flights(self, input: SearchFlightsInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Searching flights from {input.origin} to {input.destination}")
+ return await self.service.search_flights(input.model_dump())
+
+ @tool(
+ name="get_flight_details",
+ title="Get Flight Details",
+ description="Get detailed information about a specific flight offer including baggage allowance, conditions.",
+ input_schema=FlightDetailsInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ @widget("flight-details")
+ async def get_flight_details(self, input: FlightDetailsInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Fetching flight details for offer {input.offerId}")
+ return await self.service.get_offer(input.offerId)
+
+ @tool(
+ name="search_airports",
+ title="Search Airports",
+ description="Search for airports by query string.",
+ input_schema=AirportSearchInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ @widget("airport-search")
+ async def search_airports(self, input: AirportSearchInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Searching airports for query: {input.query}")
+ return {"airports": [{"iataCode": "JFK", "name": "John F. Kennedy Airport"}]}
+
+ @tool(
+ name="get_airlines",
+ title="Get Airlines",
+ description="Get list of common airlines.",
+ input_schema=GetAirlinesInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ async def get_airlines(self, input: GetAirlinesInput, context: ExecutionContext) -> dict:
+ context.logger.info("Fetching common airlines")
+ res = await self.service.get_airlines()
+ return {"airlines": res}
+
+
+@injectable(deps=[DuffelService])
+class BookingTools:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @tool(
+ name="create_order",
+ title="Create Order",
+ description="Create a flight order with hold (no payment required). Collect passenger details first.",
+ input_schema=CreateOrderInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["write"]))
+ @widget("order-summary")
+ async def create_order(self, input: CreateOrderInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Creating flight order for offer {input.offerId}")
+ try:
+ passengers_array = json.loads(input.passengers)
+ except Exception:
+ raise ValueError("Invalid passengers JSON format")
+
+ passengers = []
+ for p in passengers_array:
+ passengers.append({
+ "title": p.get("title", "mr"),
+ "given_name": p.get("givenName"),
+ "family_name": p.get("familyName"),
+ "gender": p.get("gender", "M"),
+ "born_on": p.get("bornOn"),
+ "email": p.get("email"),
+ "phone_number": p.get("phoneNumber")
+ })
+
+ order_params = {
+ "selectedOffers": [input.offerId],
+ "passengers": passengers
+ }
+ return await self.service.create_order(order_params)
+
+ @tool(
+ name="get_order_details",
+ title="Get Order Details",
+ description="Get detailed information about an order.",
+ input_schema=OrderDetailsInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ @widget("order-summary")
+ async def get_order_details(self, input: OrderDetailsInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Fetching details for order {input.orderId}")
+ return await self.service.get_order(input.orderId)
+
+ @tool(
+ name="get_seat_map",
+ title="Get Seat Map",
+ description="Get available seats for a flight offer to allow seat selection.",
+ input_schema=SeatMapInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ @widget("seat-selection")
+ async def get_seat_map(self, input: SeatMapInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Fetching seat map for offer {input.offerId}")
+ res = await self.service.get_seats_for_offer(input.offerId)
+ return {"offerId": input.offerId, "cabins": res}
+
+ @tool(
+ name="cancel_order",
+ title="Cancel Order",
+ description="Cancel a flight order and request refund if applicable.",
+ input_schema=CancelOrderInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["write"]))
+ @widget("order-cancellation")
+ async def cancel_order(self, input: CancelOrderInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Cancelling order {input.orderId}")
+ return await self.service.cancel_order(input.orderId)
diff --git a/examples/flight_booking_server.py b/examples/flight_booking_server.py
index bc6b74e..18d35f8 100644
--- a/examples/flight_booking_server.py
+++ b/examples/flight_booking_server.py
@@ -14,563 +14,47 @@
# # TOKEN_AUDIENCE=https://mcplocal
# # TOKEN_ISSUER=https://dev-5dt0utuk315713tjm.us.auth0.com
+import asyncio
+
import asyncio
import os
import sys
-import json
-import uuid
-import time
-import urllib.request
-import urllib.parse
-from typing import Dict, Any, List, Optional
-from pydantic import BaseModel, Field
-# Ensure parent directory is in sys.path so nitrostack can be imported
+# Keep direct execution working outside the repository working directory.
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
-from nitrostack import (
- tool,
- prompt,
- resource,
- injectable,
- module,
- mcp_app,
- McpApplicationFactory,
- ServerConfig,
- ExecutionContext,
- use_guards,
- widget,
- OAuthGuard,
- health_check,
+from nitrostack import McpApplicationFactory
+from examples.flight_booking.models import (
+ SearchFlightsInput,
+ FlightDetailsInput,
+ AirportSearchInput,
+ CreateOrderInput,
+ OrderDetailsInput,
+ SeatMapInput,
+ CancelOrderInput,
+ GetAirlinesInput,
)
-from nitrostack.auth.oauth import OAuthModule
-
-# 1. Custom Scope Guard Factory
-def create_scope_guard(required_scopes: list):
- class ScopeGuard:
- async def can_activate(self, context: ExecutionContext) -> bool:
- user_scopes = getattr(context.auth, "scopes", [])
- missing_scopes = [s for s in required_scopes if s not in user_scopes]
- if missing_scopes:
- raise ValueError(
- f"Insufficient scope. Required: {', '.join(required_scopes)}. "
- f"Missing: {', '.join(missing_scopes)}"
- )
- return True
- return ScopeGuard
-
-# 2. Input Validation Schemas
-class SearchFlightsInput(BaseModel):
- origin: str = Field(description="Origin airport IATA code (e.g., 'JFK', 'LHR')")
- destination: str = Field(description="Destination airport IATA code (e.g., 'LAX', 'CDG')")
- departureDate: str = Field(description="Departure date in YYYY-MM-DD format")
- returnDate: Optional[str] = Field(default=None, description="Return date in YYYY-MM-DD format for round trip")
- adults: int = Field(default=1, description="Number of adult passengers (18+)")
- cabinClass: str = Field(default="economy", description="Preferred cabin class (economy, premium_economy, business, first)")
-
-class FlightDetailsInput(BaseModel):
- offerId: str = Field(description="The flight offer ID from search results")
-
-class AirportSearchInput(BaseModel):
- query: str = Field(description="The search query for airports (e.g., 'London', 'New York')")
-
-class CreateOrderInput(BaseModel):
- offerId: str = Field(description="The offer ID to book")
- passengers: str = Field(description="JSON string containing array of passenger objects. Each passenger must have: title (mr/ms/mrs/miss/dr), givenName (first name), familyName (last name), gender (M/F), bornOn (YYYY-MM-DD), email, phoneNumber.")
-
-class OrderDetailsInput(BaseModel):
- orderId: str = Field(description="The order ID")
-
-class SeatMapInput(BaseModel):
- offerId: str = Field(description="The offer ID to get seats for")
-
-class CancelOrderInput(BaseModel):
- orderId: str = Field(description="The order ID to cancel")
-
-class GetAirlinesInput(BaseModel):
- pass
-
-
-
-# 3. Duffel Flight API Service
-@injectable()
-class DuffelService:
- def __init__(self):
- self.api_key = os.environ.get("DUFFEL_API_KEY")
- self.is_mock = not self.api_key or self.api_key.startswith("your-") or len(self.api_key) < 5
-
- def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
- if self.is_mock:
- raise ValueError("Duffel API key is not configured. Running in mock mode.")
-
- headers = {
- "Authorization": f"Bearer {self.api_key}",
- "Duffel-Version": "v1",
- "Content-Type": "application/json"
- }
- url = f"https://api.duffel.com{path}"
- req_data = json.dumps({"data": data}).encode("utf-8") if data else None
-
- req = urllib.request.Request(url, data=req_data, headers=headers, method=method)
- try:
- with urllib.request.urlopen(req, timeout=10) as response:
- res_payload = json.loads(response.read().decode("utf-8"))
- return res_payload.get("data", {})
- except Exception as e:
- sys.stderr.write(f"Duffel API Request failed: {e}\n")
- sys.stderr.flush()
- raise e
-
- async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": "orq_mock123456",
- "offers": [
- {
- "id": "off_mock123456",
- "total_amount": "450.00",
- "total_currency": "USD",
- "expires_at": "2026-12-31T12:00:00Z",
- "slices": [
- {
- "origin": {"iata_code": params["origin"], "name": "Origin Airport", "city_name": "Origin City"},
- "destination": {"iata_code": params["destination"], "name": "Dest Airport", "city_name": "Dest City"},
- "duration": "PT6H30M",
- "segments": [
- {
- "id": "seg_outbound",
- "origin": {"iata_code": params["origin"]},
- "destination": {"iata_code": params["destination"]},
- "departing_at": f"{params['departureDate']}T08:00:00Z",
- "arriving_at": f"{params['departureDate']}T14:30:00Z",
- "marketing_carrier": {"name": "Mock Airlines"},
- "marketing_carrier_flight_number": "MK123",
- "aircraft": {"name": "Boeing 787"}
- }
- ]
- }
- ]
- }
- ]
- }
-
- slices = [{"origin": params["origin"], "destination": params["destination"], "departure_date": params["departureDate"]}]
- if params.get("returnDate"):
- slices.append({"origin": params["destination"], "destination": params["origin"], "departure_date": params["returnDate"]})
-
- duffel_params = {
- "slices": slices,
- "passengers": params.get("passengers", [{"type": "adult"}]),
- "cabin_class": params.get("cabinClass", "economy"),
- "return_offers": True
- }
- res = self._request("POST", "/offer_requests", duffel_params)
- return {
- "id": res.get("id"),
- "offers": res.get("offers", []),
- "passengers": res.get("passengers", []),
- "slices": res.get("slices", [])
- }
-
- async def get_offer(self, offer_id: str) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": offer_id,
- "total_amount": "450.00",
- "total_currency": "USD",
- "expires_at": "2026-12-31T12:00:00Z",
- "slices": [
- {
- "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
- "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
- "duration": "PT6H30M",
- "segments": [
- {
- "id": "seg_mock",
- "origin": {"iata_code": "JFK"},
- "destination": {"iata_code": "LAX"},
- "departing_at": "2026-07-15T08:00:00Z",
- "arriving_at": "2026-07-15T14:30:00Z",
- "marketing_carrier": {"name": "Mock Airlines"},
- "marketing_carrier_flight_number": "MK123",
- "aircraft": {"name": "Boeing 787"}
- }
- ]
- }
- ]
- }
- return self._request("GET", f"/offers/{offer_id}")
-
- async def get_seats_for_offer(self, offer_id: str) -> List[Dict[str, Any]]:
- if self.is_mock:
- return [
- {
- "cabin_class": "economy",
- "rows": [
- {
- "row_number": 10,
- "sections": [
- {
- "elements": [
- {
- "type": "seat",
- "id": "seat_10a",
- "designator": "10A",
- "available_services": [{"total_amount": "25.00", "total_currency": "USD"}],
- "disclosures": ["window"]
- },
- {
- "type": "seat",
- "id": "seat_10b",
- "designator": "10B",
- "available_services": [{"total_amount": "0.00", "total_currency": "USD"}],
- "disclosures": ["middle"]
- }
- ]
- }
- ]
- }
- ]
- }
- ]
- res = self._request("GET", f"/seat_maps?offer_id={offer_id}")
- return res if isinstance(res, list) else []
-
- async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": "ord_mock123456",
- "status": "held",
- "total_amount": "450.00",
- "total_currency": "USD",
- "expires_at": "2026-12-31T12:00:00Z",
- "booking_reference": "ABCXYZ",
- "passengers": [
- {
- "id": f"pax_{idx}",
- "given_name": p["given_name"],
- "family_name": p["family_name"],
- "type": "adult"
- } for idx, p in enumerate(params["passengers"])
- ],
- "slices": [
- {
- "origin": {"iata_code": "JFK"},
- "destination": {"iata_code": "LAX"},
- "duration": "PT6H30M",
- "segments": [
- {
- "departing_at": "2026-07-15T08:00:00Z",
- "arriving_at": "2026-07-15T14:30:00Z"
- }
- ]
- }
- ]
- }
-
- order_payload = {
- "selected_offers": params["selectedOffers"],
- "passengers": params["passengers"],
- "type": "hold"
- }
- return self._request("POST", "/orders", order_payload)
-
- async def get_order(self, order_id: str) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": order_id,
- "status": "held",
- "total_amount": "450.00",
- "total_currency": "USD",
- "booking_reference": "ABCXYZ",
- "created_at": "2026-06-25T12:00:00Z",
- "expires_at": "2026-12-31T12:00:00Z",
- "passengers": [
- {
- "id": "pax_0",
- "given_name": "John",
- "family_name": "Doe",
- "type": "adult",
- "email": "john@example.com",
- "phone_number": "+1234567890"
- }
- ],
- "slices": [
- {
- "id": "sli_mock",
- "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
- "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
- "duration": "PT6H30M",
- "segments": [
- {
- "id": "seg_mock",
- "origin": {"iata_code": "JFK"},
- "destination": {"iata_code": "LAX"},
- "departing_at": "2026-07-15T08:00:00Z",
- "arriving_at": "2026-07-15T14:30:00Z",
- "marketing_carrier": {"name": "Mock Airlines"},
- "marketing_carrier_flight_number": "MK123",
- "aircraft": {"name": "Boeing 787"}
- }
- ]
- }
- ]
- }
- return self._request("GET", f"/orders/{order_id}")
-
- async def cancel_order(self, order_id: str) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": "ocr_mock123456",
- "refund_amount": "450.00",
- "refund_currency": "USD",
- "confirmed_at": "2026-06-25T12:30:00Z"
- }
- cancel_payload = {"order_id": order_id}
- return self._request("POST", "/order_cancellations", cancel_payload)
-
- async def get_airlines(self) -> List[Dict[str, Any]]:
- if self.is_mock:
- return [
- {"iata_code": "AA", "name": "American Airlines"},
- {"iata_code": "DL", "name": "Delta Air Lines"},
- {"iata_code": "UA", "name": "United Airlines"},
- {"iata_code": "BA", "name": "British Airways"}
- ]
- res = self._request("GET", "/airlines")
- return res if isinstance(res, list) else []
-
-
-# 4. Controllers Exposing Tools
-@injectable(deps=[DuffelService])
-class FlightTools:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @tool(
- name="search_flights",
- title="Search Flights",
- description="Search for flight offers based on origin, destination, dates, and preferences.",
- input_schema=SearchFlightsInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- @widget("flight-search-results")
- async def search_flights(self, input: SearchFlightsInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Searching flights from {input.origin} to {input.destination}")
- return await self.service.search_flights(input.model_dump())
-
- @tool(
- name="get_flight_details",
- title="Get Flight Details",
- description="Get detailed information about a specific flight offer including baggage allowance, conditions.",
- input_schema=FlightDetailsInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- @widget("flight-details")
- async def get_flight_details(self, input: FlightDetailsInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Fetching flight details for offer {input.offerId}")
- return await self.service.get_offer(input.offerId)
-
- @tool(
- name="search_airports",
- title="Search Airports",
- description="Search for airports by query string.",
- input_schema=AirportSearchInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- @widget("airport-search")
- async def search_airports(self, input: AirportSearchInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Searching airports for query: {input.query}")
- return {"airports": [{"iataCode": "JFK", "name": "John F. Kennedy Airport"}]}
-
- @tool(
- name="get_airlines",
- title="Get Airlines",
- description="Get list of common airlines.",
- input_schema=GetAirlinesInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- async def get_airlines(self, input: GetAirlinesInput, context: ExecutionContext) -> dict:
- context.logger.info("Fetching common airlines")
- res = await self.service.get_airlines()
- return {"airlines": res}
-
-
-@injectable(deps=[DuffelService])
-class BookingTools:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @tool(
- name="create_order",
- title="Create Order",
- description="Create a flight order with hold (no payment required). Collect passenger details first.",
- input_schema=CreateOrderInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["write"]))
- @widget("order-summary")
- async def create_order(self, input: CreateOrderInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Creating flight order for offer {input.offerId}")
- try:
- passengers_array = json.loads(input.passengers)
- except Exception:
- raise ValueError("Invalid passengers JSON format")
-
- passengers = []
- for p in passengers_array:
- passengers.append({
- "title": p.get("title", "mr"),
- "given_name": p.get("givenName"),
- "family_name": p.get("familyName"),
- "gender": p.get("gender", "M"),
- "born_on": p.get("bornOn"),
- "email": p.get("email"),
- "phone_number": p.get("phoneNumber")
- })
-
- order_params = {
- "selectedOffers": [input.offerId],
- "passengers": passengers
- }
- return await self.service.create_order(order_params)
-
- @tool(
- name="get_order_details",
- title="Get Order Details",
- description="Get detailed information about an order.",
- input_schema=OrderDetailsInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- @widget("order-summary")
- async def get_order_details(self, input: OrderDetailsInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Fetching details for order {input.orderId}")
- return await self.service.get_order(input.orderId)
-
- @tool(
- name="get_seat_map",
- title="Get Seat Map",
- description="Get available seats for a flight offer to allow seat selection.",
- input_schema=SeatMapInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- @widget("seat-selection")
- async def get_seat_map(self, input: SeatMapInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Fetching seat map for offer {input.offerId}")
- res = await self.service.get_seats_for_offer(input.offerId)
- return {"offerId": input.offerId, "cabins": res}
-
- @tool(
- name="cancel_order",
- title="Cancel Order",
- description="Cancel a flight order and request refund if applicable.",
- input_schema=CancelOrderInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["write"]))
- @widget("order-cancellation")
- async def cancel_order(self, input: CancelOrderInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Cancelling order {input.orderId}")
- return await self.service.cancel_order(input.orderId)
-
-
-# 5. Flight Prompts
-@injectable(deps=[DuffelService])
-class FlightPrompts:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @prompt(
- name="flight_search_assistant",
- description="An AI assistant specialized in helping users search for flights and make booking decisions."
- )
- async def flight_search_assistant(self, args: dict, context: ExecutionContext) -> str:
- return "You are a professional flight booking assistant. Help the user search for flights using search_flights, search_airports, and assist in booking holds."
-
- @prompt(
- name="flight_comparison",
- description="Compare multiple flight offers and provide recommendations."
- )
- async def flight_comparison(self, args: dict, context: ExecutionContext) -> str:
- return "Compare the provided flight offer details, check layover times, durations, and pricing, and give the user a summary of best options."
-
-
-# 6. Flight Resources
-@injectable(deps=[DuffelService])
-class FlightResources:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @resource(
- uri="flight://popular-routes",
- name="Popular Flight Routes",
- description="Information about popular routes and pricing",
- mime_type="application/json"
- )
- async def popular_routes(self, context: ExecutionContext) -> dict:
- return {
- "routes": [
- {"route": "JFK -> LAX", "price": "$200-400"},
- {"route": "LHR -> JFK", "price": "$400-800"}
- ]
- }
-
- @resource(
- uri="flight://booking-guide",
- name="Flight Booking Guide",
- description="Guide on searching and booking flights",
- mime_type="text/markdown"
- )
- async def booking_guide(self, context: ExecutionContext) -> str:
- return "# Flight Booking Guide\n\n1. Search flights.\n2. Collect passenger info.\n3. Create order hold."
-
-
-# 7. Health Check
-class SystemHealthCheck:
- def __init__(self):
- self.start_time = time.time()
-
- @health_check("system")
- def check_system(self) -> bool:
- uptime = time.time() - self.start_time
- return uptime >= 0
-
-
-# 8. Modules
-@module(
- name="flights",
- controllers=[FlightTools, BookingTools, FlightPrompts, FlightResources],
- providers=[DuffelService],
- exports=[DuffelService]
+from examples.flight_booking.guards import (
+ create_scope_guard,
)
-class FlightsModule:
- pass
-
-@module(
- name="app",
- imports=[
- # Configure OAuth resource protection
- OAuthModule.for_root(
- resource_uri="https://mcplocal",
- authorization_servers=["https://dev-5dt0utuk315713tjm.us.auth0.com"],
- scopes_supported=["read", "write", "admin"],
- token_introspection_endpoint=os.environ.get("INTROSPECTION_ENDPOINT")
- ),
- FlightsModule
- ],
- controllers=[],
- providers=[SystemHealthCheck],
- exports=[]
+from examples.flight_booking.service import (
+ DuffelService,
)
-class AppModule:
- pass
-
-
-# 9. Application Entrypoint
-@mcp_app(
- module=AppModule,
- server=ServerConfig(name="airline-ticketing-server", version="1.0.0")
+from examples.flight_booking.tools import (
+ FlightTools,
+ BookingTools,
+)
+from examples.flight_booking.definitions import (
+ FlightPrompts,
+ FlightResources,
+ SystemHealthCheck,
)
-class App:
- pass
+from examples.flight_booking.application import (
+ FlightsModule,
+ AppModule,
+ App,
+)
+
async def main():
sys.stderr.write("🔐 Starting Airline Ticketing MCP Server with OAuth 2.1...\n")
@@ -578,5 +62,6 @@ async def main():
app = await McpApplicationFactory.create(App)
await app.start()
+
if __name__ == "__main__":
asyncio.run(main())
diff --git a/nitrostack/__init__.py b/nitrostack/__init__.py
index 9f1c3d5..f6f10e0 100644
--- a/nitrostack/__init__.py
+++ b/nitrostack/__init__.py
@@ -1,247 +1,252 @@
# NitroStack Python SDK Public API Exports
-from nitrostack.core.decorators import (
- tool,
- resource,
- prompt,
- initial_tool,
- widget,
- ToolAnnotations,
- ResourceAnnotations,
- PromptArgument,
- PromptMessage,
- ToolInvocation,
- ToolExamples,
- widget_resource_uri,
-)
-from nitrostack.core.context import (
- ExecutionContext,
- AuthContext,
- TaskContext,
-)
-from nitrostack.core.task import (
- TaskManager,
- TaskData,
- TaskStatus,
- TERMINAL_STATUSES,
- is_terminal_status,
-)
-from nitrostack.core.di import (
- injectable,
- DIContainer,
-)
-from nitrostack.core.module import (
- module,
-)
-from nitrostack.core.app import (
- mcp_app,
- McpApplicationFactory,
- ServerConfig,
-)
-from nitrostack.core.errors import (
- ToolExecutionError,
- ValidationError,
- ResourceNotFoundError,
- PromptNotFoundError,
- TaskCancelledError,
- TaskNotFoundError,
- TaskAlreadyTerminalError,
- InvalidTaskTransitionError,
- TaskExpiredError,
- ConfigurationError,
- DependencyResolutionError,
- OAuthError,
- TokenInactiveError,
- AudienceMismatchError,
-)
-from nitrostack.core.pipeline import (
- use_guards,
- use_middleware,
- use_interceptors,
- use_pipes,
- use_filters,
- ApiKeyGuard,
- JwtGuard,
- OAuthGuard,
-)
-from nitrostack.core.additional_decorators import (
- cache,
- rate_limit,
- health_check,
-)
-from nitrostack.events.event_emitter import (
- on_event,
- EventEmitter,
-)
-from nitrostack.auth.api_key import (
- ApiKeyModule,
-)
-from nitrostack.auth.jwt import (
- JWTModule,
-)
-from nitrostack.auth.oauth import (
- OAuthModule,
- OAuthService,
- generate_www_authenticate_header,
-)
-from nitrostack.auth.cimd import (
- CimdFetchError,
- CimdValidationError,
- is_blocked_ip,
- resolve_cimd,
- validate_client_identifier_url,
-)
-from nitrostack.auth.oauth_security import (
- AuthorizationIssuerMismatchError,
- validate_authorization_iss,
-)
-from nitrostack.auth.pkce import (
- generate_code_challenge,
- generate_code_verifier,
- generate_pkce_params,
- is_valid_code_verifier,
- validate_pkce_support,
- verify_pkce,
-)
-from nitrostack.auth.scopes import (
- has_all_scopes,
- has_any_scope,
- has_scope,
- require_scopes,
-)
-from nitrostack.auth.config import (
- ConfigModule,
- ConfigService,
-)
-from nitrostack.widgets import (
- Component,
- WidgetCsp,
- WidgetOptions,
- create_component,
- get_app_mode,
- get_widget_mime_type,
- is_mcp_app_mode,
- is_openai_mode,
- OPENAI_SKYBRIDGE_MIME_TYPE,
- RESOURCE_MIME_TYPE_MCP_APP,
- RESOURCE_MIME_TYPE_OPENAI,
-)
-from nitrostack.testing import (
- NitroTestingModule,
-)
-from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION
-from nitrostack.protocol.errors import JsonRpcErrorCode
-from nitrostack.protocol.mrtr import InputRequest, InputRequiredResult, accepted_content, input_required
-from nitrostack.tasks import InMemoryTaskStore, TaskAccessContext, TaskStore
-from nitrostack.tasks.authorization import check_task_access, extract_task_access_context
-from nitrostack.runtime import StatelessInvariants, assert_stateless_headers
-from nitrostack.transports import wrap_stateless_transport, StatelessIngressPipeline
-
-
-__all__ = [
- "tool",
- "resource",
- "prompt",
- "initial_tool",
- "widget",
- "ToolAnnotations",
- "ResourceAnnotations",
- "PromptArgument",
- "PromptMessage",
- "ToolInvocation",
- "ToolExamples",
- "ExecutionContext",
- "AuthContext",
- "injectable",
- "DIContainer",
- "module",
- "mcp_app",
- "McpApplicationFactory",
- "ServerConfig",
- "ToolExecutionError",
- "ValidationError",
- "ResourceNotFoundError",
- "PromptNotFoundError",
- "use_guards",
- "use_middleware",
- "use_interceptors",
- "use_pipes",
- "use_filters",
- "ApiKeyGuard",
- "JwtGuard",
- "OAuthGuard",
- "cache",
- "rate_limit",
- "health_check",
- "on_event",
- "EventEmitter",
- "ApiKeyModule",
- "JWTModule",
- "OAuthModule",
- "OAuthService",
- "generate_www_authenticate_header",
- "validate_client_identifier_url",
- "resolve_cimd",
- "is_blocked_ip",
- "CimdValidationError",
- "CimdFetchError",
- "validate_authorization_iss",
- "AuthorizationIssuerMismatchError",
- "generate_code_challenge",
- "generate_code_verifier",
- "generate_pkce_params",
- "is_valid_code_verifier",
- "validate_pkce_support",
- "verify_pkce",
- "has_all_scopes",
- "has_any_scope",
- "has_scope",
- "require_scopes",
- "ConfigurationError",
- "DependencyResolutionError",
- "OAuthError",
- "TokenInactiveError",
- "AudienceMismatchError",
- "ConfigModule",
- "ConfigService",
- "NitroTestingModule",
- "TaskContext",
- "TaskCancelledError",
- "TaskManager",
- "TaskData",
- "TaskStatus",
- "TERMINAL_STATUSES",
- "is_terminal_status",
- "TaskNotFoundError",
- "TaskAlreadyTerminalError",
- "InvalidTaskTransitionError",
- "TaskExpiredError",
- "widget_resource_uri",
- "Component",
- "WidgetCsp",
- "WidgetOptions",
- "create_component",
- "get_app_mode",
- "get_widget_mime_type",
- "is_mcp_app_mode",
- "is_openai_mode",
- "OPENAI_SKYBRIDGE_MIME_TYPE",
- "RESOURCE_MIME_TYPE_MCP_APP",
- "RESOURCE_MIME_TYPE_OPENAI",
- "NitroTestingModule",
- "MODERN_PROTOCOL_VERSION",
- "JsonRpcErrorCode",
- "InputRequest",
- "InputRequiredResult",
- "accepted_content",
- "input_required",
- "TaskAccessContext",
- "TaskStore",
- "InMemoryTaskStore",
- "check_task_access",
- "extract_task_access_context",
- "StatelessInvariants",
- "assert_stateless_headers",
- "wrap_stateless_transport",
- "StatelessIngressPipeline",
-]
+from __future__ import annotations
+
+import importlib
+import pkgutil
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from nitrostack._export_map import EXPORT_LOCATIONS
+
+_PKG_ROOT = Path(__file__).resolve().parent
+
+
+def _subpackage_names() -> frozenset[str]:
+ names = {m.name for m in pkgutil.iter_modules([str(_PKG_ROOT)]) if not m.name.startswith("_")}
+ for path in _PKG_ROOT.iterdir():
+ if path.is_dir() and not path.name.startswith("_") and path.name != "__pycache__":
+ names.add(path.name)
+ return frozenset(names)
+
+# NitroStack Python SDK Public API Exports
+
+try:
+ from importlib.metadata import PackageNotFoundError, version as _package_version
+
+ __version__ = _package_version("nitrostack")
+except PackageNotFoundError:
+ # Keep the SDK version available when running directly from a source checkout.
+ try:
+ from pathlib import Path
+
+ try:
+ import tomllib
+ except ModuleNotFoundError: # Python 3.10
+ import tomli as tomllib
+
+ _project_metadata = tomllib.loads(
+ (Path(__file__).resolve().parent.parent / "pyproject.toml").read_text(encoding="utf-8")
+ )
+ __version__ = str(_project_metadata["project"]["version"])
+ except (ImportError, KeyError, OSError, ValueError, TypeError):
+ __version__ = "unknown"
+
+
+__all__ = ['AuthorizationFlow',
+ 'ClientRegistration',
+ 'OAuth2Client',
+ 'OAuth2ClientConfig',
+ 'OAuthClientError',
+ 'FileTokenStore',
+ 'MemoryTokenStore',
+ 'StoredToken',
+ 'TokenStore',
+ 'TokenStoreError',
+ 'calculate_expiration',
+ 'create_default_token_store',
+ 'get_default_store_path',
+ 'get_well_known_metadata_uris',
+ 'is_token_expired',
+ 'parse_www_authenticate_header',
+ 'token_response_to_stored',
+ '__version__',
+ 'DataSpilloverInterceptor',
+ 'FileSpilloverStore',
+ 'MemorySpilloverStore',
+ 'PayloadTooLargeError',
+ 'SpilloverEntry',
+ 'SpilloverStore',
+ 'generate_preview',
+ 'tool',
+ 'resource',
+ 'prompt',
+ 'initial_tool',
+ 'widget',
+ 'ToolAnnotations',
+ 'ResourceAnnotations',
+ 'PromptArgument',
+ 'PromptMessage',
+ 'ToolInvocation',
+ 'ToolExamples',
+ 'ExecutionContext',
+ 'AuthContext',
+ 'injectable',
+ 'DIContainer',
+ 'module',
+ 'mcp_app',
+ 'McpApplicationFactory',
+ 'ServerConfig',
+ 'ToolExecutionError',
+ 'ValidationError',
+ 'RateLimitExceededError',
+ 'ResourceNotFoundError',
+ 'PromptNotFoundError',
+ 'use_guards',
+ 'use_middleware',
+ 'use_interceptors',
+ 'use_pipes',
+ 'use_filters',
+ 'ApiKeyGuard',
+ 'JwtGuard',
+ 'OAuthGuard',
+ 'cache',
+ 'rate_limit',
+ 'health_check',
+ 'TransformTelemetry',
+ 'ServerHealthPayload',
+ 'on_event',
+ 'EventEmitter',
+ 'ApiKeyModule',
+ 'JWTModule',
+ 'OAuthModule',
+ 'OAuthService',
+ 'generate_www_authenticate_header',
+ 'validate_client_identifier_url',
+ 'resolve_cimd',
+ 'is_blocked_ip',
+ 'CimdValidationError',
+ 'CimdFetchError',
+ 'validate_authorization_iss',
+ 'AuthorizationIssuerMismatchError',
+ 'generate_code_challenge',
+ 'generate_code_verifier',
+ 'generate_pkce_params',
+ 'is_valid_code_verifier',
+ 'validate_pkce_support',
+ 'verify_pkce',
+ 'has_all_scopes',
+ 'has_any_scope',
+ 'has_scope',
+ 'require_scopes',
+ 'ConfigurationError',
+ 'DependencyResolutionError',
+ 'OAuthError',
+ 'TokenInactiveError',
+ 'AudienceMismatchError',
+ 'ConfigModule',
+ 'ConfigService',
+ 'SecretValue',
+ 'is_secret_value',
+ 'unwrap_secret',
+ 'setup_jwt_auth',
+ 'setup_api_key_auth',
+ 'setup_oauth_auth',
+ 'generate_test_credentials',
+ 'validate_auth_env',
+ 'print_auth_setup_instructions',
+ 'NitroTestingModule',
+ 'TaskContext',
+ 'LogRecord',
+ 'LogEmitter',
+ 'LogEmitterHandler',
+ 'log_emitter',
+ 'TaskCancelledError',
+ 'TaskManager',
+ 'TaskData',
+ 'TaskStatus',
+ 'TERMINAL_STATUSES',
+ 'is_terminal_status',
+ 'TaskNotFoundError',
+ 'TaskAlreadyTerminalError',
+ 'InvalidTaskTransitionError',
+ 'TaskExpiredError',
+ 'WidgetExample',
+ 'WidgetManifest',
+ 'WidgetMetadata',
+ 'WidgetRegistry',
+ 'get_widget_registry',
+ 'widget_resource_uri',
+ 'Component',
+ 'WidgetCsp',
+ 'WidgetOptions',
+ 'create_component',
+ 'get_app_mode',
+ 'get_widget_mime_type',
+ 'is_mcp_app_mode',
+ 'is_openai_mode',
+ 'OPENAI_SKYBRIDGE_MIME_TYPE',
+ 'RESOURCE_MIME_TYPE_MCP_APP',
+ 'RESOURCE_MIME_TYPE_OPENAI',
+ 'NitroTestingModule',
+ 'MODERN_PROTOCOL_VERSION',
+ 'JsonRpcErrorCode',
+ 'InputRequest',
+ 'InputRequiredResult',
+ 'accepted_content',
+ 'input_required',
+ 'TaskAccessContext',
+ 'TaskStore',
+ 'InMemoryTaskStore',
+ 'check_task_access',
+ 'extract_task_access_context',
+ 'StatelessInvariants',
+ 'assert_stateless_headers']
+
+def __getattr__(name: str) -> object:
+ location = EXPORT_LOCATIONS.get(name)
+ if location is not None:
+ module_name, attr = location
+ module = importlib.import_module(module_name)
+ value = getattr(module, attr)
+ globals()[name] = value
+ return value
+ if name.startswith("_") or name not in _subpackage_names():
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ try:
+ module = importlib.import_module(f"{__name__}.{name}")
+ except ModuleNotFoundError as exc:
+ if exc.name == f"{__name__}.{name}":
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
+ raise
+ globals()[name] = module
+ return module
+
+
+def __dir__() -> list[str]:
+ return sorted({*globals().keys(), *__all__, *_subpackage_names()})
+
+if TYPE_CHECKING:
+ from nitrostack.widgets.registry import WidgetExample, WidgetManifest, WidgetMetadata, WidgetRegistry, get_widget_registry # noqa: F401
+ from nitrostack.core.interceptors import DataSpilloverInterceptor, FileSpilloverStore, MemorySpilloverStore, PayloadTooLargeError, SpilloverEntry, SpilloverStore, generate_preview # noqa: F401
+ from nitrostack.core.decorators import tool, resource, prompt, initial_tool, widget, ToolAnnotations, ResourceAnnotations, PromptArgument, PromptMessage, ToolInvocation, ToolExamples, widget_resource_uri # noqa: F401
+ from nitrostack.core.context import ExecutionContext, AuthContext, TaskContext # noqa: F401
+ from nitrostack.core.log_emitter import LogRecord, LogEmitter, LogEmitterHandler, log_emitter # noqa: F401
+ from nitrostack.core.task import TaskManager, TaskData, TaskStatus, TERMINAL_STATUSES, is_terminal_status # noqa: F401
+ from nitrostack.core.di import injectable, DIContainer # noqa: F401
+ from nitrostack.core.module import module # noqa: F401
+ from nitrostack.core.app import mcp_app, McpApplicationFactory, ServerConfig # noqa: F401
+ from nitrostack.core.errors import ToolExecutionError, ValidationError, RateLimitExceededError, ResourceNotFoundError, PromptNotFoundError, TaskCancelledError, TaskNotFoundError, TaskAlreadyTerminalError, InvalidTaskTransitionError, TaskExpiredError, ConfigurationError, DependencyResolutionError, OAuthError, TokenInactiveError, AudienceMismatchError # noqa: F401
+ from nitrostack.core.pipeline import use_guards, use_middleware, use_interceptors, use_pipes, use_filters, ApiKeyGuard, JwtGuard, OAuthGuard # noqa: F401
+ from nitrostack.core.additional_decorators import cache, rate_limit, health_check, TransformTelemetry, ServerHealthPayload # noqa: F401
+ from nitrostack.events.event_emitter import on_event, EventEmitter # noqa: F401
+ from nitrostack.auth.api_key import ApiKeyModule # noqa: F401
+ from nitrostack.auth.jwt import JWTModule # noqa: F401
+ from nitrostack.auth.oauth import OAuthModule, OAuthService, generate_www_authenticate_header # noqa: F401
+ from nitrostack.auth.cimd import CimdFetchError, CimdValidationError, is_blocked_ip, resolve_cimd, validate_client_identifier_url # noqa: F401
+ from nitrostack.auth.oauth_security import AuthorizationIssuerMismatchError, validate_authorization_iss # noqa: F401
+ from nitrostack.auth.pkce import generate_code_challenge, generate_code_verifier, generate_pkce_params, is_valid_code_verifier, validate_pkce_support, verify_pkce # noqa: F401
+ from nitrostack.auth.client import AuthorizationFlow, ClientRegistration, OAuth2Client, OAuth2ClientConfig, OAuthClientError, get_well_known_metadata_uris, parse_www_authenticate_header # noqa: F401
+ from nitrostack.auth.token_store import FileTokenStore, MemoryTokenStore, StoredToken, TokenStore, TokenStoreError, calculate_expiration, create_default_token_store, get_default_store_path, is_token_expired, token_response_to_stored # noqa: F401
+ from nitrostack.auth.scopes import has_all_scopes, has_any_scope, has_scope, require_scopes # noqa: F401
+ from nitrostack.auth.config import ConfigModule, ConfigService # noqa: F401
+ from nitrostack.auth.secret import SecretValue, is_secret_value, unwrap_secret # noqa: F401
+ from nitrostack.auth.setup import generate_test_credentials, print_auth_setup_instructions, setup_api_key_auth, setup_jwt_auth, setup_oauth_auth, validate_auth_env # noqa: F401
+ from nitrostack.widgets import Component, WidgetCsp, WidgetOptions, create_component, get_app_mode, get_widget_mime_type, is_mcp_app_mode, is_openai_mode, OPENAI_SKYBRIDGE_MIME_TYPE, RESOURCE_MIME_TYPE_MCP_APP, RESOURCE_MIME_TYPE_OPENAI # noqa: F401
+ from nitrostack.testing import NitroTestingModule # noqa: F401
+ from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION # noqa: F401
+ from nitrostack.protocol.errors import JsonRpcErrorCode # noqa: F401
+ from nitrostack.protocol.mrtr import InputRequest, InputRequiredResult, accepted_content, input_required # noqa: F401
+ from nitrostack.tasks import InMemoryTaskStore, TaskAccessContext, TaskStore # noqa: F401
+ from nitrostack.tasks.authorization import check_task_access, extract_task_access_context # noqa: F401
+ from nitrostack.runtime import StatelessInvariants, assert_stateless_headers # noqa: F401
diff --git a/nitrostack/_export_map.py b/nitrostack/_export_map.py
new file mode 100644
index 0000000..eb18a65
--- /dev/null
+++ b/nitrostack/_export_map.py
@@ -0,0 +1,153 @@
+"""Lazy public API symbol locations (PEP 562)."""
+
+from typing import Dict, Tuple
+
+EXPORT_LOCATIONS: Dict[str, Tuple[str, str]] = {
+ "ApiKeyGuard": ("nitrostack.core.pipeline", "ApiKeyGuard"),
+ "ApiKeyModule": ("nitrostack.auth.api_key", "ApiKeyModule"),
+ "AudienceMismatchError": ("nitrostack.core.errors", "AudienceMismatchError"),
+ "AuthContext": ("nitrostack.core.context", "AuthContext"),
+ "AuthorizationFlow": ("nitrostack.auth.client", "AuthorizationFlow"),
+ "AuthorizationIssuerMismatchError": ("nitrostack.auth.oauth_security", "AuthorizationIssuerMismatchError"),
+ "CimdFetchError": ("nitrostack.auth.cimd", "CimdFetchError"),
+ "CimdValidationError": ("nitrostack.auth.cimd", "CimdValidationError"),
+ "ClientRegistration": ("nitrostack.auth.client", "ClientRegistration"),
+ "Component": ("nitrostack.widgets", "Component"),
+ "ConfigModule": ("nitrostack.auth.config", "ConfigModule"),
+ "ConfigService": ("nitrostack.auth.config", "ConfigService"),
+ "ConfigurationError": ("nitrostack.core.errors", "ConfigurationError"),
+ "DIContainer": ("nitrostack.core.di", "DIContainer"),
+ "DataSpilloverInterceptor": ("nitrostack.core.interceptors", "DataSpilloverInterceptor"),
+ "DependencyResolutionError": ("nitrostack.core.errors", "DependencyResolutionError"),
+ "EventEmitter": ("nitrostack.events.event_emitter", "EventEmitter"),
+ "ExecutionContext": ("nitrostack.core.context", "ExecutionContext"),
+ "FileSpilloverStore": ("nitrostack.core.interceptors", "FileSpilloverStore"),
+ "FileTokenStore": ("nitrostack.auth.token_store", "FileTokenStore"),
+ "InMemoryTaskStore": ("nitrostack.tasks", "InMemoryTaskStore"),
+ "InputRequest": ("nitrostack.protocol.mrtr", "InputRequest"),
+ "InputRequiredResult": ("nitrostack.protocol.mrtr", "InputRequiredResult"),
+ "InvalidTaskTransitionError": ("nitrostack.core.errors", "InvalidTaskTransitionError"),
+ "JWTModule": ("nitrostack.auth.jwt", "JWTModule"),
+ "JsonRpcErrorCode": ("nitrostack.protocol.errors", "JsonRpcErrorCode"),
+ "JwtGuard": ("nitrostack.core.pipeline", "JwtGuard"),
+ "LogEmitter": ("nitrostack.core.log_emitter", "LogEmitter"),
+ "LogEmitterHandler": ("nitrostack.core.log_emitter", "LogEmitterHandler"),
+ "LogRecord": ("nitrostack.core.log_emitter", "LogRecord"),
+ "MODERN_PROTOCOL_VERSION": ("nitrostack.protocol.version", "MODERN_PROTOCOL_VERSION"),
+ "McpApplicationFactory": ("nitrostack.core.app", "McpApplicationFactory"),
+ "MemorySpilloverStore": ("nitrostack.core.interceptors", "MemorySpilloverStore"),
+ "MemoryTokenStore": ("nitrostack.auth.token_store", "MemoryTokenStore"),
+ "NitroTestingModule": ("nitrostack.testing", "NitroTestingModule"),
+ "OAuth2Client": ("nitrostack.auth.client", "OAuth2Client"),
+ "OAuth2ClientConfig": ("nitrostack.auth.client", "OAuth2ClientConfig"),
+ "OAuthClientError": ("nitrostack.auth.client", "OAuthClientError"),
+ "OAuthError": ("nitrostack.core.errors", "OAuthError"),
+ "OAuthGuard": ("nitrostack.core.pipeline", "OAuthGuard"),
+ "OAuthModule": ("nitrostack.auth.oauth", "OAuthModule"),
+ "OAuthService": ("nitrostack.auth.oauth", "OAuthService"),
+ "OPENAI_SKYBRIDGE_MIME_TYPE": ("nitrostack.widgets", "OPENAI_SKYBRIDGE_MIME_TYPE"),
+ "PayloadTooLargeError": ("nitrostack.core.interceptors", "PayloadTooLargeError"),
+ "PromptArgument": ("nitrostack.core.decorators", "PromptArgument"),
+ "PromptMessage": ("nitrostack.core.decorators", "PromptMessage"),
+ "PromptNotFoundError": ("nitrostack.core.errors", "PromptNotFoundError"),
+ "RESOURCE_MIME_TYPE_MCP_APP": ("nitrostack.widgets", "RESOURCE_MIME_TYPE_MCP_APP"),
+ "RESOURCE_MIME_TYPE_OPENAI": ("nitrostack.widgets", "RESOURCE_MIME_TYPE_OPENAI"),
+ "RateLimitExceededError": ("nitrostack.core.errors", "RateLimitExceededError"),
+ "ResourceAnnotations": ("nitrostack.core.decorators", "ResourceAnnotations"),
+ "ResourceNotFoundError": ("nitrostack.core.errors", "ResourceNotFoundError"),
+ "SecretValue": ("nitrostack.auth.secret", "SecretValue"),
+ "ServerConfig": ("nitrostack.core.app", "ServerConfig"),
+ "ServerHealthPayload": ("nitrostack.core.additional_decorators", "ServerHealthPayload"),
+ "SpilloverEntry": ("nitrostack.core.interceptors", "SpilloverEntry"),
+ "SpilloverStore": ("nitrostack.core.interceptors", "SpilloverStore"),
+ "StatelessInvariants": ("nitrostack.runtime", "StatelessInvariants"),
+ "StoredToken": ("nitrostack.auth.token_store", "StoredToken"),
+ "TERMINAL_STATUSES": ("nitrostack.core.task", "TERMINAL_STATUSES"),
+ "TaskAccessContext": ("nitrostack.tasks", "TaskAccessContext"),
+ "TaskAlreadyTerminalError": ("nitrostack.core.errors", "TaskAlreadyTerminalError"),
+ "TaskCancelledError": ("nitrostack.core.errors", "TaskCancelledError"),
+ "TaskContext": ("nitrostack.core.context", "TaskContext"),
+ "TaskData": ("nitrostack.core.task", "TaskData"),
+ "TaskExpiredError": ("nitrostack.core.errors", "TaskExpiredError"),
+ "TaskManager": ("nitrostack.core.task", "TaskManager"),
+ "TaskNotFoundError": ("nitrostack.core.errors", "TaskNotFoundError"),
+ "TaskStatus": ("nitrostack.core.task", "TaskStatus"),
+ "TaskStore": ("nitrostack.tasks", "TaskStore"),
+ "TokenInactiveError": ("nitrostack.core.errors", "TokenInactiveError"),
+ "TokenStore": ("nitrostack.auth.token_store", "TokenStore"),
+ "TokenStoreError": ("nitrostack.auth.token_store", "TokenStoreError"),
+ "ToolAnnotations": ("nitrostack.core.decorators", "ToolAnnotations"),
+ "ToolExamples": ("nitrostack.core.decorators", "ToolExamples"),
+ "ToolExecutionError": ("nitrostack.core.errors", "ToolExecutionError"),
+ "ToolInvocation": ("nitrostack.core.decorators", "ToolInvocation"),
+ "TransformTelemetry": ("nitrostack.core.additional_decorators", "TransformTelemetry"),
+ "ValidationError": ("nitrostack.core.errors", "ValidationError"),
+ "WidgetCsp": ("nitrostack.widgets", "WidgetCsp"),
+ "WidgetExample": ("nitrostack.widgets.registry", "WidgetExample"),
+ "WidgetManifest": ("nitrostack.widgets.registry", "WidgetManifest"),
+ "WidgetMetadata": ("nitrostack.widgets.registry", "WidgetMetadata"),
+ "WidgetOptions": ("nitrostack.widgets", "WidgetOptions"),
+ "WidgetRegistry": ("nitrostack.widgets.registry", "WidgetRegistry"),
+ "accepted_content": ("nitrostack.protocol.mrtr", "accepted_content"),
+ "assert_stateless_headers": ("nitrostack.runtime", "assert_stateless_headers"),
+ "cache": ("nitrostack.core.additional_decorators", "cache"),
+ "calculate_expiration": ("nitrostack.auth.token_store", "calculate_expiration"),
+ "check_task_access": ("nitrostack.tasks.authorization", "check_task_access"),
+ "create_component": ("nitrostack.widgets", "create_component"),
+ "create_default_token_store": ("nitrostack.auth.token_store", "create_default_token_store"),
+ "extract_task_access_context": ("nitrostack.tasks.authorization", "extract_task_access_context"),
+ "generate_code_challenge": ("nitrostack.auth.pkce", "generate_code_challenge"),
+ "generate_code_verifier": ("nitrostack.auth.pkce", "generate_code_verifier"),
+ "generate_pkce_params": ("nitrostack.auth.pkce", "generate_pkce_params"),
+ "generate_preview": ("nitrostack.core.interceptors", "generate_preview"),
+ "generate_test_credentials": ("nitrostack.auth.setup", "generate_test_credentials"),
+ "generate_www_authenticate_header": ("nitrostack.auth.oauth", "generate_www_authenticate_header"),
+ "get_app_mode": ("nitrostack.widgets", "get_app_mode"),
+ "get_default_store_path": ("nitrostack.auth.token_store", "get_default_store_path"),
+ "get_well_known_metadata_uris": ("nitrostack.auth.client", "get_well_known_metadata_uris"),
+ "get_widget_mime_type": ("nitrostack.widgets", "get_widget_mime_type"),
+ "get_widget_registry": ("nitrostack.widgets.registry", "get_widget_registry"),
+ "has_all_scopes": ("nitrostack.auth.scopes", "has_all_scopes"),
+ "has_any_scope": ("nitrostack.auth.scopes", "has_any_scope"),
+ "has_scope": ("nitrostack.auth.scopes", "has_scope"),
+ "health_check": ("nitrostack.core.additional_decorators", "health_check"),
+ "initial_tool": ("nitrostack.core.decorators", "initial_tool"),
+ "injectable": ("nitrostack.core.di", "injectable"),
+ "input_required": ("nitrostack.protocol.mrtr", "input_required"),
+ "is_blocked_ip": ("nitrostack.auth.cimd", "is_blocked_ip"),
+ "is_mcp_app_mode": ("nitrostack.widgets", "is_mcp_app_mode"),
+ "is_openai_mode": ("nitrostack.widgets", "is_openai_mode"),
+ "is_secret_value": ("nitrostack.auth.secret", "is_secret_value"),
+ "is_terminal_status": ("nitrostack.core.task", "is_terminal_status"),
+ "is_token_expired": ("nitrostack.auth.token_store", "is_token_expired"),
+ "is_valid_code_verifier": ("nitrostack.auth.pkce", "is_valid_code_verifier"),
+ "log_emitter": ("nitrostack.core.log_emitter", "log_emitter"),
+ "mcp_app": ("nitrostack.core.app", "mcp_app"),
+ "module": ("nitrostack.core.module", "module"),
+ "on_event": ("nitrostack.events.event_emitter", "on_event"),
+ "parse_www_authenticate_header": ("nitrostack.auth.client", "parse_www_authenticate_header"),
+ "print_auth_setup_instructions": ("nitrostack.auth.setup", "print_auth_setup_instructions"),
+ "prompt": ("nitrostack.core.decorators", "prompt"),
+ "rate_limit": ("nitrostack.core.additional_decorators", "rate_limit"),
+ "require_scopes": ("nitrostack.auth.scopes", "require_scopes"),
+ "resolve_cimd": ("nitrostack.auth.cimd", "resolve_cimd"),
+ "resource": ("nitrostack.core.decorators", "resource"),
+ "setup_api_key_auth": ("nitrostack.auth.setup", "setup_api_key_auth"),
+ "setup_jwt_auth": ("nitrostack.auth.setup", "setup_jwt_auth"),
+ "setup_oauth_auth": ("nitrostack.auth.setup", "setup_oauth_auth"),
+ "token_response_to_stored": ("nitrostack.auth.token_store", "token_response_to_stored"),
+ "tool": ("nitrostack.core.decorators", "tool"),
+ "unwrap_secret": ("nitrostack.auth.secret", "unwrap_secret"),
+ "use_filters": ("nitrostack.core.pipeline", "use_filters"),
+ "use_guards": ("nitrostack.core.pipeline", "use_guards"),
+ "use_interceptors": ("nitrostack.core.pipeline", "use_interceptors"),
+ "use_middleware": ("nitrostack.core.pipeline", "use_middleware"),
+ "use_pipes": ("nitrostack.core.pipeline", "use_pipes"),
+ "validate_auth_env": ("nitrostack.auth.setup", "validate_auth_env"),
+ "validate_authorization_iss": ("nitrostack.auth.oauth_security", "validate_authorization_iss"),
+ "validate_client_identifier_url": ("nitrostack.auth.cimd", "validate_client_identifier_url"),
+ "validate_pkce_support": ("nitrostack.auth.pkce", "validate_pkce_support"),
+ "verify_pkce": ("nitrostack.auth.pkce", "verify_pkce"),
+ "widget": ("nitrostack.core.decorators", "widget"),
+ "widget_resource_uri": ("nitrostack.core.decorators", "widget_resource_uri"),
+}
diff --git a/nitrostack/auth/_client_types.py b/nitrostack/auth/_client_types.py
new file mode 100644
index 0000000..19daa5e
--- /dev/null
+++ b/nitrostack/auth/_client_types.py
@@ -0,0 +1,98 @@
+"""Secret-safe OAuth configuration, results, errors, and transport records."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field, fields
+from types import MappingProxyType
+from typing import Any, Mapping
+
+from nitrostack.auth.secret import SecretValue
+
+
+_OAUTH_ERRORS = frozenset({
+ "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client",
+ "unsupported_grant_type", "invalid_scope", "access_denied", "server_error",
+ "temporarily_unavailable", "invalid_token", "unsupported_token_type",
+ "invalid_redirect_uri", "invalid_client_metadata",
+})
+
+
+class OAuthClientError(ValueError):
+ """Only operation, status, and recognized OAuth error codes are exposed."""
+
+ def __init__(self, operation: str, *, status: int | None = None, error_code=None):
+ self.operation = operation
+ self.status = status
+ self.error_code = error_code if isinstance(error_code, str) and error_code in _OAUTH_ERRORS else None
+ suffix = f" (HTTP {status})" if status is not None else ""
+ if self.error_code:
+ suffix += f": {self.error_code}"
+ super().__init__(f"OAuth {operation} failed{suffix}")
+
+
+@dataclass(frozen=True)
+class OAuth2ClientConfig:
+ client_id: str | None = field(default=None, repr=False)
+ client_secret: str | SecretValue | None = field(default=None, repr=False)
+ issuer: str | None = field(default=None, repr=False)
+ redirect_uri: str | None = field(default=None, repr=False)
+ authorization_endpoint: str | None = field(default=None, repr=False)
+ token_endpoint: str | None = field(default=None, repr=False)
+ revocation_endpoint: str | None = field(default=None, repr=False)
+ registration_endpoint: str | None = field(default=None, repr=False)
+ protected_resource_metadata_url: str | None = field(default=None, repr=False)
+ authorization_server_metadata_url: str | None = field(default=None, repr=False)
+
+ def __post_init__(self):
+ if any(value is not None and (not isinstance(value, str) or not value)
+ for value in (getattr(self, item.name) for item in fields(self) if item.name != "client_secret")):
+ raise OAuthClientError("configuration")
+ if self.client_secret is not None and not isinstance(self.client_secret, SecretValue):
+ if not isinstance(self.client_secret, str) or not self.client_secret:
+ raise OAuthClientError("configuration")
+
+
+@dataclass(frozen=True)
+class AuthorizationFlow:
+ authorization_url: str = field(repr=False)
+ state: str = field(repr=False)
+ code_verifier: str = field(repr=False)
+ code_challenge: str = field(repr=False)
+ code_challenge_method: str = "S256"
+
+
+@dataclass(frozen=True)
+class ClientRegistration:
+ client_id: str = field(repr=False)
+ client_secret: str | None = field(default=None, repr=False)
+ metadata: Mapping[str, Any] = field(default_factory=dict, repr=False)
+
+ def __post_init__(self):
+ if (not isinstance(self.client_id, str) or not self.client_id
+ or (self.client_secret is not None and not isinstance(self.client_secret, str))):
+ raise OAuthClientError("registration response")
+ object.__setattr__(self, "metadata", MappingProxyType(dict(self.metadata)))
+
+ def to_dict(self) -> dict[str, Any]:
+ """Explicit credential-bearing output; never log this mapping."""
+ result = {**self.metadata, "client_id": self.client_id}
+ if self.client_secret is not None:
+ result["client_secret"] = self.client_secret
+ return result
+
+
+@dataclass(frozen=True)
+class _Request:
+ method: str
+ url: str = field(repr=False)
+ headers: Mapping[str, str] = field(repr=False)
+ body: bytes | None = field(repr=False)
+ timeout: float
+ pinned_ip: str | None = field(default=None, repr=False)
+
+
+@dataclass(frozen=True)
+class _Response:
+ status: int
+ headers: Mapping[str, str] = field(repr=False)
+ body: bytes = field(repr=False)
diff --git a/nitrostack/auth/api_key.py b/nitrostack/auth/api_key.py
index fd0eaf2..6cb98b9 100644
--- a/nitrostack/auth/api_key.py
+++ b/nitrostack/auth/api_key.py
@@ -1,9 +1,10 @@
import secrets
import hashlib
import os
-from typing import List, Optional
+from typing import List, Optional, Sequence, Union
from nitrostack.core.module import module
from nitrostack.core.di import DIContainer
+from nitrostack.auth.secret import SecretValue, unwrap_secret
class ApiKeyService:
def __init__(
@@ -11,10 +12,13 @@ def __init__(
keys_env_prefix: str = "API_KEY",
header_name: str = "x-api-key",
hashed: bool = False,
+ keys: Optional[Sequence[Union[SecretValue, str]]] = None,
):
self.keys_env_prefix = keys_env_prefix
self.header_name = header_name
self.hashed = hashed
+ # Keys passed in code are used in addition to the ones found in the environment.
+ self._explicit_keys: List[Union[SecretValue, str]] = list(keys or [])
self._keys: List[str] = []
self._load_keys()
@@ -29,7 +33,8 @@ def _load_keys(self) -> None:
for k, v in os.environ.items():
if k.startswith(f"{self.keys_env_prefix}_"):
keys.append(v)
-
+
+ keys.extend(unwrap_secret(k) for k in self._explicit_keys)
self._keys = keys
def get_keys(self) -> List[str]:
@@ -65,11 +70,13 @@ def for_root(
keys_env_prefix: str = "API_KEY",
header_name: str = "x-api-key",
hashed: bool = False,
+ keys: Optional[Sequence[Union[SecretValue, str]]] = None,
):
service = ApiKeyService(
keys_env_prefix=keys_env_prefix,
header_name=header_name,
- hashed=hashed
+ hashed=hashed,
+ keys=keys,
)
DIContainer.get_instance().register_value(ApiKeyService, service)
return cls
diff --git a/nitrostack/auth/cimd.py b/nitrostack/auth/cimd.py
index f9aa7a3..a0e7659 100644
--- a/nitrostack/auth/cimd.py
+++ b/nitrostack/auth/cimd.py
@@ -59,8 +59,15 @@ class CimdFetchError(ValueError):
def validate_client_identifier_url(client_id_url: str, *, allow_loopback: bool = False) -> str:
+ """CIMD identifiers additionally require a non-root document path."""
+ return validate_fetch_url(client_id_url, allow_loopback=allow_loopback, require_non_root_path=True)
+
+
+def validate_fetch_url(
+ client_id_url: str, *, allow_loopback: bool = False, require_non_root_path: bool = False,
+) -> str:
"""
- Validate a CIMD ``client_id`` URL before any network fetch.
+ Validate a fetch URL, optionally requiring CIMD's non-root document path.
Returns the normalized URL string on success.
"""
@@ -85,10 +92,10 @@ def validate_client_identifier_url(client_id_url: str, *, allow_loopback: bool =
raise CimdValidationError("client_id URL must not contain a fragment")
path = parsed.path or ""
- if not path or path == "/":
+ if require_non_root_path and (not path or path == "/"):
raise CimdValidationError("client_id URL must include a non-root path")
- segments = [segment for segment in path.split("/") if segment]
+ segments = [segment for segment in urllib.parse.unquote(path).split("/") if segment]
if any(segment in {".", ".."} for segment in segments):
raise CimdValidationError("client_id URL path must not contain '.' or '..' segments")
@@ -125,16 +132,10 @@ def _pick_pinned_ip(resolved_ips: set[str]) -> str:
def cimd_peer_is_acceptable(peer: str, pinned_ip: str) -> bool:
- """Require the direct socket peer to match the pinned IP.
-
- A configured trusted proxy hop is the only exception; untrusted peers
- cannot stand in for the destination.
- """
+ """Require the direct socket peer to match the pinned IP."""
if peer == pinned_ip:
return not is_blocked_ip(peer)
- from nitrostack.transports.proxy import peer_is_trusted
-
- return peer_is_trusted(peer)
+ return False
def request_host_for_cimd(
@@ -160,9 +161,11 @@ def cimd_host_matches_request(
return cimd_url_matches_request_host(cimd_url, headers, peer, trusted=trusted)
-async def assert_safe_fetch_target(url_str: str, *, allow_loopback: bool = False) -> Optional[str]:
+async def assert_safe_fetch_target(
+ url_str: str, *, allow_loopback: bool = False, require_non_root_path: bool = True,
+) -> Optional[str]:
"""DNS pre-resolution and IP range filtering. Returns the pinned destination IP."""
- validate_client_identifier_url(url_str, allow_loopback=allow_loopback)
+ validate_fetch_url(url_str, allow_loopback=allow_loopback, require_non_root_path=require_non_root_path)
parsed = urllib.parse.urlparse(url_str)
hostname = parsed.hostname
if not hostname:
@@ -222,27 +225,29 @@ def connect(self) -> None:
class _PinnedHTTPHandler(urllib.request.HTTPHandler):
- def __init__(self, hostname: str, pinned_ip: str) -> None:
+ def __init__(self, hostname: str, pinned_ip: str, port: Optional[int] = None) -> None:
super().__init__()
self._hostname = hostname
self._pinned_ip = pinned_ip
+ self._port = port
def http_open(self, req: urllib.request.Request):
return self.do_open(
- lambda host, **kwargs: _PinnedHTTPConnection(self._hostname, self._pinned_ip, **kwargs),
+ lambda host, **kwargs: _PinnedHTTPConnection(self._hostname, self._pinned_ip, port=self._port, **kwargs),
req,
)
class _PinnedHTTPSHandler(urllib.request.HTTPSHandler):
- def __init__(self, hostname: str, pinned_ip: str) -> None:
+ def __init__(self, hostname: str, pinned_ip: str, port: Optional[int] = None) -> None:
super().__init__()
self._hostname = hostname
self._pinned_ip = pinned_ip
+ self._port = port
def https_open(self, req: urllib.request.Request):
return self.do_open(
- lambda host, **kwargs: _PinnedHTTPSConnection(self._hostname, self._pinned_ip, **kwargs),
+ lambda host, **kwargs: _PinnedHTTPSConnection(self._hostname, self._pinned_ip, port=self._port, **kwargs),
req,
)
@@ -258,22 +263,24 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001
)
+def _build_fetch_opener(url_str: str, pinned_ip: Optional[str] = None):
+ """Share redirect denial and DNS-pinned, hostname-verified connections."""
+ parsed = urllib.parse.urlparse(url_str)
+ handlers: list[urllib.request.BaseHandler] = [_NoRedirectHandler()]
+ if pinned_ip and parsed.hostname:
+ handlers.append(urllib.request.ProxyHandler({}))
+ handler = _PinnedHTTPHandler if parsed.scheme == "http" else _PinnedHTTPSHandler
+ handlers.append(handler(parsed.hostname, pinned_ip, parsed.port))
+ return urllib.request.build_opener(*handlers)
+
+
def _fetch_cimd_bytes(
url_str: str,
*,
timeout_sec: float,
pinned_ip: Optional[str] = None,
) -> bytes:
- parsed = urllib.parse.urlparse(url_str)
- hostname = parsed.hostname
- handlers: list[urllib.request.BaseHandler] = [_NoRedirectHandler()]
- if pinned_ip and hostname:
- if (parsed.scheme or "").lower() == "http":
- handlers.append(_PinnedHTTPHandler(hostname, pinned_ip))
- else:
- handlers.append(_PinnedHTTPSHandler(hostname, pinned_ip))
-
- opener = urllib.request.build_opener(*handlers)
+ opener = _build_fetch_opener(url_str, pinned_ip)
request = urllib.request.Request(url_str, headers={"Accept": "application/json"}, method="GET")
try:
@@ -369,24 +376,3 @@ def resolve_cimd_sync(
resolve_cimd(client_id_url, allow_loopback=allow_loopback, timeout_sec=timeout_sec)
)
raise CimdFetchError("CIMD resolution cannot run nested on a running event loop")
-
-
-def looks_like_cimd_url(value: Any) -> bool:
- """Return True when ``value`` is an http(s) client identifier URL."""
- return isinstance(value, str) and value.startswith(("https://", "http://"))
-
-
-def resolve_cimd_sync(
- client_id_url: str,
- *,
- allow_loopback: bool = False,
- timeout_sec: float = CIMD_FETCH_TIMEOUT_SEC,
-) -> dict[str, Any]:
- """Synchronous wrapper for registration / other non-async callers."""
- try:
- asyncio.get_running_loop()
- except RuntimeError:
- return asyncio.run(
- resolve_cimd(client_id_url, allow_loopback=allow_loopback, timeout_sec=timeout_sec)
- )
- raise CimdFetchError("CIMD resolution cannot run nested on a running event loop")
diff --git a/nitrostack/auth/client.py b/nitrostack/auth/client.py
new file mode 100644
index 0000000..d458f55
--- /dev/null
+++ b/nitrostack/auth/client.py
@@ -0,0 +1,418 @@
+"""Reusable OAuth client, adapted from PR #4 with managed, secret-safe tokens."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+import math
+import re
+import secrets
+import urllib.error
+import urllib.parse
+import urllib.request
+import weakref
+from dataclasses import fields
+from typing import Any, Mapping
+
+from nitrostack.auth import cimd
+# Re-export the original import locations for callers and transport test seams.
+from nitrostack.auth._client_types import (
+ AuthorizationFlow, ClientRegistration, OAuth2ClientConfig, OAuthClientError,
+ _Request, _Response,
+)
+from nitrostack.auth.secret import unwrap_secret
+from nitrostack.auth.pkce import generate_pkce_params, is_valid_code_verifier, validate_pkce_support
+from nitrostack.auth.token_store import (
+ MemoryTokenStore, StoredToken, TokenStore, is_token_expired, token_response_to_stored,
+)
+
+
+def get_well_known_metadata_uris(resource_url: str) -> list[str]:
+ parsed = urllib.parse.urlsplit(resource_url)
+ origin = f"{parsed.scheme}://{parsed.netloc}"
+ urls = []
+ if parsed.path and parsed.path != "/":
+ urls.append(f"{origin}/.well-known/oauth-protected-resource{parsed.path}")
+ return list(dict.fromkeys([*urls, f"{origin}/.well-known/oauth-protected-resource"]))
+
+
+def parse_www_authenticate_header(value: str) -> dict[str, str] | None:
+ match = re.search(r"(?:^|,)\s*Bearer\s+", value, re.IGNORECASE)
+ if not match:
+ return None
+ result = {"scheme": "Bearer"}
+ for item in re.finditer(r'([\w-]+)\s*=\s*(?:"((?:\\.|[^"\\])*)"|([^,\s]+))', value[match.end():]):
+ text = item.group(2) if item.group(2) is not None else item.group(3)
+ result[item.group(1).lower()] = re.sub(r"\\(.)", r"\1", text)
+ return result
+
+
+class OAuth2Client:
+ """One configured OAuth client; share it to coalesce refreshes per token key.
+
+ Store keys must distinguish provider, client, principal, and resource. This
+ client never launches a browser or listens for authorization callbacks.
+ """
+
+ def __init__(
+ self, config: OAuth2ClientConfig | Mapping[str, Any], *, store: TokenStore | None = None,
+ timeout_seconds: float = 10, max_response_bytes: int = 1024 * 1024,
+ ):
+ try:
+ self.config = config if isinstance(config, OAuth2ClientConfig) else OAuth2ClientConfig(**dict(config))
+ except (TypeError, ValueError):
+ raise OAuthClientError("configuration") from None
+ try:
+ valid_timeout = (not isinstance(timeout_seconds, bool) and isinstance(timeout_seconds, (int, float))
+ and math.isfinite(timeout_seconds) and timeout_seconds > 0)
+ except OverflowError:
+ valid_timeout = False
+ if not valid_timeout:
+ raise OAuthClientError("configuration")
+ if type(max_response_bytes) is not int or max_response_bytes <= 0:
+ raise OAuthClientError("configuration")
+ self.store = MemoryTokenStore() if store is None else store
+ self.timeout_seconds = timeout_seconds
+ self.max_response_bytes = max_response_bytes
+ self._metadata: dict[str, Any] = {}
+ self._refresh_tasks: dict[str, asyncio.Task[StoredToken]] = {}
+ self._force_refresh: dict[str, bool] = {}
+ self._key_locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
+ self._trusted_urls = {
+ value for item in fields(self.config)
+ if item.name.endswith(("endpoint", "metadata_url")) or item.name == "issuer"
+ if (value := getattr(self.config, item.name)) is not None
+ }
+ for url in self._trusted_urls:
+ self._validate_url(url)
+
+ def _validate_url(self, url: str) -> None:
+ try:
+ if not isinstance(url, str) or url != url.strip():
+ raise ValueError()
+ cimd.validate_fetch_url(url, allow_loopback=url in self._trusted_urls)
+ # Trigger port validation before urllib or socket sees malformed input.
+ urllib.parse.urlsplit(url).port
+ except (TypeError, ValueError):
+ raise OAuthClientError("endpoint validation") from None
+
+ def _endpoint(self, name: str) -> str:
+ value = getattr(self.config, name) or self._metadata.get(name)
+ if not value:
+ raise OAuthClientError("endpoint configuration")
+ self._validate_url(value)
+ return value
+
+ async def _send(self, request: _Request) -> _Response:
+ """Internal async transport seam; tests replace it without real network IO."""
+ return await asyncio.to_thread(self._send_sync, request)
+
+ def _send_sync(self, request: _Request) -> _Response:
+ opener = cimd._build_fetch_opener(request.url, request.pinned_ip)
+ outgoing = urllib.request.Request(request.url, data=request.body,
+ headers=dict(request.headers), method=request.method)
+ try:
+ response = opener.open(outgoing, timeout=request.timeout)
+ except urllib.error.HTTPError as exc:
+ response = exc
+ with response:
+ length = response.headers.get("Content-Length")
+ if length is not None and not 0 <= int(length) <= self.max_response_bytes:
+ raise OAuthClientError("response size")
+ body = response.read(self.max_response_bytes + 1)
+ if len(body) > self.max_response_bytes:
+ raise OAuthClientError("response size")
+ return _Response(response.code, dict(response.headers), body)
+
+ async def _request(
+ self, operation: str, method: str, url: str, *, body: bytes | None = None,
+ headers: Mapping[str, str] | None = None, allowed_statuses: tuple[int, ...] = (),
+ ) -> _Response:
+ try:
+ self._validate_url(url)
+ pinned_ip = None
+ if url not in self._trusted_urls:
+ pinned_ip = await cimd.assert_safe_fetch_target(url, require_non_root_path=False)
+ if not pinned_ip:
+ raise OAuthClientError("endpoint validation")
+ response = await self._send(_Request(
+ method, url, {"Accept": "application/json", **(headers or {})}, body,
+ self.timeout_seconds, pinned_ip,
+ ))
+ if len(response.body) > self.max_response_bytes:
+ raise OAuthClientError("response size")
+ except OAuthClientError:
+ raise
+ except Exception:
+ raise OAuthClientError(operation) from None
+ if not (200 <= response.status < 300 or response.status in allowed_statuses):
+ error_code = None
+ try:
+ error_code = json.loads(response.body).get("error")
+ except (ValueError, AttributeError, TypeError):
+ pass
+ raise OAuthClientError(operation, status=response.status, error_code=error_code)
+ return response
+
+ @staticmethod
+ def _json(response: _Response, operation: str) -> dict[str, Any]:
+ try:
+ result = json.loads(response.body)
+ if not isinstance(result, dict):
+ raise ValueError()
+ return result
+ except (ValueError, TypeError, UnicodeError):
+ raise OAuthClientError(operation) from None
+
+ async def discover_protected_resource_metadata(
+ self, resource_url: str, *, www_authenticate_header: str | None = None,
+ ) -> dict[str, Any]:
+ self._validate_url(resource_url)
+ configured = self.config.protected_resource_metadata_url
+ if configured:
+ candidates = [configured]
+ else:
+ if www_authenticate_header is None:
+ try:
+ response = await self._request("resource discovery", "GET", resource_url,
+ allowed_statuses=(401,))
+ www_authenticate_header = next((value for key, value in response.headers.items()
+ if key.lower() == "www-authenticate"), "")
+ except OAuthClientError:
+ www_authenticate_header = ""
+ challenge = parse_www_authenticate_header(www_authenticate_header or "") or {}
+ candidates = list(dict.fromkeys([
+ *([challenge["resource_metadata"]] if challenge.get("resource_metadata") else []),
+ *get_well_known_metadata_uris(resource_url),
+ ]))
+ for url in candidates:
+ try:
+ metadata = self._json(await self._request("resource discovery", "GET", url), "resource metadata")
+ if metadata.get("resource") != resource_url:
+ raise OAuthClientError("resource metadata")
+ servers = metadata.get("authorization_servers")
+ if not isinstance(servers, list) or not servers:
+ raise OAuthClientError("resource metadata")
+ for issuer in servers:
+ self._validate_url(issuer)
+ return metadata
+ except OAuthClientError:
+ continue
+ raise OAuthClientError("resource discovery")
+
+ async def discover_authorization_server_metadata(self, issuer: str | None = None) -> dict[str, Any]:
+ issuer = issuer or self.config.issuer
+ self._validate_url(issuer)
+ parsed = urllib.parse.urlsplit(issuer)
+ if parsed.query:
+ raise OAuthClientError("issuer validation")
+ origin = f"{parsed.scheme}://{parsed.netloc}"
+ path = parsed.path.rstrip("/")
+ configured = self.config.authorization_server_metadata_url
+ candidates = [configured] if configured else list(dict.fromkeys([
+ f"{origin}/.well-known/oauth-authorization-server{path}",
+ f"{origin}/.well-known/openid-configuration{path}",
+ f"{issuer.rstrip('/')}/.well-known/openid-configuration",
+ ]))
+ for url in candidates:
+ try:
+ metadata = self._json(await self._request("authorization discovery", "GET", url), "authorization metadata")
+ if metadata.get("issuer") != issuer or not metadata.get("token_endpoint"):
+ raise OAuthClientError("authorization metadata")
+ for name in ("authorization_endpoint", "token_endpoint", "registration_endpoint", "revocation_endpoint"):
+ if name in metadata:
+ self._validate_url(metadata[name])
+ self._metadata = dict(metadata)
+ return dict(metadata)
+ except OAuthClientError:
+ continue
+ raise OAuthClientError("authorization discovery")
+
+ def _client_id(self) -> str:
+ if not self.config.client_id:
+ raise OAuthClientError("client configuration")
+ return self.config.client_id
+
+ def _key_lock(self, key: str) -> asyncio.Lock:
+ if not isinstance(key, str) or not key:
+ raise OAuthClientError("token key")
+ lock = self._key_locks.get(key)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._key_locks[key] = lock
+ return lock
+
+ async def start_authorization_flow(
+ self, *, scope: str | None = None, state: str | None = None,
+ resource: str | None = None, redirect_uri: str | None = None,
+ ) -> AuthorizationFlow:
+ redirect_uri = redirect_uri or self.config.redirect_uri
+ if not redirect_uri or (state is not None and (not isinstance(state, str) or not state)):
+ raise OAuthClientError("authorization configuration")
+ if self._metadata and not validate_pkce_support(self._metadata.get("code_challenge_methods_supported")):
+ raise OAuthClientError("PKCE support")
+ pkce = generate_pkce_params("S256")
+ state = secrets.token_urlsafe(32) if state is None else state
+ params = {"response_type": "code", "client_id": self._client_id(), "redirect_uri": redirect_uri,
+ "state": state, "code_challenge": pkce["code_challenge"], "code_challenge_method": "S256"}
+ if scope is not None:
+ params["scope"] = scope
+ if resource is not None:
+ params["resource"] = resource
+ endpoint = urllib.parse.urlsplit(self._endpoint("authorization_endpoint"))
+ reserved = {"response_type", "client_id", "redirect_uri", "state", "code_challenge",
+ "code_challenge_method", "scope", "resource"}
+ query = [(key, value) for key, value in urllib.parse.parse_qsl(endpoint.query, keep_blank_values=True)
+ if key not in reserved]
+ authorization_url = urllib.parse.urlunsplit(endpoint._replace(query=urllib.parse.urlencode([*query, *params.items()])))
+ return AuthorizationFlow(authorization_url, state, pkce["code_verifier"], pkce["code_challenge"])
+
+ def _authenticate(self, params: dict[str, Any]) -> dict[str, str]:
+ params["client_id"] = self._client_id()
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+ if self.config.client_secret is not None:
+ try:
+ secret = unwrap_secret(self.config.client_secret)
+ if not secret:
+ raise ValueError
+ except Exception:
+ raise OAuthClientError("client authentication") from None
+ credentials = ":".join(urllib.parse.quote_plus(value, safe="") for value in
+ (self._client_id(), secret))
+ headers["Authorization"] = "Basic " + base64.b64encode(credentials.encode("ascii")).decode("ascii")
+ return headers
+
+ async def _obtain_token(self, key, params, *, resource=None, previous=None):
+ if not isinstance(key, str) or not key:
+ raise OAuthClientError("token key")
+ headers = self._authenticate(params)
+ if resource is not None:
+ params["resource"] = resource
+ response = await self._request("token request", "POST", self._endpoint("token_endpoint"),
+ body=urllib.parse.urlencode(params).encode("utf-8"), headers=headers)
+ try:
+ token = token_response_to_stored(self._json(response, "token response"), resource, previous=previous)
+ await self.store.save_token(key, token)
+ except Exception:
+ raise OAuthClientError("token persistence or response") from None
+ return token
+
+ async def exchange_code_for_token(
+ self, key: str, *, code: str, code_verifier: str,
+ redirect_uri: str | None = None, resource: str | None = None,
+ ) -> StoredToken:
+ redirect_uri = redirect_uri or self.config.redirect_uri
+ if (not isinstance(code, str) or not code or not isinstance(code_verifier, str)
+ or not is_valid_code_verifier(code_verifier) or not redirect_uri):
+ raise OAuthClientError("code exchange configuration")
+ async with self._key_lock(key):
+ return await self._obtain_token(key, {"grant_type": "authorization_code", "code": code,
+ "code_verifier": code_verifier, "redirect_uri": redirect_uri}, resource=resource)
+
+ async def get_client_credentials_token(
+ self, key: str, *, scope: str | None = None, resource: str | None = None,
+ ) -> StoredToken:
+ if not self.config.client_secret:
+ raise OAuthClientError("client credentials configuration")
+ params = {"grant_type": "client_credentials"}
+ if scope is not None:
+ params["scope"] = scope
+ async with self._key_lock(key):
+ return await self._obtain_token(key, params, resource=resource)
+
+ async def _refresh(self, key: str, *, only_if_expired: bool = False) -> StoredToken:
+ async with self._key_lock(key):
+ return await self._refresh_locked(key, only_if_expired=only_if_expired)
+
+ async def _refresh_locked(self, key: str, *, only_if_expired: bool = False) -> StoredToken:
+ try:
+ previous = await self.store.get_token(key)
+ except Exception:
+ raise OAuthClientError("token retrieval") from None
+ if (only_if_expired and not self._force_refresh.get(key, False)
+ and previous is not None and not is_token_expired(previous)):
+ return previous
+ if previous is None or not previous.refresh_token:
+ raise OAuthClientError("refresh credential")
+ params = {"grant_type": "refresh_token", "refresh_token": previous.refresh_token}
+ if previous.scope is not None:
+ params["scope"] = previous.scope
+ return await self._obtain_token(key, params, resource=previous.resource, previous=previous)
+
+ async def get_access_token(self, key: str) -> str:
+ """Return a usable access token, refreshing and persisting when necessary."""
+ token = await self._coalesced_refresh(key, only_if_expired=True)
+ if is_token_expired(token):
+ raise OAuthClientError("access token expiry")
+ return token.access_token
+
+ async def refresh_token(self, key: str) -> StoredToken:
+ return await self._coalesced_refresh(key)
+
+ async def _coalesced_refresh(self, key: str, *, only_if_expired: bool = False) -> StoredToken:
+ if not isinstance(key, str) or not key:
+ raise OAuthClientError("token key")
+ task = self._refresh_tasks.get(key)
+ if task is None or task.done():
+ self._force_refresh[key] = not only_if_expired
+ task = asyncio.create_task(self._refresh(key, only_if_expired=only_if_expired))
+ self._refresh_tasks[key] = task
+
+ def completed(done):
+ if self._refresh_tasks.get(key) is done:
+ self._refresh_tasks.pop(key, None)
+ self._force_refresh.pop(key, None)
+ if not done.cancelled():
+ done.exception() # Consume failures even if every waiter cancelled.
+
+ task.add_done_callback(completed)
+ elif not only_if_expired:
+ self._force_refresh[key] = True
+ return await asyncio.shield(task)
+
+ async def revoke_token(
+ self, key: str, *, token_type_hint: str | None = None, local_fallback: bool = False,
+ ) -> None:
+ """Revoke remotely; opt in to local deletion if remote revocation fails."""
+ if type(local_fallback) is not bool:
+ raise OAuthClientError("revocation configuration")
+ async with self._key_lock(key):
+ await self._revoke_locked(key, token_type_hint, local_fallback)
+
+ async def _revoke_locked(self, key: str, token_type_hint: str | None, local_fallback: bool) -> None:
+ try:
+ stored = await self.store.get_token(key)
+ if stored is None:
+ return
+ hint = token_type_hint if token_type_hint is not None else (
+ "refresh_token" if stored.refresh_token else "access_token"
+ )
+ if hint not in ("access_token", "refresh_token") or not getattr(stored, hint):
+ raise OAuthClientError("revocation configuration")
+ params = {"token": getattr(stored, hint), "token_type_hint": hint}
+ try:
+ headers = self._authenticate(params)
+ await self._request("revocation", "POST", self._endpoint("revocation_endpoint"),
+ body=urllib.parse.urlencode(params).encode("utf-8"), headers=headers)
+ except OAuthClientError:
+ if not local_fallback:
+ raise
+ await self.store.delete_token(key)
+ except OAuthClientError:
+ raise
+ except Exception:
+ raise OAuthClientError("revocation persistence") from None
+
+ async def register_client(self, metadata: Mapping[str, Any]) -> ClientRegistration:
+ try:
+ body = json.dumps(dict(metadata)).encode("utf-8")
+ except Exception:
+ raise OAuthClientError("registration configuration") from None
+ response = await self._request("registration", "POST", self._endpoint("registration_endpoint"),
+ body=body, headers={"Content-Type": "application/json"})
+ result = self._json(response, "registration response")
+ try:
+ return ClientRegistration(result["client_id"], result.get("client_secret"), result)
+ except (KeyError, TypeError, ValueError):
+ raise OAuthClientError("registration response") from None
diff --git a/nitrostack/auth/config.py b/nitrostack/auth/config.py
index 7b4cd4c..a124578 100644
--- a/nitrostack/auth/config.py
+++ b/nitrostack/auth/config.py
@@ -2,6 +2,7 @@
from typing import Dict, Any, Callable, Optional
from nitrostack.core.module import module
from nitrostack.core.di import DIContainer, injectable
+from nitrostack.auth.secret import SecretValue
@injectable()
class ConfigService:
@@ -12,6 +13,8 @@ def __init__(
defaults: Optional[Dict[str, Any]] = None,
validate_fn: Optional[Callable[[Dict[str, Any]], bool]] = None,
):
+ # ``defaults`` values may be SecretValue instances. They are kept as they are, so
+ # printing the config or calling ``get()`` never shows the raw secret.
self._config: Dict[str, Any] = {}
if defaults:
self._config.update(defaults)
@@ -57,6 +60,25 @@ def get_or_throw(self, key: str) -> Any:
raise KeyError(f"Configuration key '{key}' is required but not found.")
return self._config[key]
+ def get_secret(self, key: str, default: Optional[SecretValue] = None) -> Optional[SecretValue]:
+ """Return a configuration value as a ``SecretValue`` (or ``default`` when missing).
+
+ A value that is already a ``SecretValue`` is returned as it is. A plain string is
+ wrapped, so callers can pass it on without it being printed by accident.
+ """
+ value = self._config.get(key)
+ if value is None or value == "":
+ return default
+ if isinstance(value, SecretValue):
+ return value
+ return SecretValue(str(value), source="config")
+
+ def get_secret_or_throw(self, key: str) -> SecretValue:
+ secret = self.get_secret(key)
+ if secret is None:
+ raise KeyError(f"Configuration key '{key}' is required but not found.")
+ return secret
+
@module(name="ConfigModule")
class ConfigModule:
@classmethod
diff --git a/nitrostack/auth/jwt.py b/nitrostack/auth/jwt.py
index 19bd0c7..84c9c5b 100644
--- a/nitrostack/auth/jwt.py
+++ b/nitrostack/auth/jwt.py
@@ -4,9 +4,10 @@
import hashlib
import base64
import os
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Optional, Union
from nitrostack.core.module import module
from nitrostack.core.di import DIContainer
+from nitrostack.auth.secret import SecretValue, unwrap_secret
class JWTService:
def __init__(
@@ -15,13 +16,18 @@ def __init__(
expires_in: str = "24h",
audience: Optional[str] = None,
issuer: Optional[str] = None,
+ secret: Union[SecretValue, str, None] = None,
):
self.secret_env_var = secret_env_var
+ # An explicit secret wins over the environment variable. Prefer a SecretValue.
+ self._secret = secret
self.expires_in = expires_in
self.audience = audience
self.issuer = issuer
def get_secret(self) -> str:
+ if self._secret is not None:
+ return unwrap_secret(self._secret)
secret = os.environ.get(self.secret_env_var)
if not secret:
# Fallback for dev mode/testing so it doesn't fail hard if not set
@@ -116,12 +122,14 @@ def for_root(
expires_in: str = "24h",
audience: Optional[str] = None,
issuer: Optional[str] = None,
+ secret: Union[SecretValue, str, None] = None,
):
service = JWTService(
secret_env_var=secret_env_var,
expires_in=expires_in,
audience=audience,
- issuer=issuer
+ issuer=issuer,
+ secret=secret,
)
DIContainer.get_instance().register_value(JWTService, service)
return cls
diff --git a/nitrostack/auth/oauth.py b/nitrostack/auth/oauth.py
index b6b3358..0865349 100644
--- a/nitrostack/auth/oauth.py
+++ b/nitrostack/auth/oauth.py
@@ -1,56 +1,54 @@
import os
import sys
-import time
-import json
-import urllib.request
-import urllib.parse
-from typing import List, Optional, Dict, Any, Tuple
-from http.server import HTTPServer, BaseHTTPRequestHandler
+import urllib.parse # noqa: F401 (kept: callers patch nitrostack.auth.oauth.urllib.request)
+import urllib.request # noqa: F401
+from typing import List, Optional, Dict, Any, Tuple, Union
+from http.server import HTTPServer
import threading
from nitrostack.core.module import module
from nitrostack.core.di import DIContainer
-from nitrostack.auth.oauth_module import (
+from nitrostack.auth.secret import SecretValue
+from nitrostack.auth.oauth_types import (
+ TokenInfo,
+ _has_secret,
+ generate_www_authenticate_header,
+ is_oauth_required,
+)
+from nitrostack.auth.oauth_cache import cache_get, cache_set
+from nitrostack.auth.oauth_tokens import (
+ get_jwks_client,
+ introspect_via_endpoint,
+ introspect_via_jwks,
+ validate_audience,
+)
+from nitrostack.auth.oauth_discovery import start_discovery_server
+# Re-exported only so existing ``from nitrostack.auth.oauth import ...`` lines keep working.
+from nitrostack.auth.secret import unwrap_secret # noqa: F401
+from nitrostack.auth.cimd import CimdFetchError, CimdValidationError # noqa: F401
+from nitrostack.auth.oauth_module import ( # noqa: F401
apply_cimd_to_registration_body,
build_authorization_server_metadata,
build_protected_resource_metadata,
build_registration_response,
is_client_registration_enabled,
)
-from nitrostack.auth.cimd import CimdFetchError, CimdValidationError
from nitrostack.core.errors import AudienceMismatchError, ConfigurationError, TokenInactiveError
-
-def is_oauth_required() -> bool:
- """TS ``OAuthModule.isAuthRequired()`` — Studio/local default is off.
-
- Set ``OAUTH_REQUIRED=true`` to enforce Bearer tokens. Unset/false lets
- NitroStudio and Inspector call tools against mock Duffel data.
- """
- return (os.environ.get("OAUTH_REQUIRED") or "").strip().lower() == "true"
-
+# Everything that used to live in this module is still importable from it. The
+# implementation is split by responsibility: oauth_types (helpers), oauth_cache,
+# oauth_tokens (validation), oauth_discovery (metadata server). This module keeps
+# OAuthService, OAuthModule and the fail-open warning state.
+__all__ = [
+ "OAuthModule",
+ "OAuthService",
+ "generate_www_authenticate_header",
+ "is_oauth_required",
+ "warn_if_oauth_fail_open",
+]
_oauth_fail_open_warned = False
-def generate_www_authenticate_header(
- *,
- realm: str = "mcp",
- resource_metadata: Optional[str] = None,
- error: Optional[str] = None,
- error_description: Optional[str] = None,
-) -> str:
- """RFC 6750 / RFC 9728 WWW-Authenticate value for protected MCP resources."""
- parts = [f'Bearer realm="{realm}"']
- if resource_metadata:
- parts.append(f'resource_metadata="{resource_metadata}"')
- if error:
- parts.append(f'error="{error}"')
- if error_description:
- escaped = error_description.replace('"', "'")
- parts.append(f'error_description="{escaped}"')
- return ", ".join(parts)
-
-
def warn_if_oauth_fail_open() -> None:
"""Loud warning when OAuth is wired but tokens are not enforced."""
global _oauth_fail_open_warned
@@ -64,6 +62,7 @@ def warn_if_oauth_fail_open() -> None:
)
sys.stderr.flush()
+
class OAuthService:
def __init__(
self,
@@ -72,7 +71,7 @@ def __init__(
scopes_supported: List[str],
token_introspection_endpoint: Optional[str] = None,
token_introspection_client_id: Optional[str] = None,
- token_introspection_client_secret: Optional[str] = None,
+ token_introspection_client_secret: Union[SecretValue, str, None] = None,
discovery_port: int = 3005,
jwks_uri: Optional[str] = None,
audience: Optional[str] = None,
@@ -80,12 +79,37 @@ def __init__(
token_cache_seconds: Optional[int] = None,
enable_client_registration: Optional[bool] = None,
static_client_id: Optional[str] = None,
- static_client_secret: Optional[str] = None,
+ static_client_secret: Union[SecretValue, str, None] = None,
+ discovery_auto_retry: Optional[bool] = None,
+ discovery_max_retries: Optional[int] = None,
):
self.resource_uri = resource_uri
self.authorization_servers = authorization_servers
self.scopes_supported = scopes_supported
self.discovery_port = discovery_port
+ if discovery_auto_retry is not None:
+ self.discovery_auto_retry = discovery_auto_retry
+ else:
+ env_retry = os.environ.get("OAUTH_DISCOVERY_AUTO_RETRY")
+ self.discovery_auto_retry = (
+ env_retry.strip().lower() not in ("false", "0", "no", "off")
+ if env_retry is not None
+ else True
+ )
+
+ if discovery_max_retries is not None:
+ self.discovery_max_retries = discovery_max_retries
+ else:
+ raw_max_retries = os.environ.get("OAUTH_DISCOVERY_MAX_RETRIES")
+ if raw_max_retries is not None:
+ try:
+ self.discovery_max_retries = int(raw_max_retries)
+ except ValueError:
+ self.discovery_max_retries = 50
+ else:
+ self.discovery_max_retries = 50
+
+ self.bound_port: Optional[int] = None
# Introspection settings fall back to the environment when not passed
# explicitly. Both spellings of the endpoint variable are accepted: the
@@ -105,7 +129,9 @@ def __init__(
token_introspection_client_id or os.environ.get("INTROSPECTION_CLIENT_ID")
)
self.token_introspection_client_secret = (
- token_introspection_client_secret or os.environ.get("INTROSPECTION_CLIENT_SECRET")
+ token_introspection_client_secret
+ if _has_secret(token_introspection_client_secret)
+ else os.environ.get("INTROSPECTION_CLIENT_SECRET")
)
# Environmental fallbacks
@@ -126,7 +152,11 @@ def __init__(
else os.environ.get("OAUTH_ENABLE_CLIENT_REGISTRATION", "").lower() == "true"
)
self.static_client_id = static_client_id or os.environ.get("OAUTH_CLIENT_ID")
- self.static_client_secret = static_client_secret or os.environ.get("OAUTH_CLIENT_SECRET")
+ self.static_client_secret = (
+ static_client_secret
+ if _has_secret(static_client_secret)
+ else os.environ.get("OAUTH_CLIENT_SECRET")
+ )
# Caches: JWKS client objects (keyed by jwks_uri — PyJWKClient already does its
# own internal signing-key caching, this just avoids reconstructing the client
@@ -140,143 +170,11 @@ def __init__(
def start_discovery_server(self) -> None:
"""Starts a background HTTP discovery server for OAuth Protected Resource metadata."""
- if self._server is not None:
- return
-
- service_instance = self
- registration_path = "/oauth/v2/register"
-
- def _write_json(handler: BaseHTTPRequestHandler, status: int, payload: Dict[str, Any]) -> None:
- raw = json.dumps(payload).encode("utf-8")
- handler.send_response(status)
- handler.send_header("Content-Type", "application/json")
- handler.send_header("Content-Length", str(len(raw)))
- handler.send_header("Connection", "close")
- handler.end_headers()
- handler.wfile.write(raw)
-
- def _write_empty(handler: BaseHTTPRequestHandler, status: int) -> None:
- handler.send_response(status)
- handler.send_header("Content-Length", "0")
- handler.send_header("Connection", "close")
- handler.end_headers()
-
- class DiscoveryHandler(BaseHTTPRequestHandler):
- def log_message(self, format, *args):
- # Suppress server logging to stdout/stderr to keep stdio clean
- pass
-
- def do_OPTIONS(self):
- # TS discovery handlers honor CORS preflight without leaking credentials.
- self.send_response(200)
- self.send_header("Access-Control-Allow-Origin", "*")
- self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
- self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
- self.send_header("Content-Length", "0")
- self.send_header("Connection", "close")
- self.end_headers()
-
- def _proxy_headers(self) -> Dict[str, str]:
- return {key: value for key, value in self.headers.items()}
-
- def _proxy_peer(self) -> Optional[str]:
- return self.client_address[0] if self.client_address else None
-
- def _trusted_public_origin(self) -> Optional[str]:
- from nitrostack.transports.proxy import public_origin, trusted_forwarded_host
-
- headers = self._proxy_headers()
- peer = self._proxy_peer()
- if not trusted_forwarded_host(headers, peer):
- return None
- return public_origin(
- headers,
- peer,
- fallback_host=f"localhost:{service_instance.discovery_port}",
- fallback_proto="http",
- )
-
- def do_GET(self):
- if self.path == "/.well-known/oauth-protected-resource":
- _write_json(self, 200, build_protected_resource_metadata(service_instance))
- elif self.path == "/.well-known/oauth-authorization-server":
- origin = self._trusted_public_origin()
- registration_endpoint = (
- registration_path if is_client_registration_enabled(service_instance) else None
- )
- _write_json(
- self,
- 200,
- build_authorization_server_metadata(
- service_instance,
- registration_endpoint,
- public_origin=origin,
- ),
- )
- else:
- _write_empty(self, 404)
-
- def do_POST(self):
- if self.path != registration_path:
- _write_empty(self, 404)
- return
-
- if not is_client_registration_enabled(service_instance):
- _write_json(
- self,
- 404,
- {"error": "not_found", "error_description": "Client registration is not enabled"},
- )
- return
-
- length = int(self.headers.get("Content-Length", 0))
- raw_body = self.rfile.read(length) if length else b""
- try:
- body = json.loads(raw_body.decode("utf-8")) if raw_body else {}
- except Exception:
- body = {}
+ start_discovery_server(self)
- try:
- body = apply_cimd_to_registration_body(
- body,
- headers=self._proxy_headers(),
- peer=self._proxy_peer(),
- )
- except (CimdValidationError, CimdFetchError) as exc:
- _write_json(
- self,
- 400,
- {
- "error": "invalid_client_metadata",
- "error_description": str(exc),
- },
- )
- return
-
- _write_json(self, 200, build_registration_response(service_instance, body))
-
- def run_server():
- # Try binding to OAUTH_DISCOVERY_PORT
- port = int(os.environ.get("OAUTH_DISCOVERY_PORT", self.discovery_port))
- try:
- self._server = HTTPServer(("localhost", port), DiscoveryHandler)
- # Notify client via stderr
- oauth_metadata = {
- "port": port,
- "resource_uri": self.resource_uri,
- "authorization_servers": self.authorization_servers
- }
- sys.stderr.write(
- f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n"
- )
- sys.stderr.flush()
- self._server.serve_forever()
- except Exception as e:
- sys.stderr.write(f"Failed to start OAuth Discovery Server on port {port}: {e}\n")
- sys.stderr.flush()
-
- self._thread = threading.Thread(target=run_server, daemon=True)
- self._thread.start()
+ def get_port(self) -> Optional[int]:
+ """Returns the actual port bound by the discovery server, or None if not running."""
+ return self.bound_port
def raise_if_invalid(self, token_info: Dict[str, Any]) -> Dict[str, Any]:
"""Raise ``TokenInactiveError`` / ``AudienceMismatchError`` for an introspection result."""
@@ -291,10 +189,12 @@ def raise_if_invalid(self, token_info: Dict[str, Any]) -> Dict[str, Any]:
def stop_discovery_server(self) -> None:
if self._server:
self._server.shutdown()
+ self._server.server_close()
self._server = None
if self._thread:
self._thread.join(timeout=1.0)
self._thread = None
+ self.bound_port = None
async def introspect_token(self, token: str) -> Dict[str, Any]:
"""
@@ -338,117 +238,27 @@ async def introspect_token(self, token: str) -> Dict[str, Any]:
def _introspect_via_jwks(self, token: str) -> Dict[str, Any]:
"""JWT signature verification using a cached JWKS client (RFC 7517/7519)."""
- try:
- import jwt
- jwks_client = self._get_jwks_client(self.jwks_uri)
- signing_key = jwks_client.get_signing_key_from_jwt(token)
-
- data = jwt.decode(
- token,
- signing_key.key,
- algorithms=["RS256"],
- audience=self.audience,
- issuer=self.issuer,
- )
- return {
- "active": True,
- "scope": data.get("scope", ""),
- "sub": data.get("sub"),
- "client_id": data.get("client_id"),
- "aud": data.get("aud"),
- "exp": data.get("exp"),
- "iat": data.get("iat"),
- "iss": data.get("iss"),
- }
- except Exception as e:
- sys.stderr.write(f"OAuth JWKS verification failed: {e}\n")
- sys.stderr.flush()
- return {"active": False}
+ return introspect_via_jwks(self, token)
async def _introspect_via_endpoint(self, token: str) -> Dict[str, Any]:
"""RFC 7662 token introspection: POST the token to the authorization server
and ask whether it's active."""
- data = urllib.parse.urlencode({"token": token}).encode("utf-8")
- req = urllib.request.Request(self.token_introspection_endpoint, data=data, method="POST")
- req.add_header("Content-Type", "application/x-www-form-urlencoded")
-
- # Add basic auth if client credentials provided
- if self.token_introspection_client_id and self.token_introspection_client_secret:
- import base64
- auth_str = f"{self.token_introspection_client_id}:{self.token_introspection_client_secret}"
- encoded_auth = base64.b64encode(auth_str.encode("utf-8")).decode("utf-8")
- req.add_header("Authorization", f"Basic {encoded_auth}")
-
- try:
- # urllib.request is synchronous; run it on a thread so it doesn't block
- # the event loop this async method is running on.
- import asyncio
- loop = asyncio.get_event_loop()
-
- def do_request():
- with urllib.request.urlopen(req, timeout=5) as response:
- return json.loads(response.read().decode("utf-8"))
-
- return await loop.run_in_executor(None, do_request)
- except Exception as e:
- sys.stderr.write(f"OAuth Introspection Request Failed: {e}\n")
- sys.stderr.flush()
- return {"active": False}
+ return await introspect_via_endpoint(self, token)
def _get_jwks_client(self, jwks_uri: str):
- """Return a cached PyJWKClient for this URI, creating it on first use.
-
- PyJWKClient already caches individual signing keys internally; this cache
- is one level up — it avoids reconstructing the client object itself (and
- re-fetching the whole key set) on every single token check.
- """
- import jwt
- client = self._jwks_clients.get(jwks_uri)
- if client is None:
- client = jwt.PyJWKClient(jwks_uri)
- self._jwks_clients[jwks_uri] = client
- return client
+ """Return a cached PyJWKClient for this URI, creating it on first use."""
+ return get_jwks_client(self, jwks_uri)
def _validate_audience(self, introspection: Dict[str, Any]) -> bool:
- """
- RFC 8707 resource-indicator check: does this token's `aud` claim include
- the resource it's being presented to? Without this, a token minted for a
- *different* service could be replayed here and accepted — the token is
- legitimately signed/active, just not meant for this resource.
-
- `aud` is legal as either a single string or a list of strings per JWT
- conventions, so it's normalized to a list before comparing.
- """
- expected = self.audience or self.resource_uri
- if not expected:
- # Nothing configured to check against — permissive, matching the
- # TypeScript SDK's default when no audience is configured.
- return True
-
- raw_aud = introspection.get("aud")
- if raw_aud is None:
- # No audience claim on the token at all — nothing to validate against.
- # Treat as permissive rather than rejecting tokens from authorization
- # servers that don't emit `aud`.
- return True
-
- token_audiences = raw_aud if isinstance(raw_aud, list) else [raw_aud]
- return expected in token_audiences
+ """RFC 8707 resource-indicator check on the token's ``aud`` claim."""
+ return validate_audience(self, introspection)
def _cache_get(self, token: str) -> Optional[Dict[str, Any]]:
- cached = self._token_cache.get(token)
- if cached is None:
- return None
- result, expires_at = cached
- if time.monotonic() >= expires_at:
- del self._token_cache[token]
- return None
- return result
+ return cache_get(self._token_cache, token)
def _cache_set(self, token: str, result: Dict[str, Any]) -> None:
- if self.token_cache_seconds <= 0:
- return
- self._token_cache[token] = (result, time.monotonic() + self.token_cache_seconds)
+ cache_set(self._token_cache, token, result, self.token_cache_seconds)
+
@module(name="OAuthModule")
class OAuthModule:
@@ -460,7 +270,7 @@ def for_root(
scopes_supported: List[str],
token_introspection_endpoint: Optional[str] = None,
token_introspection_client_id: Optional[str] = None,
- token_introspection_client_secret: Optional[str] = None,
+ token_introspection_client_secret: Union[SecretValue, str, None] = None,
discovery_port: int = 3005,
jwks_uri: Optional[str] = None,
audience: Optional[str] = None,
@@ -468,7 +278,9 @@ def for_root(
token_cache_seconds: Optional[int] = None,
enable_client_registration: Optional[bool] = None,
static_client_id: Optional[str] = None,
- static_client_secret: Optional[str] = None,
+ static_client_secret: Union[SecretValue, str, None] = None,
+ discovery_auto_retry: Optional[bool] = None,
+ discovery_max_retries: Optional[int] = None,
):
if not resource_uri or not str(resource_uri).strip():
raise ConfigurationError("OAuthModule.for_root requires resource_uri")
@@ -491,6 +303,8 @@ def for_root(
enable_client_registration=enable_client_registration,
static_client_id=static_client_id,
static_client_secret=static_client_secret,
+ discovery_auto_retry=discovery_auto_retry,
+ discovery_max_retries=discovery_max_retries,
)
DIContainer.get_instance().register_value(OAuthService, service)
warn_if_oauth_fail_open()
diff --git a/nitrostack/auth/oauth_cache.py b/nitrostack/auth/oauth_cache.py
new file mode 100644
index 0000000..f8d5981
--- /dev/null
+++ b/nitrostack/auth/oauth_cache.py
@@ -0,0 +1,26 @@
+"""Token-result cache operations. Depends only on ``oauth_types``."""
+
+import time
+from typing import Dict, Optional, Tuple
+
+from nitrostack.auth.oauth_types import TokenInfo
+
+# token -> (introspection result, monotonic expiry)
+TokenCacheStore = Dict[str, Tuple[TokenInfo, float]]
+
+
+def cache_get(store: TokenCacheStore, token: str) -> Optional[TokenInfo]:
+ cached = store.get(token)
+ if cached is None:
+ return None
+ result, expires_at = cached
+ if time.monotonic() >= expires_at:
+ del store[token]
+ return None
+ return result
+
+
+def cache_set(store: TokenCacheStore, token: str, result: TokenInfo, ttl_seconds: int) -> None:
+ if ttl_seconds <= 0:
+ return
+ store[token] = (result, time.monotonic() + ttl_seconds)
diff --git a/nitrostack/auth/oauth_discovery.py b/nitrostack/auth/oauth_discovery.py
new file mode 100644
index 0000000..bbfdb93
--- /dev/null
+++ b/nitrostack/auth/oauth_discovery.py
@@ -0,0 +1,193 @@
+"""Background HTTP discovery server (OAuth protected-resource and authorization-server
+metadata, plus the simplified dynamic client registration endpoint).
+
+Depends on ``oauth_module`` and ``cimd`` for the payloads; it never imports ``oauth``.
+"""
+
+import json
+import os
+import sys
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from typing import TYPE_CHECKING, Any, Dict, Optional
+
+from nitrostack.auth.cimd import CimdFetchError, CimdValidationError
+from nitrostack.auth.oauth_module import (
+ apply_cimd_to_registration_body,
+ build_authorization_server_metadata,
+ build_protected_resource_metadata,
+ build_registration_response,
+ is_client_registration_enabled,
+)
+
+if TYPE_CHECKING:
+ from nitrostack.auth.oauth import OAuthService
+
+
+def start_discovery_server(service: "OAuthService") -> None:
+ """Starts a background HTTP discovery server for OAuth Protected Resource metadata."""
+ if service._server is not None:
+ return
+
+ service_instance = service
+ registration_path = "/oauth/v2/register"
+
+ def _write_json(handler: BaseHTTPRequestHandler, status: int, payload: Dict[str, Any]) -> None:
+ raw = json.dumps(payload).encode("utf-8")
+ handler.send_response(status)
+ handler.send_header("Content-Type", "application/json")
+ handler.send_header("Content-Length", str(len(raw)))
+ handler.send_header("Connection", "close")
+ handler.end_headers()
+ handler.wfile.write(raw)
+
+ def _write_empty(handler: BaseHTTPRequestHandler, status: int) -> None:
+ handler.send_response(status)
+ handler.send_header("Content-Length", "0")
+ handler.send_header("Connection", "close")
+ handler.end_headers()
+
+ class DiscoveryHandler(BaseHTTPRequestHandler):
+ def log_message(self, format, *args):
+ # Suppress server logging to stdout/stderr to keep stdio clean
+ pass
+
+ def do_OPTIONS(self):
+ # TS discovery handlers honor CORS preflight without leaking credentials.
+ self.send_response(200)
+ self.send_header("Access-Control-Allow-Origin", "*")
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
+ self.send_header("Content-Length", "0")
+ self.send_header("Connection", "close")
+ self.end_headers()
+
+ def _proxy_headers(self) -> Dict[str, str]:
+ return {key: value for key, value in self.headers.items()}
+
+ def _proxy_peer(self) -> Optional[str]:
+ return self.client_address[0] if self.client_address else None
+
+ def _trusted_public_origin(self) -> Optional[str]:
+ from nitrostack.transports.proxy import public_origin, trusted_forwarded_host
+
+ headers = self._proxy_headers()
+ peer = self._proxy_peer()
+ if not trusted_forwarded_host(headers, peer):
+ return None
+ port = service_instance.bound_port or service_instance.discovery_port
+ return public_origin(
+ headers,
+ peer,
+ fallback_host=f"localhost:{port}",
+ fallback_proto="http",
+ )
+
+ def do_GET(self):
+ if self.path == "/.well-known/oauth-protected-resource":
+ _write_json(self, 200, build_protected_resource_metadata(service_instance))
+ elif self.path == "/.well-known/oauth-authorization-server":
+ origin = self._trusted_public_origin()
+ registration_endpoint = (
+ registration_path if is_client_registration_enabled(service_instance) else None
+ )
+ _write_json(
+ self,
+ 200,
+ build_authorization_server_metadata(
+ service_instance,
+ registration_endpoint,
+ public_origin=origin,
+ ),
+ )
+ else:
+ _write_empty(self, 404)
+
+ def do_POST(self):
+ if self.path != registration_path:
+ _write_empty(self, 404)
+ return
+
+ if not is_client_registration_enabled(service_instance):
+ _write_json(
+ self,
+ 404,
+ {"error": "not_found", "error_description": "Client registration is not enabled"},
+ )
+ return
+
+ length = int(self.headers.get("Content-Length", 0))
+ raw_body = self.rfile.read(length) if length else b""
+ try:
+ body = json.loads(raw_body.decode("utf-8")) if raw_body else {}
+ except Exception:
+ body = {}
+
+ try:
+ body = apply_cimd_to_registration_body(
+ body,
+ headers=self._proxy_headers(),
+ peer=self._proxy_peer(),
+ )
+ except (CimdValidationError, CimdFetchError) as exc:
+ _write_json(
+ self,
+ 400,
+ {
+ "error": "invalid_client_metadata",
+ "error_description": str(exc),
+ },
+ )
+ return
+
+ _write_json(self, 200, build_registration_response(service_instance, body))
+
+ raw_port = os.environ.get("OAUTH_DISCOVERY_PORT")
+ if raw_port is not None:
+ try:
+ start_port = int(raw_port)
+ except ValueError:
+ start_port = service.discovery_port
+ else:
+ start_port = service.discovery_port
+
+ max_retries = max(0, service.discovery_max_retries) if service.discovery_auto_retry else 0
+ last_error: Optional[Exception] = None
+ bound_server: Optional[HTTPServer] = None
+
+ for attempt in range(max_retries + 1):
+ candidate_port = start_port + attempt
+ if candidate_port > 65535:
+ if last_error is None:
+ last_error = OverflowError("bind(): port must be 0-65535")
+ break
+ try:
+ server = HTTPServer(("localhost", candidate_port), DiscoveryHandler)
+ bound_server = server
+ service.bound_port = server.server_address[1]
+ break
+ except (OSError, OverflowError) as e:
+ last_error = e
+
+ if bound_server is None:
+ sys.stderr.write(f"Failed to start OAuth Discovery Server on port {start_port}: {last_error}\n")
+ sys.stderr.flush()
+ if isinstance(last_error, OSError):
+ raise last_error
+ raise OSError(f"Failed to start OAuth Discovery Server on port {start_port}: {last_error}") from last_error
+
+ service._server = bound_server
+
+ # Notify client via stderr
+ oauth_metadata = {
+ "port": service.bound_port,
+ "resource_uri": service.resource_uri,
+ "authorization_servers": service.authorization_servers,
+ }
+ sys.stderr.write(
+ f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n"
+ )
+ sys.stderr.flush()
+
+ service._thread = threading.Thread(target=service._server.serve_forever, daemon=True)
+ service._thread.start()
diff --git a/nitrostack/auth/oauth_module.py b/nitrostack/auth/oauth_module.py
index b2585c4..56f5f25 100644
--- a/nitrostack/auth/oauth_module.py
+++ b/nitrostack/auth/oauth_module.py
@@ -20,6 +20,8 @@
import time
from typing import Any, Dict, Optional, TYPE_CHECKING
+from nitrostack.auth.secret import unwrap_secret
+
from nitrostack.auth.cimd import (
looks_like_cimd_url,
resolve_cimd_sync,
@@ -112,22 +114,32 @@ def apply_cimd_to_registration_body(
honored only when the peer is trusted, so an untrusted
``X-Forwarded-Host`` cannot rebind the CIMD host comparison.
"""
- from nitrostack.auth.cimd import cimd_host_matches_request, request_host_for_cimd
+ from nitrostack.auth.cimd import (
+ CimdValidationError,
+ cimd_host_matches_request,
+ request_host_for_cimd,
+ )
payload = dict(body or {})
client_id = payload.get("client_id")
if not looks_like_cimd_url(client_id):
return payload
document = resolve_cimd_sync(str(client_id))
- payload["client_id"] = document["client_id"]
- payload["_cimd"] = document
- if headers is not None:
- payload["_cimd_request_host"] = request_host_for_cimd(headers, peer)
- payload["_cimd_host_matches_request"] = cimd_host_matches_request(
+ if headers is not None or peer is not None:
+ req_headers = headers if headers is not None else {}
+ if not cimd_host_matches_request(
str(document["client_id"]),
- headers,
+ req_headers,
peer,
- )
+ ):
+ req_host = request_host_for_cimd(req_headers, peer)
+ raise CimdValidationError(
+ f"CIMD client_id URL host does not match request host: {req_host!r}"
+ )
+ payload["_cimd_request_host"] = request_host_for_cimd(req_headers, peer)
+ payload["_cimd_host_matches_request"] = True
+ payload["client_id"] = document["client_id"]
+ payload["_cimd"] = document
return payload
@@ -143,7 +155,8 @@ def build_registration_response(service: "OAuthService", body: Optional[Dict[str
"""
body = body or {}
client_id = service.static_client_id
- client_secret = service.static_client_secret or ""
+ # The registration response must hand the real secret to the client, so unwrap it here.
+ client_secret = unwrap_secret(service.static_client_secret) if service.static_client_secret is not None else ""
return {
"client_id": client_id,
"client_secret": client_secret,
diff --git a/nitrostack/auth/oauth_tokens.py b/nitrostack/auth/oauth_tokens.py
new file mode 100644
index 0000000..c7d50cc
--- /dev/null
+++ b/nitrostack/auth/oauth_tokens.py
@@ -0,0 +1,121 @@
+"""Token validation: JWKS verification, RFC 7662 introspection and audience checks.
+
+Each function takes the ``OAuthService`` whose settings it uses. Depends only on
+``oauth_types`` (and ``secret``); it never imports ``oauth``.
+"""
+
+import json
+import sys
+import urllib.parse
+import urllib.request
+from typing import TYPE_CHECKING, Any
+
+from nitrostack.auth.oauth_types import TokenInfo, _has_secret
+from nitrostack.auth.secret import unwrap_secret
+
+if TYPE_CHECKING:
+ from nitrostack.auth.oauth import OAuthService
+
+
+def get_jwks_client(service: "OAuthService", jwks_uri: str) -> Any:
+ """Return a cached PyJWKClient for this URI, creating it on first use.
+
+ PyJWKClient already caches individual signing keys internally; this cache
+ is one level up — it avoids reconstructing the client object itself (and
+ re-fetching the whole key set) on every single token check.
+ """
+ import jwt
+ client = service._jwks_clients.get(jwks_uri)
+ if client is None:
+ client = jwt.PyJWKClient(jwks_uri)
+ service._jwks_clients[jwks_uri] = client
+ return client
+
+
+def introspect_via_jwks(service: "OAuthService", token: str) -> TokenInfo:
+ """JWT signature verification using a cached JWKS client (RFC 7517/7519)."""
+ try:
+ import jwt
+ jwks_client = service._get_jwks_client(service.jwks_uri)
+ signing_key = jwks_client.get_signing_key_from_jwt(token)
+
+ data = jwt.decode(
+ token,
+ signing_key.key,
+ algorithms=["RS256"],
+ audience=service.audience,
+ issuer=service.issuer,
+ )
+ return {
+ "active": True,
+ "scope": data.get("scope", ""),
+ "sub": data.get("sub"),
+ "client_id": data.get("client_id"),
+ "aud": data.get("aud"),
+ "exp": data.get("exp"),
+ "iat": data.get("iat"),
+ "iss": data.get("iss"),
+ }
+ except Exception as e:
+ sys.stderr.write(f"OAuth JWKS verification failed: {e}\n")
+ sys.stderr.flush()
+ return {"active": False}
+
+
+async def introspect_via_endpoint(service: "OAuthService", token: str) -> TokenInfo:
+ """RFC 7662 token introspection: POST the token to the authorization server
+ and ask whether it's active."""
+ data = urllib.parse.urlencode({"token": token}).encode("utf-8")
+ req = urllib.request.Request(service.token_introspection_endpoint, data=data, method="POST")
+ req.add_header("Content-Type", "application/x-www-form-urlencoded")
+
+ # Add basic auth if client credentials provided
+ if service.token_introspection_client_id and _has_secret(service.token_introspection_client_secret):
+ import base64
+ client_secret = unwrap_secret(service.token_introspection_client_secret)
+ auth_str = f"{service.token_introspection_client_id}:{client_secret}"
+ encoded_auth = base64.b64encode(auth_str.encode("utf-8")).decode("utf-8")
+ req.add_header("Authorization", f"Basic {encoded_auth}")
+
+ try:
+ # urllib.request is synchronous; run it on a thread so it doesn't block
+ # the event loop this async method is running on.
+ import asyncio
+ loop = asyncio.get_event_loop()
+
+ def do_request():
+ with urllib.request.urlopen(req, timeout=5) as response:
+ return json.loads(response.read().decode("utf-8"))
+
+ return await loop.run_in_executor(None, do_request)
+ except Exception as e:
+ sys.stderr.write(f"OAuth Introspection Request Failed: {e}\n")
+ sys.stderr.flush()
+ return {"active": False}
+
+
+def validate_audience(service: "OAuthService", introspection: TokenInfo) -> bool:
+ """
+ RFC 8707 resource-indicator check: does this token's `aud` claim include
+ the resource it's being presented to? Without this, a token minted for a
+ *different* service could be replayed here and accepted — the token is
+ legitimately signed/active, just not meant for this resource.
+
+ `aud` is legal as either a single string or a list of strings per JWT
+ conventions, so it's normalized to a list before comparing.
+ """
+ expected = service.audience or service.resource_uri
+ if not expected:
+ # Nothing configured to check against — permissive, matching the
+ # TypeScript SDK's default when no audience is configured.
+ return True
+
+ raw_aud = introspection.get("aud")
+ if raw_aud is None:
+ # No audience claim on the token at all — nothing to validate against.
+ # Treat as permissive rather than rejecting tokens from authorization
+ # servers that don't emit `aud`.
+ return True
+
+ token_audiences = raw_aud if isinstance(raw_aud, list) else [raw_aud]
+ return expected in token_audiences
diff --git a/nitrostack/auth/oauth_types.py b/nitrostack/auth/oauth_types.py
new file mode 100644
index 0000000..0b91076
--- /dev/null
+++ b/nitrostack/auth/oauth_types.py
@@ -0,0 +1,44 @@
+"""Shared OAuth helpers and types. A leaf module: it imports no other OAuth module."""
+
+import os
+from typing import Any, Dict, Optional
+
+from nitrostack.auth.secret import SecretValue
+
+# RFC 7662 introspection result: ``{"active": bool, ...claims}``.
+TokenInfo = Dict[str, Any]
+
+
+def is_oauth_required() -> bool:
+ """TS ``OAuthModule.isAuthRequired()`` — Studio/local default is off.
+
+ Set ``OAUTH_REQUIRED=true`` to enforce Bearer tokens. Unset/false lets
+ NitroStudio and Inspector call tools against mock Duffel data.
+ """
+ return (os.environ.get("OAUTH_REQUIRED") or "").strip().lower() == "true"
+
+
+def generate_www_authenticate_header(
+ *,
+ realm: str = "mcp",
+ resource_metadata: Optional[str] = None,
+ error: Optional[str] = None,
+ error_description: Optional[str] = None,
+) -> str:
+ """RFC 6750 / RFC 9728 WWW-Authenticate value for protected MCP resources."""
+ parts = [f'Bearer realm="{realm}"']
+ if resource_metadata:
+ parts.append(f'resource_metadata="{resource_metadata}"')
+ if error:
+ parts.append(f'error="{error}"')
+ if error_description:
+ escaped = error_description.replace('"', "'")
+ parts.append(f'error_description="{escaped}"')
+ return ", ".join(parts)
+
+
+def _has_secret(value: Any) -> bool:
+ """True when a secret was given. A SecretValue counts even if it holds no value (it is
+ falsy after pickling), so it is never silently replaced by an environment variable;
+ unwrapping it raises instead."""
+ return isinstance(value, SecretValue) or bool(value)
diff --git a/nitrostack/auth/request.py b/nitrostack/auth/request.py
index b3c22c4..6804951 100644
--- a/nitrostack/auth/request.py
+++ b/nitrostack/auth/request.py
@@ -108,12 +108,13 @@ def authorization_token_from_request(rc: Any) -> Optional[str]:
def verify_bearer_payload(token: str) -> Optional[dict[str, Any]]:
- try:
- from nitrostack.auth.jwt import JWTService
- from nitrostack.core.di import DIContainer
+ from nitrostack.auth.jwt import JWTService
+ from nitrostack.core.di import DIContainer
- payload = DIContainer.get_instance().resolve(JWTService).verify_token(token)
- except Exception:
+ service = DIContainer.get_instance().resolve(JWTService)
+ try:
+ payload = service.verify_token(token)
+ except ValueError:
return None
return payload if isinstance(payload, dict) else None
diff --git a/nitrostack/auth/secret.py b/nitrostack/auth/secret.py
new file mode 100644
index 0000000..e7dff7a
--- /dev/null
+++ b/nitrostack/auth/secret.py
@@ -0,0 +1,234 @@
+"""``SecretValue``: a wrapper that keeps a secret out of logs, ``repr``, tracebacks,
+pickles and serialized output.
+
+The raw value is only reachable through :meth:`SecretValue.unwrap`. Everything else
+that could print or serialize the object shows ``[SecretValue: REDACTED]`` instead.
+
+>>> s = SecretValue.from_value("a-long-test-secret-value", allow_hardcoded=True)
+>>> f"{s}", repr(s)
+('[SecretValue: REDACTED]', '[SecretValue: REDACTED]')
+"""
+
+from __future__ import annotations
+
+import hmac
+import os
+import secrets as _secrets
+import warnings
+from typing import Any, Optional, Union
+
+REDACTED = "[SecretValue: REDACTED]"
+
+# Secrets shorter than this still work, but trigger a warning.
+MIN_RECOMMENDED_LENGTH = 16
+
+# Per-process key so hash() never exposes anything derived from the value alone.
+_HASH_KEY = _secrets.token_bytes(32)
+
+
+# Only these labels are ever written into a pickle. Anything else becomes "custom", so a
+# caller who passes a secret (or part of one) as ``source`` cannot leak it that way.
+_PICKLE_SAFE_SOURCES = frozenset({"env", "config", "explicit"})
+
+
+def _redacted_after_pickle(source: str) -> "SecretValue":
+ """Rebuild a ``SecretValue`` that carries no value (used when unpickling)."""
+ return SecretValue._empty(source)
+
+
+class SecretValue:
+ """Holds a secret string and refuses to reveal it by accident."""
+
+ __slots__ = ("_value", "source")
+
+ def __init__(self, value: str, source: str = "env") -> None:
+ if not isinstance(value, str):
+ raise TypeError("SecretValue needs a str value")
+ if not value:
+ raise ValueError("Secret value cannot be empty")
+ if len(value) < MIN_RECOMMENDED_LENGTH:
+ warnings.warn(
+ f"[SecretValue] Secret is shorter than {MIN_RECOMMENDED_LENGTH} characters. "
+ "Consider using a longer secret.",
+ UserWarning,
+ stacklevel=2,
+ )
+ if not isinstance(source, str) or value in source:
+ raise ValueError("source must be a short label such as 'env', never the secret itself")
+ self._value: Optional[str] = value
+ self.source = source
+
+ # ------------------------------------------------------------------
+ # Construction
+ # ------------------------------------------------------------------
+
+ @classmethod
+ def _empty(cls, source: str) -> "SecretValue":
+ """A secret that was redacted on its way through pickle. It has no value."""
+ obj = cls.__new__(cls)
+ obj._value = None
+ obj.source = source
+ return obj
+
+ @classmethod
+ def from_env(cls, env_var_name: str) -> "SecretValue":
+ """Read a required secret from an environment variable."""
+ value = os.environ.get(env_var_name)
+ if not value:
+ raise ValueError(
+ f"Environment variable {env_var_name} is not set. "
+ "Set it in your environment or .env file."
+ )
+ return cls(value, "env")
+
+ @classmethod
+ def from_env_optional(cls, env_var_name: str) -> Optional["SecretValue"]:
+ """Read a secret from an environment variable, or ``None`` when it is not set."""
+ value = os.environ.get(env_var_name)
+ if not value:
+ return None
+ return cls(value, "env")
+
+ @classmethod
+ def from_value(
+ cls,
+ value: str,
+ allow_hardcoded: bool = False,
+ reason: Optional[str] = None,
+ ) -> "SecretValue":
+ """Wrap a value that is written in code. This must be allowed explicitly."""
+ if not allow_hardcoded:
+ raise ValueError(
+ "Hardcoded secrets are not allowed. Use SecretValue.from_env() to load "
+ "secrets from environment variables. If you must use a hardcoded value "
+ "(for example in a test), pass allow_hardcoded=True."
+ )
+ warnings.warn(
+ "[SecretValue] Using a hardcoded secret value. "
+ f"Reason: {reason or 'not specified'}. Do not do this in production.",
+ UserWarning,
+ stacklevel=2,
+ )
+ return cls(value, "explicit")
+
+ # ------------------------------------------------------------------
+ # Access
+ # ------------------------------------------------------------------
+
+ def unwrap(self) -> str:
+ """Return the raw secret. Call this only where the value is really needed."""
+ if self._value is None:
+ raise ValueError(
+ "This SecretValue was redacted during serialization and has no value."
+ )
+ return self._value
+
+ def is_from_environment(self) -> bool:
+ return self.source == "env"
+
+ # ------------------------------------------------------------------
+ # Redaction: str, repr, format, f-strings, logging, tracebacks
+ # ------------------------------------------------------------------
+
+ def __str__(self) -> str:
+ return REDACTED
+
+ def __repr__(self) -> str:
+ return REDACTED
+
+ def __format__(self, format_spec: str) -> str:
+ return format(REDACTED, format_spec)
+
+ # ------------------------------------------------------------------
+ # Comparison
+ # ------------------------------------------------------------------
+
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, SecretValue):
+ other_value = other._value
+ elif isinstance(other, str):
+ other_value = other
+ else:
+ return NotImplemented
+ if self._value is None or other_value is None:
+ return False
+ return hmac.compare_digest(self._value.encode("utf-8"), other_value.encode("utf-8"))
+
+ def __ne__(self, other: object) -> bool:
+ result = self.__eq__(other)
+ return result if result is NotImplemented else not result
+
+ def __hash__(self) -> int:
+ if self._value is None:
+ return hash(("SecretValue", "redacted"))
+ return hash(hmac.digest(_HASH_KEY, self._value.encode("utf-8"), "sha256"))
+
+ def __bool__(self) -> bool:
+ return self._value is not None
+
+ # ------------------------------------------------------------------
+ # Pickle and copy
+ # ------------------------------------------------------------------
+
+ def __reduce__(self):
+ # The pickle holds only the source. Loading it gives a SecretValue with no
+ # value, so a secret can neither leak through a pickle nor be silently
+ # replaced by a placeholder string.
+ # Emit a built-in label, never ``self.source`` itself: a ``str`` subclass can carry
+ # extra pickle state (or fake ``==``), and ``str.__eq__`` ignores both.
+ source = next(
+ (label for label in _PICKLE_SAFE_SOURCES if str.__eq__(self.source, label) is True),
+ "custom",
+ )
+ return (_redacted_after_pickle, (source,))
+
+ def __copy__(self) -> "SecretValue":
+ return self # immutable, so sharing is safe
+
+ def __deepcopy__(self, memo: Any) -> "SecretValue":
+ return self
+
+ # ------------------------------------------------------------------
+ # Pydantic v2: validation and JSON/dict serialization
+ # ------------------------------------------------------------------
+
+ @classmethod
+ def __get_pydantic_core_schema__(cls, source_type: Any, handler: Any):
+ from pydantic_core import core_schema
+
+ def validate(value: Any) -> "SecretValue":
+ if isinstance(value, SecretValue):
+ return value
+ if isinstance(value, str):
+ return cls(value, "explicit")
+ raise ValueError("expected a SecretValue or a string")
+
+ return core_schema.no_info_plain_validator_function(
+ validate,
+ serialization=core_schema.plain_serializer_function_ser_schema(
+ lambda _value: REDACTED,
+ return_schema=core_schema.str_schema(),
+ when_used="always",
+ ),
+ )
+
+ @classmethod
+ def __get_pydantic_json_schema__(cls, core_schema_: Any, handler: Any):
+ return {"type": "string", "format": "password", "writeOnly": True}
+
+
+def is_secret_value(value: Any) -> bool:
+ """True when ``value`` is a ``SecretValue``."""
+ return isinstance(value, SecretValue)
+
+
+def unwrap_secret(secret: Union[SecretValue, str]) -> str:
+ """Return the raw string for a ``SecretValue`` or a plain ``str``.
+
+ Plain strings are accepted so existing code keeps working.
+ """
+ if isinstance(secret, SecretValue):
+ return secret.unwrap()
+ if isinstance(secret, str):
+ return secret
+ raise TypeError(f"Expected a SecretValue or str, got {type(secret).__name__}")
diff --git a/nitrostack/auth/setup.py b/nitrostack/auth/setup.py
new file mode 100644
index 0000000..d817ada
--- /dev/null
+++ b/nitrostack/auth/setup.py
@@ -0,0 +1,221 @@
+"""One-call setup helpers for JWT, API key and OAuth, plus an environment check.
+
+Each ``setup_*_auth`` helper returns a plain ``dict`` of keyword arguments. Pass it straight
+to the matching module::
+
+ JWTModule.for_root(**setup_jwt_auth())
+ ApiKeyModule.for_root(**setup_api_key_auth())
+ OAuthModule.for_root(**setup_oauth_auth())
+
+Secrets in the returned dict are ``SecretValue`` objects, so printing or logging the config
+never shows them.
+"""
+
+import os
+import secrets
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
+
+from nitrostack.auth.secret import SecretValue
+from nitrostack.core.errors import ConfigurationError
+
+AUTH_KINDS = ("jwt", "api_key", "oauth")
+
+# Each entry is a group of alternatives: the group is satisfied if ANY name in it is set.
+_REQUIRED_ENV: Dict[str, List[Tuple[str, ...]]] = {
+ "jwt": [("JWT_SECRET",)],
+ "api_key": [("API_KEY",)],
+ "oauth": [
+ ("RESOURCE_URI",),
+ ("AUTH_SERVER_URL",),
+ ("JWKS_URI", "OAUTH_INTROSPECTION_ENDPOINT", "INTROSPECTION_ENDPOINT"),
+ ],
+}
+
+_INSTRUCTIONS = {
+ "jwt": """JWT auth setup
+ 1. Set a long random secret: JWT_SECRET=
+ 2. In your module: JWTModule.for_root(**setup_jwt_auth())
+ Optional: TOKEN_AUDIENCE, TOKEN_ISSUER""",
+ "api_key": """API key auth setup
+ 1. Set one or more keys: API_KEY= (or API_KEY_1, API_KEY_2, ...)
+ 2. In your module: ApiKeyModule.for_root(**setup_api_key_auth())
+ Clients send the key in the x-api-key header.""",
+ "oauth": """OAuth auth setup
+ 1. Set the server identity: RESOURCE_URI=https://your-server/mcp
+ AUTH_SERVER_URL=https://your-authorization-server
+ 2. Set ONE way to verify tokens:
+ JWKS_URI=https://your-authorization-server/.well-known/jwks.json
+ or OAUTH_INTROSPECTION_ENDPOINT=https://your-authorization-server/introspect
+ 3. In your module: OAuthModule.for_root(**setup_oauth_auth())
+ Optional: TOKEN_AUDIENCE, TOKEN_ISSUER, INTROSPECTION_CLIENT_ID, INTROSPECTION_CLIENT_SECRET""",
+}
+
+
+def _check_kind(kind: str) -> str:
+ if kind not in AUTH_KINDS:
+ raise ValueError(f"Unknown auth kind {kind!r}; expected one of {', '.join(AUTH_KINDS)}")
+ return kind
+
+
+def _is_set(name: str) -> bool:
+ return bool((os.environ.get(name) or "").strip())
+
+
+def _api_key_names() -> List[str]:
+ return [k for k in os.environ if (k == "API_KEY" or k.startswith("API_KEY_")) and _is_set(k)]
+
+
+def validate_auth_env(kind: str) -> Tuple[bool, List[str]]:
+ """Check the environment for ``kind`` (``"jwt"``, ``"api_key"`` or ``"oauth"``).
+
+ Returns ``(valid, missing)``. ``missing`` lists every missing variable, not just the
+ first. When any one of several variables would do, they are shown joined with `` or ``.
+ """
+ _check_kind(kind)
+ missing: List[str] = []
+ for group in _REQUIRED_ENV[kind]:
+ if kind == "api_key":
+ satisfied = bool(_api_key_names())
+ label = "API_KEY (or API_KEY_)"
+ else:
+ satisfied = any(_is_set(name) for name in group)
+ label = " or ".join(group)
+ if not satisfied:
+ missing.append(label)
+ return (not missing, missing)
+
+
+def print_auth_setup_instructions(kind: str) -> None:
+ """Print how to configure ``kind``. Never prints any secret value."""
+ print(_INSTRUCTIONS[_check_kind(kind)])
+
+
+def _require_env(kind: str) -> None:
+ valid, missing = validate_auth_env(kind)
+ if not valid:
+ raise ConfigurationError(
+ f"Missing environment for {kind} auth: {', '.join(missing)}. "
+ f"Call print_auth_setup_instructions({kind!r}) for help."
+ )
+
+
+def setup_jwt_auth(
+ secret: Union[SecretValue, str, None] = None,
+ expires_in: str = "24h",
+ audience: Optional[str] = None,
+ issuer: Optional[str] = None,
+ secret_env_var: str = "JWT_SECRET",
+) -> Dict[str, Any]:
+ """Return keyword arguments for ``JWTModule.for_root``.
+
+ Without ``secret``, the secret is read from ``JWT_SECRET`` and a
+ ``ConfigurationError`` is raised if it is not set.
+ """
+ if secret is None:
+ if not _is_set(secret_env_var):
+ raise ConfigurationError(
+ f"Missing environment for jwt auth: {secret_env_var}. "
+ "Call print_auth_setup_instructions('jwt') for help."
+ )
+ secret = SecretValue.from_env(secret_env_var)
+ elif not isinstance(secret, SecretValue):
+ secret = SecretValue(secret)
+ return {
+ "secret_env_var": secret_env_var,
+ "expires_in": expires_in,
+ "audience": audience or os.environ.get("TOKEN_AUDIENCE") or None,
+ "issuer": issuer or os.environ.get("TOKEN_ISSUER") or None,
+ "secret": secret,
+ }
+
+
+def setup_api_key_auth(
+ keys: Optional[Sequence[Union[SecretValue, str]]] = None,
+ header_name: str = "x-api-key",
+ hashed: bool = False,
+ keys_env_prefix: str = "API_KEY",
+) -> Dict[str, Any]:
+ """Return keyword arguments for ``ApiKeyModule.for_root``.
+
+ Without ``keys``, at least one ``API_KEY`` / ``API_KEY_`` variable must be set.
+ """
+ if keys:
+ wrapped = [k if isinstance(k, SecretValue) else SecretValue(k) for k in keys]
+ else:
+ names = [
+ k
+ for k in os.environ
+ if (k == keys_env_prefix or k.startswith(f"{keys_env_prefix}_")) and _is_set(k)
+ ]
+ if not names:
+ raise ConfigurationError(
+ f"Missing environment for api_key auth: {keys_env_prefix} "
+ f"(or {keys_env_prefix}_). "
+ "Call print_auth_setup_instructions('api_key') for help."
+ )
+ wrapped = [] # the module reads these from the environment itself
+ return {
+ "keys_env_prefix": keys_env_prefix,
+ "header_name": header_name,
+ "hashed": hashed,
+ "keys": wrapped,
+ }
+
+
+def setup_oauth_auth(
+ resource_uri: Optional[str] = None,
+ authorization_servers: Optional[Sequence[str]] = None,
+ scopes_supported: Optional[Sequence[str]] = None,
+ **overrides: Any,
+) -> Dict[str, Any]:
+ """Return keyword arguments for ``OAuthModule.for_root``.
+
+ Values not passed are read from ``RESOURCE_URI`` and ``AUTH_SERVER_URL``. Token
+ verification (``JWKS_URI`` or an introspection endpoint) is picked up by the module
+ from the environment, so one of them must be set unless passed in ``overrides``
+ (for example ``jwks_uri=...`` or ``token_introspection_endpoint=...``).
+ Any other ``OAuthModule.for_root`` argument can be passed as an override.
+ """
+ resource = resource_uri or os.environ.get("RESOURCE_URI")
+ servers = list(authorization_servers or [])
+ if not servers and _is_set("AUTH_SERVER_URL"):
+ servers = [os.environ["AUTH_SERVER_URL"].strip()]
+ has_verifier = (
+ overrides.get("jwks_uri")
+ or overrides.get("token_introspection_endpoint")
+ or any(_is_set(n) for n in _REQUIRED_ENV["oauth"][2])
+ )
+ missing: List[str] = []
+ if not resource:
+ missing.append("RESOURCE_URI")
+ if not servers:
+ missing.append("AUTH_SERVER_URL")
+ if not has_verifier:
+ missing.append(" or ".join(_REQUIRED_ENV["oauth"][2]))
+ if missing:
+ raise ConfigurationError(
+ f"Missing environment for oauth auth: {', '.join(missing)}. "
+ "Call print_auth_setup_instructions('oauth') for help."
+ )
+ for name in ("token_introspection_client_secret", "static_client_secret"):
+ value = overrides.get(name)
+ if isinstance(value, str):
+ overrides[name] = SecretValue(value)
+ return {
+ "resource_uri": resource,
+ "authorization_servers": servers,
+ "scopes_supported": list(scopes_supported or ["read", "write"]),
+ **overrides,
+ }
+
+
+def generate_test_credentials() -> Dict[str, SecretValue]:
+ """Make random credentials for TESTS AND LOCAL DEMOS ONLY. Never use them in production.
+
+ Fresh on every call. The values are ``SecretValue`` objects, so they are not printed
+ by default; call ``.unwrap()`` to read one.
+ """
+ return {
+ "jwt_secret": SecretValue(secrets.token_urlsafe(48)),
+ "api_key": SecretValue(f"sk_test_{secrets.token_hex(24)}"),
+ }
diff --git a/nitrostack/auth/token_store.py b/nitrostack/auth/token_store.py
new file mode 100644
index 0000000..77b5c30
--- /dev/null
+++ b/nitrostack/auth/token_store.py
@@ -0,0 +1,298 @@
+"""Async token persistence adapted from the unmerged full-parity implementation.
+
+Expiry is milliseconds since the Unix epoch; durations and skew are seconds.
+Expired records remain readable so their refresh credentials are not discarded.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import math
+import os
+import stat
+import tempfile
+import threading
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Mapping, Protocol
+
+
+class TokenStoreError(ValueError):
+ """Persistence or record validation failed; messages never contain credentials."""
+
+
+@dataclass(frozen=True)
+class StoredToken:
+ access_token: str = field(repr=False)
+ token_type: str = field(repr=False)
+ expires_at: int
+ refresh_token: str | None = field(default=None, repr=False)
+ scope: str | None = field(default=None, repr=False)
+ resource: str | None = field(default=None, repr=False)
+
+ def __post_init__(self) -> None:
+ if not isinstance(self.access_token, str) or not self.access_token:
+ raise TokenStoreError("Invalid access token")
+ if not isinstance(self.token_type, str) or not self.token_type:
+ raise TokenStoreError("Invalid token type")
+ if type(self.expires_at) is not int or self.expires_at < 0:
+ raise TokenStoreError("Invalid token expiry")
+ if any(value is not None and not isinstance(value, str)
+ for value in (self.refresh_token, self.scope, self.resource)):
+ raise TokenStoreError("Invalid optional token fields")
+
+ def to_dict(self) -> dict[str, Any]:
+ """Explicit credential-bearing serialization. Never log this mapping."""
+ return {"access_token": self.access_token, "token_type": self.token_type,
+ "expires_at": self.expires_at, "refresh_token": self.refresh_token,
+ "scope": self.scope, "resource": self.resource}
+
+ @classmethod
+ def from_dict(cls, value: Mapping[str, Any]) -> StoredToken:
+ try:
+ return cls(**dict(value))
+ except (TypeError, ValueError):
+ raise TokenStoreError("Invalid stored token record") from None
+
+
+def _seconds(value: float, label: str) -> float:
+ try:
+ valid = not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(value) and value >= 0
+ except OverflowError:
+ valid = False
+ if not valid:
+ raise ValueError(f"{label} must be finite, nonnegative seconds")
+ return value
+
+
+def calculate_expiration(expires_in: float) -> int:
+ deadline = time.time() * 1000 + _seconds(expires_in, "expires_in") * 1000
+ if not math.isfinite(deadline):
+ raise ValueError("expires_in is too large")
+ return int(deadline)
+
+
+def is_token_expired(token: StoredToken, skew: float = 30) -> bool:
+ return time.time() * 1000 >= token.expires_at - _seconds(skew, "skew") * 1000
+
+
+def token_response_to_stored(
+ response: Mapping[str, Any], resource: str | None = None,
+ *, previous: StoredToken | None = None,
+) -> StoredToken:
+ """Use a one-hour fallback only for absent expiry, preserving refresh rotation."""
+ try:
+ expires_in = response.get("expires_in")
+ if isinstance(expires_in, str):
+ expires_in = float(expires_in.strip())
+ return StoredToken(
+ access_token=response["access_token"],
+ token_type=response.get("token_type", "Bearer"),
+ expires_at=calculate_expiration(3600 if expires_in is None else expires_in),
+ refresh_token=response.get("refresh_token", previous.refresh_token if previous else None),
+ scope=response.get("scope", previous.scope if previous else None),
+ resource=previous.resource if previous else resource,
+ )
+ except (KeyError, TypeError, ValueError, OverflowError):
+ raise TokenStoreError("Invalid OAuth token response") from None
+
+
+class TokenStore(Protocol):
+ async def save_token(self, key: str, token: StoredToken) -> None: ...
+ async def get_token(self, key: str) -> StoredToken | None: ...
+ async def delete_token(self, key: str) -> None: ...
+ async def list_keys(self) -> list[str]: ...
+ async def clear(self) -> None: ...
+
+
+def _validate_key(key: str) -> None:
+ if not isinstance(key, str) or not key:
+ raise TokenStoreError("A nonempty token key is required")
+
+
+class MemoryTokenStore:
+ def __init__(self) -> None:
+ self._tokens: dict[str, StoredToken] = {}
+ self._lock = threading.RLock()
+
+ async def save_token(self, key: str, token: StoredToken) -> None:
+ _validate_key(key)
+ if not isinstance(token, StoredToken):
+ raise TokenStoreError("Expected a StoredToken")
+ with self._lock:
+ self._tokens[key] = token
+
+ async def get_token(self, key: str) -> StoredToken | None:
+ _validate_key(key)
+ with self._lock:
+ return self._tokens.get(key)
+
+ async def delete_token(self, key: str) -> None:
+ _validate_key(key)
+ with self._lock:
+ self._tokens.pop(key, None)
+
+ async def list_keys(self) -> list[str]:
+ with self._lock:
+ return list(self._tokens)
+
+ async def clear(self) -> None:
+ with self._lock:
+ self._tokens.clear()
+
+
+_ENCRYPTION_SALT = b"nitrostack-token-store"
+_path_locks = tuple(threading.RLock() for _ in range(256))
+
+
+class FileTokenStore:
+ """Atomic single-process storage, serialized across instances of the same path.
+
+ POSIX files are mode 0600. Windows deployments must use a private parent ACL.
+ Encryption retains the prior AES-GCM ``iv:tag:ciphertext`` hex file format.
+ """
+
+ def __init__(self, store_path: str | Path, encryption_key: str | None = None):
+ self._path = Path(store_path).expanduser().absolute()
+ if encryption_key is not None and (not isinstance(encryption_key, str) or not encryption_key):
+ raise TokenStoreError("Encryption key must be a nonempty string")
+ self._encryption_key = None
+ if encryption_key is not None:
+ try:
+ self._encryption_key = hashlib.pbkdf2_hmac(
+ "sha256", encryption_key.encode("utf-8"), _ENCRYPTION_SALT, 100000, 32,
+ )
+ except Exception:
+ raise TokenStoreError("Token store key derivation failed") from None
+ canonical = os.path.normcase(str(self._path.parent.resolve() / self._path.name))
+ self._lock = _path_locks[hash(canonical) % len(_path_locks)]
+
+ def _cipher_parts(self):
+ try:
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
+ except ImportError:
+ raise TokenStoreError("Install nitrostack[token-encryption] for encrypted storage") from None
+ return Cipher, algorithms, modes, self._encryption_key
+
+ def _encrypt(self, text: str) -> str:
+ if self._encryption_key is None:
+ return text
+ Cipher, algorithms, modes, key = self._cipher_parts()
+ iv = os.urandom(16)
+ encryptor = Cipher(algorithms.AES(key), modes.GCM(iv)).encryptor()
+ ciphertext = encryptor.update(text.encode("utf-8")) + encryptor.finalize()
+ return f"{iv.hex()}:{encryptor.tag.hex()}:{ciphertext.hex()}"
+
+ def _decrypt(self, text: str) -> str:
+ if self._encryption_key is None:
+ return text
+ Cipher, algorithms, modes, key = self._cipher_parts()
+ iv, tag, ciphertext = (bytes.fromhex(part) for part in text.split(":"))
+ decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag)).decryptor()
+ return (decryptor.update(ciphertext) + decryptor.finalize()).decode("utf-8")
+
+ def _check_path(self) -> None:
+ if self._path.is_symlink():
+ raise TokenStoreError("Token store cannot be a symlink")
+
+ def _load(self) -> dict[str, StoredToken]:
+ self._check_path()
+ try:
+ descriptor = os.open(self._path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
+ except FileNotFoundError:
+ return {}
+ with os.fdopen(descriptor, "r", encoding="utf-8") as stream:
+ if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
+ raise TokenStoreError("Token store must be a regular file")
+ if os.name == "posix":
+ os.fchmod(stream.fileno(), 0o600)
+ text = stream.read()
+ try:
+ plaintext = self._decrypt(text)
+ except TokenStoreError:
+ raise
+ except Exception:
+ raise TokenStoreError("Token store decryption failed") from None
+ try:
+ raw = json.loads(plaintext)
+ except (ValueError, TypeError):
+ raise TokenStoreError("Token store contains invalid JSON") from None
+ if not isinstance(raw, dict):
+ raise TokenStoreError("Invalid token store document")
+ for key in raw:
+ _validate_key(key)
+ return {key: StoredToken.from_dict(value) for key, value in raw.items()}
+
+ def _save(self, tokens: dict[str, StoredToken]) -> None:
+ self._check_path()
+ data = self._encrypt(json.dumps({key: value.to_dict() for key, value in tokens.items()}))
+ self._path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ descriptor, temporary = tempfile.mkstemp(prefix=".oauth-token-", dir=self._path.parent)
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ if os.name == "posix":
+ os.fchmod(stream.fileno(), 0o600)
+ else:
+ os.chmod(temporary, 0o600)
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ self._check_path()
+ os.replace(temporary, self._path)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+ def _operate(self, operation: str, key=None, token=None):
+ try:
+ with self._lock:
+ tokens = self._load()
+ if operation == "get":
+ return tokens.get(key)
+ if operation == "list":
+ return list(tokens)
+ if operation == "save":
+ tokens[key] = token
+ elif operation == "delete":
+ tokens.pop(key, None)
+ elif operation == "clear":
+ tokens.clear()
+ self._save(tokens)
+ except TokenStoreError:
+ raise
+ except PermissionError:
+ raise TokenStoreError("Token store permission denied") from None
+ except Exception:
+ raise TokenStoreError("Token store operation failed") from None
+
+ async def save_token(self, key: str, token: StoredToken) -> None:
+ _validate_key(key)
+ if not isinstance(token, StoredToken):
+ raise TokenStoreError("Expected a StoredToken")
+ await asyncio.to_thread(self._operate, "save", key, token)
+
+ async def get_token(self, key: str) -> StoredToken | None:
+ _validate_key(key)
+ return await asyncio.to_thread(self._operate, "get", key)
+
+ async def delete_token(self, key: str) -> None:
+ _validate_key(key)
+ await asyncio.to_thread(self._operate, "delete", key)
+
+ async def list_keys(self) -> list[str]:
+ return await asyncio.to_thread(self._operate, "list")
+
+ async def clear(self) -> None:
+ await asyncio.to_thread(self._operate, "clear")
+
+
+def get_default_store_path() -> str:
+ return str(Path.home() / ".nitrostack" / "tokens.json")
+
+
+def create_default_token_store(
+ store_path: str | Path | None = None, encryption_key: str | None = None,
+) -> FileTokenStore:
+ return FileTokenStore(store_path or get_default_store_path(), encryption_key)
diff --git a/nitrostack/cli/_config.py b/nitrostack/cli/_config.py
new file mode 100644
index 0000000..01bb257
--- /dev/null
+++ b/nitrostack/cli/_config.py
@@ -0,0 +1,15 @@
+"""Project template names and CLI defaults."""
+
+DEFAULT_PROJECT_NAME = "my-mcp-server"
+
+DEFAULT_MCP_PORT = "3000"
+
+DEFAULT_WIDGETS_PORT = "3001"
+
+OFFICIAL_TEMPLATES = {
+ "python-starter": "starter",
+ "python-pizzaz": "pizzaz",
+ "python-oauth": "flight-booking",
+ "python-enterprise-search": "enterprise-search",
+ "python-code-mode": "code-mode",
+}
diff --git a/nitrostack/cli/_interaction.py b/nitrostack/cli/_interaction.py
new file mode 100644
index 0000000..a9bb90f
--- /dev/null
+++ b/nitrostack/cli/_interaction.py
@@ -0,0 +1,89 @@
+"""Terminal prompts and template selection."""
+
+import sys
+
+
+def print_banner():
+ banner = """\033[34m╔══════════════════════════════════════════════════════════╗
+║ ║
+║ _ _ ___ _____ ____ ___ ║
+║ | \\ | ||_ _|_ _| _ \\ / _ \\ ║
+║ | \\| | | | | | | |_) | | | | ║
+║ | |\\ | | | | | | _ <| |_| | ║
+║ |_| \\_||___| |_| |_| \\_\\\\___/ ║
+║ ║
+║ \033[1;34mNITROSTACK\033[0;34m — Official MCP Framework ║
+║ ║
+╚══════════════════════════════════════════════════════════╝\033[0m"""
+ print(banner)
+
+def _stdin_is_interactive() -> bool:
+ """False for Studio/CI, which inherit an stdin that may never write."""
+ try:
+ return sys.stdin is not None and sys.stdin.isatty()
+ except Exception:
+ return False
+
+def _prompt(message: str, default: str='', *, _stdin_is_interactive) -> str:
+ default_hint = f" [{default}]" if default else ""
+ sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m{default_hint} ")
+ if not _stdin_is_interactive():
+ sys.stdout.write(f"{default}\n")
+ sys.stdout.flush()
+ return default
+ sys.stdout.flush()
+ try:
+ value = sys.stdin.readline().strip()
+ except Exception:
+ value = ""
+ return value or default
+
+def _resolve_template(template: str, *, OFFICIAL_TEMPLATES) -> str:
+ key = (template or "").strip().lower()
+ if key not in OFFICIAL_TEMPLATES:
+ names = ", ".join(OFFICIAL_TEMPLATES)
+ print(f"Error: Unknown template '{template}'. Use one of: {names}")
+ sys.exit(1)
+ return key
+
+def _prompt_template(*, OFFICIAL_TEMPLATES, _prompt) -> str:
+ print("\033[32m? \033[1;37mChoose a template:\033[0m")
+ print(" \033[34m1. python-starter\033[0m Starter — simple calculator for learning basics")
+ print(" \033[34m2. python-pizzaz\033[0m Advanced — pizza shop finder with maps & widgets")
+ print(" \033[34m3. python-oauth\033[0m Flight booking with OAuth 2.1 auth")
+ print(" \033[34m4. python-enterprise-search\033[0m BM25 progressive tool discovery")
+ print(" \033[34m5. python-code-mode\033[0m QuickJS multi-tool workflows")
+ by_choice = {
+ "1": "python-starter",
+ "2": "python-pizzaz",
+ "3": "python-oauth",
+ "4": "python-enterprise-search",
+ "5": "python-code-mode",
+ }
+ while True:
+ choice = _prompt("Enter choice (1-5) or template name", "1")
+ if choice in by_choice:
+ return by_choice[choice]
+ if choice.lower() in OFFICIAL_TEMPLATES:
+ return choice.lower()
+ print("Please enter 1-5, or an explicit template name (" + ", ".join(OFFICIAL_TEMPLATES) + ").")
+
+def _prompt_yes_no(message: str, default_yes: bool=True, *, _stdin_is_interactive) -> bool:
+ hint = "Y/n" if default_yes else "y/N"
+ sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m ({hint}) ")
+ if not _stdin_is_interactive():
+ sys.stdout.write(("yes" if default_yes else "no") + "\n")
+ sys.stdout.flush()
+ return default_yes
+ sys.stdout.flush()
+ try:
+ ans = sys.stdin.readline().strip().lower()
+ except Exception:
+ ans = ""
+ if not ans:
+ return default_yes
+ if ans in ("y", "yes"):
+ return True
+ if ans in ("n", "no"):
+ return False
+ return default_yes
diff --git a/nitrostack/cli/_pack_files.py b/nitrostack/cli/_pack_files.py
new file mode 100644
index 0000000..f0de42d
--- /dev/null
+++ b/nitrostack/cli/_pack_files.py
@@ -0,0 +1,166 @@
+"""File selection, staging, and cleanup for project packaging."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import stat
+from fnmatch import fnmatch
+from typing import List, Sequence, Tuple
+
+from nitrostack.cli._shared import EXCLUDE_DIR_NAMES
+
+
+_EXCLUDE_DIR_NAMES = EXCLUDE_DIR_NAMES
+
+
+_EXCLUDE_SUFFIXES = {
+ ".pyc",
+ ".pyo",
+ ".pyd",
+ ".so",
+ ".dll",
+ ".egg",
+}
+
+
+_EXCLUDE_NAME_GLOBS = {
+ "*.egg-info",
+}
+
+
+def _is_secret_env(name: str) -> bool:
+ if name == ".env.example":
+ return False
+ return name == ".env" or name.startswith(".env.")
+
+
+def _load_gitignore_patterns(root: str) -> List[Tuple[str, bool]]:
+ """Return (pattern, is_negation) pairs from .gitignore if present."""
+ path = os.path.join(root, ".gitignore")
+ patterns: List[Tuple[str, bool]] = []
+ if not os.path.isfile(path):
+ return patterns
+ try:
+ with open(path, "r", encoding="utf-8") as handle:
+ for raw in handle:
+ line = raw.strip()
+ if not line or line.startswith("#"):
+ continue
+ negated = line.startswith("!")
+ if negated:
+ line = line[1:]
+ patterns.append((line.rstrip("/"), negated))
+ except OSError:
+ return []
+ return patterns
+
+
+def _matches_gitignore(rel_posix: str, patterns: Sequence[Tuple[str, bool]]) -> bool:
+ ignored = False
+ basename = rel_posix.rsplit("/", 1)[-1]
+ for pattern, negated in patterns:
+ pat = pattern[2:] if pattern.startswith("./") else pattern
+ hit = (
+ fnmatch(rel_posix, pat)
+ or fnmatch(rel_posix, pat.rstrip("/") + "/*")
+ or fnmatch(basename, pat)
+ or (pat.endswith("/") and (rel_posix.startswith(pat) or rel_posix.startswith(pat.rstrip("/"))))
+ )
+ if hit:
+ ignored = not negated
+ return ignored
+
+
+def _should_exclude(
+ rel_posix: str,
+ name: str,
+ is_dir: bool,
+ gitignore: Sequence[Tuple[str, bool]],
+ *,
+ include_env: bool = False,
+) -> bool:
+ if name == ".env.example":
+ return False
+ if _is_secret_env(name) and not include_env:
+ return True
+ if name in _EXCLUDE_DIR_NAMES and is_dir:
+ return True
+ if any(fnmatch(name, glob) for glob in _EXCLUDE_NAME_GLOBS):
+ return True
+ if any(name.endswith(suffix) for suffix in _EXCLUDE_SUFFIXES):
+ return True
+ if name.endswith(".egg-info") or ".egg-info/" in rel_posix:
+ return True
+ if _matches_gitignore(rel_posix, gitignore):
+ return True
+ return False
+
+
+def collect_pack_files(root: str, *, include_env: bool = False) -> List[str]:
+ """Return posix-relative paths that would be included in a pack."""
+ gitignore = _load_gitignore_patterns(root)
+ included: List[str] = []
+ root = os.path.abspath(root)
+
+ for dirpath, dirnames, filenames in os.walk(root):
+ rel_dir = os.path.relpath(dirpath, root)
+ rel_dir_posix = "" if rel_dir == "." else rel_dir.replace("\\", "/")
+
+ kept_dirs = []
+ for dirname in dirnames:
+ child_rel = f"{rel_dir_posix}/{dirname}" if rel_dir_posix else dirname
+ if _should_exclude(child_rel, dirname, True, gitignore, include_env=include_env):
+ continue
+ kept_dirs.append(dirname)
+ dirnames[:] = kept_dirs
+
+ for filename in filenames:
+ child_rel = f"{rel_dir_posix}/{filename}" if rel_dir_posix else filename
+ if _should_exclude(child_rel, filename, False, gitignore, include_env=include_env):
+ continue
+ included.append(child_rel)
+
+ if ".env.example" not in included:
+ included.append(".env.example")
+ included.sort()
+ return included
+
+
+def _rmtree(path: str) -> None:
+ def _onerror(func, p, _exc):
+ try:
+ os.chmod(p, stat.S_IWRITE)
+ func(p)
+ except OSError:
+ pass
+
+ shutil.rmtree(path, onerror=_onerror)
+
+
+def _copy_selected(src_root: str, dest_root: str, files: Sequence[str]) -> None:
+ for rel in files:
+ if rel == ".env.example":
+ continue # handled separately so a stub can be created
+ src = os.path.join(src_root, rel.replace("/", os.sep))
+ dest = os.path.join(dest_root, rel.replace("/", os.sep))
+ if not os.path.isfile(src):
+ continue
+ os.makedirs(os.path.dirname(dest) or dest_root, exist_ok=True)
+ shutil.copy2(src, dest)
+
+
+def _collect_staging_bytes(src_root: str, *, include_env: bool = False) -> dict:
+ contents = {}
+ for dirpath, dirnames, filenames in os.walk(src_root):
+ dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_DIR_NAMES and not d.endswith(".egg-info")]
+ for filename in filenames:
+ if any(filename.endswith(suffix) for suffix in _EXCLUDE_SUFFIXES):
+ continue
+ if _is_secret_env(filename) and not include_env:
+ continue
+ full = os.path.join(dirpath, filename)
+ rel = os.path.relpath(full, src_root).replace("\\", "/")
+ with open(full, "rb") as handle:
+ contents[rel] = handle.read()
+ return contents
diff --git a/nitrostack/cli/_pack_metadata.py b/nitrostack/cli/_pack_metadata.py
new file mode 100644
index 0000000..bd59859
--- /dev/null
+++ b/nitrostack/cli/_pack_metadata.py
@@ -0,0 +1,159 @@
+"""Project identity, dependency declarations, and generated packaging metadata."""
+
+from __future__ import annotations
+
+import os
+import re
+from typing import Iterable, List, Optional, Sequence, Set, Tuple
+
+from nitrostack.cli._pack_files import _EXCLUDE_DIR_NAMES
+from nitrostack.cli._shared import (
+ parse_pyproject_dependencies, parse_requirements, read_text, requirement_name,
+)
+
+
+ENV_EXAMPLE_STUB = """PORT=8000
+NODE_ENV=development
+"""
+
+
+_PYPROJECT_TEMPLATE = """[build-system]
+requires = ["setuptools>=61.0.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "{name}"
+version = "{version}"
+description = "Packed NitroStack MCP server"
+requires-python = ">=3.10"
+dependencies = {deps}
+
+[tool.setuptools]
+py-modules = {py_modules}
+
+[tool.setuptools.packages.find]
+where = ["."]
+namespaces = true
+exclude = ["tests*", "venv*", "node_modules*", "src.widgets*"]
+
+[tool.setuptools.package-data]
+"*" = [".env.example", "requirements.txt", "*.md"]
+"""
+
+
+def _read_text(path: str) -> str:
+ return read_text(path)
+
+
+def _parse_pyproject_field(text: str, field: str) -> Optional[str]:
+ match = re.search(rf'^{field}\s*=\s*["\']([^"\']+)["\']', text, re.MULTILINE)
+ return match.group(1) if match else None
+
+
+def _parse_pyproject_dependencies(text: str) -> List[str]:
+ return parse_pyproject_dependencies(text)
+
+
+def _parse_requirements(path: str) -> List[str]:
+ return parse_requirements(path)
+
+
+def _project_name_and_version(root: str) -> Tuple[str, str]:
+ pyproject = os.path.join(root, "pyproject.toml")
+ if os.path.isfile(pyproject):
+ text = _read_text(pyproject)
+ name = _parse_pyproject_field(text, "name")
+ version = _parse_pyproject_field(text, "version")
+ if name and version:
+ return name, version
+ if name:
+ return name, version or "0.1.0"
+ return os.path.basename(os.path.abspath(root)) or "nitrostack-project", "0.1.0"
+
+
+def _normalize_dist_name(name: str) -> str:
+ normalized = re.sub(r"[-_.]+", "-", name).strip("-").lower()
+ return normalized or "nitrostack-project"
+
+
+def _pep503_wheel_name(name: str) -> str:
+ return re.sub(r"[-_.]+", "_", name)
+
+
+def _requirement_name(req: str) -> str:
+ return requirement_name(req)
+
+
+def requirements_from_project(root: str) -> List[str]:
+ pyproject = os.path.join(root, "pyproject.toml")
+ req_path = os.path.join(root, "requirements.txt")
+ deps: List[str] = []
+ name, _ = _project_name_and_version(root)
+ if os.path.isfile(pyproject):
+ deps = _parse_pyproject_dependencies(_read_text(pyproject))
+ if not deps and os.path.isfile(req_path):
+ deps = _parse_requirements(req_path)
+ deps = [item.lstrip("\ufeff").strip() for item in deps if item.lstrip("\ufeff").strip()]
+ has_nitrostack = any(_requirement_name(item) == "nitrostack" for item in deps)
+ if not has_nitrostack and name.lower() != "nitrostack":
+ from nitrostack.cli.vendor import runtime_nitrostack_requirement
+
+ deps = [runtime_nitrostack_requirement(), *deps]
+ from nitrostack.cli.vendor import apply_runtime_nitrostack_pins
+
+ return apply_runtime_nitrostack_pins(deps)
+
+
+def write_requirements_txt(root: str, deps: Sequence[str]) -> str:
+ path = os.path.join(root, "requirements.txt")
+ body = "".join(f"{dep}\n" for dep in deps) if deps else "nitrostack\n"
+ with open(path, "w", encoding="utf-8") as handle:
+ handle.write(body)
+ return path
+
+
+def _ensure_env_example(root: str) -> str:
+ path = os.path.join(root, ".env.example")
+ if not os.path.isfile(path):
+ with open(path, "w", encoding="utf-8") as handle:
+ handle.write(ENV_EXAMPLE_STUB)
+ return path
+
+
+def _discover_py_modules_and_packages(root: str) -> Tuple[List[str], List[str]]:
+ py_modules: List[str] = []
+ packages: Set[str] = set()
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_DIR_NAMES and not d.endswith(".egg-info")]
+ rel_dir = os.path.relpath(dirpath, root)
+ if rel_dir == ".":
+ for filename in filenames:
+ if filename.endswith(".py") and filename != "setup.py":
+ py_modules.append(os.path.splitext(filename)[0])
+ continue
+ parts = rel_dir.replace("\\", "/").split("/")
+ if any(part in _EXCLUDE_DIR_NAMES for part in parts):
+ continue
+ if any(filename.endswith(".py") for filename in filenames):
+ packages.add(".".join(parts))
+ return sorted(py_modules), sorted(packages)
+
+
+def _toml_list(values: Iterable[str]) -> str:
+ items = ", ".join(f'"{v}"' for v in values)
+ return f"[{items}]"
+
+
+def _ensure_pyproject(root: str, name: str, version: str, deps: Sequence[str]) -> None:
+ path = os.path.join(root, "pyproject.toml")
+ if os.path.isfile(path):
+ return
+ py_modules, _packages = _discover_py_modules_and_packages(root)
+ content = _PYPROJECT_TEMPLATE.format(
+ name=_normalize_dist_name(name),
+ version=version,
+ deps=_toml_list(deps),
+ py_modules=_toml_list(py_modules),
+ )
+ with open(path, "w", encoding="utf-8") as handle:
+ handle.write(content)
diff --git a/nitrostack/cli/_pack_wheel.py b/nitrostack/cli/_pack_wheel.py
new file mode 100644
index 0000000..929f30d
--- /dev/null
+++ b/nitrostack/cli/_pack_wheel.py
@@ -0,0 +1,155 @@
+"""Wheel assembly, backend fallback, and archive integrity for project packaging."""
+
+from __future__ import annotations
+
+import os
+import zipfile
+from typing import Callable, Optional, Sequence, Tuple
+
+from nitrostack.cli._pack_files import _collect_staging_bytes
+from nitrostack.cli._pack_metadata import _normalize_dist_name, _pep503_wheel_name
+
+
+def _sha256_record(data: bytes) -> str:
+ import base64
+ import hashlib
+
+ digest = hashlib.sha256(data).digest()
+ return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+
+
+def _inject_into_wheel(wheel_path: str, files: Sequence[Tuple[str, str]]) -> None:
+ """Add extra files to a built wheel and rewrite RECORD so the wheel stays valid."""
+ with zipfile.ZipFile(wheel_path, "r") as src:
+ contents = {name: src.read(name) for name in src.namelist()}
+
+ for arcname, source in files:
+ posix = arcname.replace("\\", "/")
+ if posix in contents or not os.path.isfile(source):
+ continue
+ with open(source, "rb") as handle:
+ contents[posix] = handle.read()
+
+ record_name = next((n for n in contents if n.endswith(".dist-info/RECORD")), None)
+ if record_name:
+ rows = []
+ for name in sorted(contents):
+ if name == record_name:
+ continue
+ data = contents[name]
+ rows.append(f"{name},{_sha256_record(data)},{len(data)}")
+ rows.append(f"{record_name},,")
+ contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8")
+
+ tmp_path = wheel_path + ".tmp"
+ with zipfile.ZipFile(tmp_path, "w", compression=zipfile.ZIP_DEFLATED) as dest:
+ for name, data in contents.items():
+ dest.writestr(name, data)
+ os.replace(tmp_path, wheel_path)
+
+
+def _is_valid_wheel(path: str) -> bool:
+ if not zipfile.is_zipfile(path):
+ return False
+ with zipfile.ZipFile(path, "r") as zf:
+ names = zf.namelist()
+ has_wheel = any(n.endswith(".dist-info/WHEEL") for n in names)
+ has_meta = any(n.endswith(".dist-info/METADATA") for n in names)
+ has_record = any(n.endswith(".dist-info/RECORD") for n in names)
+ if not (has_wheel and has_meta and has_record):
+ return False
+ wheel_name = next(n for n in names if n.endswith(".dist-info/WHEEL"))
+ body = zf.read(wheel_name).decode("utf-8", errors="replace")
+ return "Wheel-Version:" in body
+
+
+def _write_purelib_wheel(
+ src_root: str,
+ wheel_dir: str,
+ name: str,
+ version: str,
+ deps: Sequence[str],
+ *,
+ include_env: bool = False,
+) -> str:
+ """Write a PEP 427 py3-none-any wheel from the staged project files."""
+ os.makedirs(wheel_dir, exist_ok=True)
+ dist_name = _pep503_wheel_name(_normalize_dist_name(name))
+ display_name = _normalize_dist_name(name)
+ wheel_filename = f"{dist_name}-{version}-py3-none-any.whl"
+ wheel_path = os.path.join(wheel_dir, wheel_filename)
+ dist_info = f"{dist_name}-{version}.dist-info"
+
+ contents = _collect_staging_bytes(src_root, include_env=include_env)
+ metadata_lines = [
+ "Metadata-Version: 2.1",
+ f"Name: {display_name}",
+ f"Version: {version}",
+ "Summary: Packed NitroStack MCP server",
+ "Requires-Python: >=3.10",
+ ]
+ for dep in deps:
+ metadata_lines.append(f"Requires-Dist: {dep}")
+ contents[f"{dist_info}/METADATA"] = ("\n".join(metadata_lines) + "\n").encode("utf-8")
+ contents[f"{dist_info}/WHEEL"] = (
+ "Wheel-Version: 1.0\n"
+ "Generator: nitrostack-py pack\n"
+ "Root-Is-Purelib: true\n"
+ "Tag: py3-none-any\n"
+ ).encode("utf-8")
+
+ record_name = f"{dist_info}/RECORD"
+ rows = []
+ for arcname in sorted(contents):
+ data = contents[arcname]
+ rows.append(f"{arcname},{_sha256_record(data)},{len(data)}")
+ rows.append(f"{record_name},,")
+ contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8")
+
+ with zipfile.ZipFile(wheel_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
+ for arcname, data in contents.items():
+ zf.writestr(arcname, data)
+ return wheel_path
+
+
+def _setuptools_build_wheel(wheel_dir: str) -> str:
+ from setuptools.build_meta import build_wheel as setuptools_build_wheel
+ return setuptools_build_wheel(wheel_dir)
+
+
+def _build_wheel_with_setuptools(
+ src_root: str, wheel_dir: str, *, build_backend: Callable[[str], str],
+) -> Optional[str]:
+ """Use the setuptools PEP 517 backend when it is importable."""
+ os.makedirs(wheel_dir, exist_ok=True)
+ previous = os.getcwd()
+ try:
+ os.chdir(src_root)
+ filename = build_backend(wheel_dir)
+ except ImportError as exc:
+ print(f"Warning: setuptools build backend unavailable, falling back: {exc}")
+ return None
+ except Exception as exc:
+ print(f"Warning: setuptools build failed, falling back: {exc}")
+ return None
+ finally:
+ os.chdir(previous)
+ path = os.path.join(wheel_dir, filename)
+ return path if os.path.isfile(path) else None
+
+
+def _build_wheel(
+ src_root: str,
+ wheel_dir: str,
+ name: str,
+ version: str,
+ deps: Sequence[str],
+ *,
+ build_with_setuptools: Callable[[str, str], Optional[str]],
+ write_purelib: Callable[[str, str, str, str, Sequence[str]], str],
+) -> str:
+ os.makedirs(wheel_dir, exist_ok=True)
+ built = build_with_setuptools(src_root, wheel_dir)
+ if built:
+ return built
+ return write_purelib(src_root, wheel_dir, name, version, deps)
diff --git a/nitrostack/cli/_parser.py b/nitrostack/cli/_parser.py
new file mode 100644
index 0000000..4be23e9
--- /dev/null
+++ b/nitrostack/cli/_parser.py
@@ -0,0 +1,169 @@
+"""CLI argument declarations; dispatch stays in the public entry module."""
+
+import argparse
+import os
+
+
+def build_parser(*, _add_port_flags, OFFICIAL_TEMPLATES):
+ parser = argparse.ArgumentParser(
+ prog="nitrostack-py",
+ description="nitrostack-py CLI — Scaffold, develop, pack, and run NitroStack Python MCP servers",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog=(
+ "examples:\n"
+ " nitrostack-py init my-server\n"
+ " nitrostack-py generate guard MyGuard\n"
+ " nitrostack-py pack --dry-run\n"
+ " nitrostack-py upgrade --dry-run\n"
+ " nitrostack-py install --production\n"
+ " nitrostack-py validate\n"
+ ),
+ )
+ subparsers = parser.add_subparsers(dest="command", metavar="command")
+
+ # init command
+ init_parser = subparsers.add_parser("init", help="Initialize a new NitroStack MCP server project")
+ init_parser.add_argument("name", nargs="?", default=None, help="Name of the project directory (prompted if omitted)")
+ init_parser.add_argument(
+ "--template",
+ choices=list(OFFICIAL_TEMPLATES.keys()),
+ default=None,
+ help="Template to use: " + ", ".join(OFFICIAL_TEMPLATES) + " (default: interactive prompt)",
+ )
+ init_parser.add_argument("--skip-install", action="store_true", help="Skip installing Python (and widget npm) dependencies")
+ init_parser.add_argument(
+ "--force",
+ action="store_true",
+ help="Overwrite existing agent skill directories when installing",
+ )
+ _add_port_flags(init_parser)
+
+ # dev command
+ dev_parser = subparsers.add_parser("dev", help="Start the hot-reloading development server")
+ _add_port_flags(dev_parser)
+
+ # start command
+ start_parser = subparsers.add_parser("start", help="Start the production server")
+ _add_port_flags(start_parser)
+
+ # register command
+ reg_parser = subparsers.add_parser("register", help="Register server script inside Claude Desktop configuration")
+ reg_parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="Name of the server (defaults to folder name)")
+ reg_parser.add_argument("--file", default="main.py", help="Python script to register (defaults to main.py)")
+
+ # cursor command
+ cursor_parser = subparsers.add_parser("cursor", help="Register this server in Cursor MCP configuration")
+ cursor_parser.add_argument("--global", dest="global_config", action="store_true", help="Write to ~/.cursor/mcp.json")
+ cursor_parser.add_argument(
+ "--transport",
+ choices=("command", "streamable-http", "sse"),
+ default="command",
+ help="Connection type (default: command)",
+ )
+ cursor_parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="Name of the server")
+ cursor_parser.add_argument("--file", default="main.py", help="Python script to register for command transport")
+
+ # generate command
+ gen_parser = subparsers.add_parser(
+ "generate",
+ help="Generate boilerplate code (tool, module, guard, pipe, interceptor, filter, service)",
+ )
+ gen_subparsers = gen_parser.add_subparsers(dest="generator", metavar="type")
+
+ tool_parser = gen_subparsers.add_parser("tool", help="Generate a new tool boilerplate")
+ tool_parser.add_argument("name", help="Name of the tool")
+
+ mod_parser = gen_subparsers.add_parser("module", help="Generate a new module boilerplate")
+ mod_parser.add_argument("name", help="Name of the module")
+
+ for kind, kind_help in (
+ ("guard", "Generate an authorization guard"),
+ ("pipe", "Generate a validation/transform pipe"),
+ ("interceptor", "Generate an execution interceptor"),
+ ("filter", "Generate an exception filter"),
+ ("service", "Generate an injectable service"),
+ ):
+ kind_parser = gen_subparsers.add_parser(kind, help=kind_help)
+ kind_parser.add_argument("name", help=f"Name of the {kind}")
+
+ # pack command
+ pack_parser = subparsers.add_parser(
+ "pack",
+ help="Build a deployable wheel of the current project (excludes .env by default)",
+ )
+ pack_parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show files that would be packed without creating the artifact",
+ )
+ pack_parser.add_argument(
+ "--include-env",
+ action="store_true",
+ help="Include .env files in the wheel (use with caution!)",
+ )
+
+ # upgrade command
+ upgrade_parser = subparsers.add_parser(
+ "upgrade",
+ help="Update the nitrostack dependency to the latest (or a specific) PyPI version",
+ )
+ upgrade_parser.add_argument(
+ "--version",
+ dest="target_version",
+ metavar="X.Y.Z",
+ help="Pin nitrostack to this version instead of the latest PyPI release",
+ )
+ upgrade_parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show the version change without modifying pyproject.toml",
+ )
+ upgrade_parser.add_argument(
+ "--allow-downgrade",
+ action="store_true",
+ help="Allow --version to pin an older release than the one currently declared",
+ )
+
+ # install command
+ install_parser = subparsers.add_parser(
+ "install",
+ help="Install project dependencies from pyproject.toml / requirements.txt",
+ )
+ install_parser.add_argument(
+ "--production",
+ action="store_true",
+ help="Skip development dependencies (optional extras and requirements-dev.txt)",
+ )
+
+ # validate command
+ subparsers.add_parser(
+ "validate",
+ help="Lint project config, @mcp_app imports, and @module() class references",
+ )
+
+ login_parser = subparsers.add_parser(
+ "login",
+ help=(
+ "Record NitroCloud user identity for analytics "
+ "(alias anonymous id to Cloud user id)"
+ ),
+ )
+ login_parser.add_argument(
+ "--user-id",
+ required=True,
+ dest="user_id",
+ help="Stable NitroCloud user id",
+ )
+ login_parser.add_argument(
+ "--email",
+ required=True,
+ help="User email (e.g. user@example.com)",
+ )
+ login_parser.add_argument(
+ "--org-id",
+ default=None,
+ dest="org_id",
+ help="Organization id for group analytics (optional)",
+ )
+
+ return parser, gen_parser
diff --git a/nitrostack/cli/_project_init.py b/nitrostack/cli/_project_init.py
new file mode 100644
index 0000000..163ecd8
--- /dev/null
+++ b/nitrostack/cli/_project_init.py
@@ -0,0 +1,243 @@
+"""Project initialization and dependency setup."""
+
+import os
+import sys
+import shutil
+import subprocess
+import time
+
+from nitrostack.cli.telemetry import track_init_completed
+
+
+def init_project(
+ name: str = None,
+ template: str = None,
+ skip_install: bool = False,
+ port = None,
+ widget = None,
+ force: bool = False,
+ *,
+ DEFAULT_MCP_PORT,
+ DEFAULT_PROJECT_NAME,
+ DEFAULT_WIDGETS_PORT,
+ OFFICIAL_TEMPLATES,
+ _normalize_port,
+ _prompt,
+ _prompt_template,
+ _prompt_yes_no,
+ _resolve_template,
+ _run_npm,
+ _stdin_is_interactive,
+ _upsert_env_var,
+ ensure_python_widgets,
+ install_dependencies,
+ lock_with_uv,
+ print_banner,
+ rewrite_pyproject_identity,
+ run_skills_flow,
+):
+ print_banner()
+ init_started = time.monotonic()
+
+ # 1. Project name — optional CLI arg, otherwise the next readline
+ if not name:
+ name = _prompt("Project name", DEFAULT_PROJECT_NAME)
+ name = (name or "").strip()
+ if not name:
+ print("Error: Project name cannot be empty.")
+ sys.exit(1)
+
+ # 2. Overwrite check
+ if os.path.exists(name):
+ if not _stdin_is_interactive():
+ print(f"Error: Directory '{name}' already exists.")
+ sys.exit(1)
+ sys.stdout.write(f"\033[32m? \033[1;37mDirectory '{name}' already exists. Overwrite?\033[0m (Yes/No) [No]: ")
+ sys.stdout.flush()
+ ans = sys.stdin.readline().strip().lower()
+ if ans not in ("y", "yes"):
+ print("Initialization cancelled.")
+ sys.exit(0)
+ shutil.rmtree(name, ignore_errors=True)
+
+ # 3. Select template (explicit python-* names)
+ if not template:
+ template = _prompt_template()
+ else:
+ template = _resolve_template(template)
+
+ # 4. Description and Author (defaults when stdin is not a TTY)
+ description = _prompt("Description", "My awesome MCP server")
+ author = _prompt("Author", "developer")
+
+ # 5. Install dependencies (Y/n). --skip-install skips the prompt.
+ if skip_install:
+ install_deps = False
+ else:
+ install_deps = _prompt_yes_no("Install dependencies", default_yes=True)
+
+ mcp_port = _normalize_port(port, "--port") if port is not None else DEFAULT_MCP_PORT
+ widgets_port = _normalize_port(widget, "--widget") if widget is not None else DEFAULT_WIDGETS_PORT
+
+ # 6. Copy template directory
+ import nitrostack
+ package_dir = os.path.dirname(nitrostack.__file__)
+ template_dir = OFFICIAL_TEMPLATES[template]
+ template_src_dir = os.path.join(package_dir, "templates", template_dir)
+
+ if not os.path.exists(template_src_dir):
+ print(f"Error: Template '{template}' not found at '{template_src_dir}'.")
+ sys.exit(1)
+
+ shutil.copytree(template_src_dir, name)
+ rewrite_pyproject_identity(
+ os.path.join(name, "pyproject.toml"),
+ name=os.path.basename(os.path.abspath(name)),
+ description=description,
+ )
+ from nitrostack.cli.vendor import ensure_vendored_nitrostack
+ ensure_vendored_nitrostack(name)
+ lock_with_uv(name)
+ widget_routes = ensure_python_widgets(name)
+ print("\n\033[32m✓\033[0m Project created")
+ if widget_routes:
+ print(f"\033[32m✓\033[0m Python widgets: {', '.join(widget_routes)}")
+ print(" HTML in widgets/out/ — preview: widgets/preview.html")
+
+ # 7. Update .env file
+ env_path = os.path.join(name, ".env")
+ env_example_path = os.path.join(name, ".env.example")
+ if not os.path.exists(env_path) and os.path.isfile(env_example_path):
+ shutil.copyfile(env_example_path, env_path)
+ if os.path.exists(env_path):
+ with open(env_path, "r", encoding="utf-8") as f:
+ lines = f.readlines()
+ new_lines = []
+ for line in lines:
+ if line.startswith("SERVER_NAME="):
+ new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n')
+ elif line.startswith("SERVER_DESC="):
+ new_lines.append(f'SERVER_DESC="{description}"\n')
+ elif line.startswith("SERVER_AUTHOR="):
+ new_lines.append(f'SERVER_AUTHOR="{author}"\n')
+ else:
+ new_lines.append(line)
+ has_name = any(line.startswith("SERVER_NAME=") for line in new_lines)
+ has_desc = any(line.startswith("SERVER_DESC=") for line in new_lines)
+ has_author = any(line.startswith("SERVER_AUTHOR=") for line in new_lines)
+ if not has_name:
+ new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n')
+ if not has_desc:
+ new_lines.append(f'SERVER_DESC="{description}"\n')
+ if not has_author:
+ new_lines.append(f'SERVER_AUTHOR="{author}"\n')
+ new_lines = _upsert_env_var(new_lines, "PORT", mcp_port)
+ new_lines = _upsert_env_var(new_lines, "WIDGETS_DEV_PORT", widgets_port)
+ new_lines = _upsert_env_var(new_lines, "NITROSTACK_APP_MODE", "openai")
+ with open(env_path, "w", encoding="utf-8") as f:
+ f.writelines(new_lines)
+
+ # 8. Update widgets package.json
+ widgets_package_path = os.path.join(name, "src", "widgets", "package.json")
+ if os.path.exists(widgets_package_path):
+ import json
+ try:
+ with open(widgets_package_path, "r", encoding="utf-8") as f:
+ pkg = json.load(f)
+ pkg["name"] = f"{name}-widgets"
+ # The port is passed once by the CLI (`npm run dev -- --port N`), so it
+ # is deliberately not baked into the script.
+ scripts = pkg.setdefault("scripts", {})
+ scripts["dev"] = "next dev"
+ scripts["start"] = "next start"
+ with open(widgets_package_path, "w", encoding="utf-8") as f:
+ json.dump(pkg, f, indent=2)
+ except Exception:
+ pass
+
+ # 9. Install Python deps (requirements.txt / pyproject.toml), then widget npm if present.
+ if install_deps:
+ print("Installing dependencies...")
+ try:
+ install_dependencies(cwd=name)
+ print("\033[32m✓\033[0m Dependencies installed")
+ except Exception as e:
+ print(f"Warning: Failed to install dependencies: {e}")
+ print("Please run 'nitrostack-py install' from the project directory.\n")
+ widgets_dir = os.path.join(name, "src", "widgets")
+ if os.path.exists(widgets_dir):
+ print("Installing widget dependencies...")
+ try:
+ _run_npm(["--version"], capture_output=True, check=True, text=True)
+ _run_npm(["install"], cwd=widgets_dir, check=True)
+ print("\033[32m✓\033[0m Widget dependencies installed\n")
+ except FileNotFoundError as e:
+ print(f"Warning: {e}")
+ print("Please run 'npm install' inside 'src/widgets' manually.\n")
+ except subprocess.CalledProcessError as e:
+ detail = (getattr(e, "stderr", None) or getattr(e, "stdout", None) or str(e)).strip()
+ print(f"Warning: Failed to install widget dependencies: {detail}")
+ print("Please run 'npm install' inside 'src/widgets' manually.\n")
+ else:
+ print("\033[32m✓\033[0m Skipped dependency install")
+
+ run_skills_flow(os.path.abspath(name), force=force)
+
+ # Success Card
+ abs_path = os.path.abspath(name)
+ success_box = f"""\033[36m╔══════════════════════════════════════════════════════════╗
+║ \033[32m✓ Project Ready\033[36m ║
+║ ║
+║ Name: {name:<48} ║
+║ Template: {template:<44} ║
+║ Path: {abs_path:<48} ║
+╚══════════════════════════════════════════════════════════╝\033[0m"""
+ print(success_box)
+
+ # Next Steps
+ print("\n\033[1;37mNext steps:\033[0m")
+ print(f" 1. \033[34mcd {name}\033[0m")
+ if template in ("python-enterprise-search", "python-code-mode"):
+ print(" 2. Read README.md for sample tool calls and local demonstration data")
+ print(" 3. Validate the project: nitrostack-py validate")
+ print(" 4. Install dependencies if skipped: nitrostack-py install")
+ print(" 5. Start an MCP stdio server: python main.py")
+ print(" For HTTP set MCP_TRANSPORT_TYPE=http, then connect to http://localhost:3000/mcp")
+ if template == "python-code-mode":
+ print(" Try scripts/sample-batch.js through execute; QuickJS must be installed")
+ else:
+ print(" Try search_tools with 'overdue invoices', then invoke it through call_tool")
+ print("\nHappy coding! 🚀\n")
+ duration_ms = int((time.monotonic() - init_started) * 1000)
+ track_init_completed(
+ template=template,
+ skip_install=skip_install,
+ duration_ms=duration_ms,
+ has_custom_description=description.strip() != "My awesome MCP server",
+ )
+ return
+ if template == "python-oauth":
+ print(" 2. Configure OAuth credentials in your \033[34m.env\033[0m file")
+ print(" See \033[34mOAUTH_SETUP.md\033[0m for provider guides")
+ else:
+ print(" 2. Configure environment variables in \033[34m.env\033[0m")
+ print(" 3. Start development server: \033[34mnitrostack-py dev\033[0m (or `python -m nitrostack.cli.main dev`)")
+ print(" 4. Preview widgets: \033[34mhttp://localhost:3000/widgets/preview\033[0m (server running)")
+ print(" Static file (manual JSON): \033[34mopen widgets/preview.html\033[0m")
+ print(
+ " 5. Inspector (HTTP): \033[34mMCP_TRANSPORT_TYPE=http MCP_STATELESS=true "
+ "NITROSTACK_APP_MODE=universal python main.py\033[0m"
+ )
+ print(" Connect Streamable HTTP to \033[34mhttp://localhost:3000/mcp\033[0m with \033[34mAuthentication = Off\033[0m")
+ print(" Apps tab renders the widget from live \033[34mstructuredContent\033[0m (not widgets/preview.html)")
+ print(" For open shops only set \033[34mopenNow=true\033[0m (list) or \033[34mfilter=open_now\033[0m (map)")
+ print(" 6. NitroStudio cannot folder-connect a Python project (it looks for @nitrostack/core).")
+ print(" Use Inspector HTTP as above, or Studio's custom MCP URL if it offers Streamable HTTP.")
+ print("\nHappy coding! 🚀\n")
+ duration_ms = int((time.monotonic() - init_started) * 1000)
+ track_init_completed(
+ template=template,
+ skip_install=skip_install,
+ duration_ms=duration_ms,
+ has_custom_description=description.strip() != "My awesome MCP server",
+ )
diff --git a/nitrostack/cli/_registration.py b/nitrostack/cli/_registration.py
new file mode 100644
index 0000000..08a21b4
--- /dev/null
+++ b/nitrostack/cli/_registration.py
@@ -0,0 +1,155 @@
+"""Claude Desktop and Cursor client registration."""
+
+import os
+import sys
+
+
+def get_claude_config_paths():
+ paths = []
+ home = os.path.expanduser("~")
+
+ # Windows
+ if sys.platform == "win32":
+ appdata = os.environ.get("APPDATA")
+ if appdata:
+ paths.append(os.path.join(appdata, "Claude", "claude_desktop_config.json"))
+ # Windows Store app path
+ localappdata = os.environ.get("LOCALAPPDATA")
+ if localappdata:
+ store_dir = os.path.join(localappdata, "Packages")
+ if os.path.exists(store_dir):
+ try:
+ for folder in os.listdir(store_dir):
+ if folder.startswith("Claude_"):
+ paths.append(os.path.join(store_dir, folder, "LocalCache", "Roaming", "Claude", "claude_desktop_config.json"))
+ except Exception:
+ pass
+ # macOS
+ elif sys.platform == "darwin":
+ paths.append(os.path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"))
+ # Linux
+ else:
+ paths.append(os.path.join(home, ".config", "Claude", "claude_desktop_config.json"))
+
+ return [p for p in paths if os.path.exists(os.path.dirname(p))]
+
+def register_server(name: str, file_path: str, *, _build_server_entry, get_claude_config_paths):
+ import json
+
+ if not os.path.exists(file_path):
+ print(f"Error: Script file '{file_path}' does not exist.")
+ sys.exit(1)
+
+ server_entry = _build_server_entry(file_path)
+
+ config_paths = get_claude_config_paths()
+ if not config_paths:
+ print("Error: Could not find any Claude Desktop installation directories.")
+ print("Please ensure Claude Desktop is installed on your machine.")
+ sys.exit(1)
+
+ registered_any = False
+ for path in config_paths:
+ try:
+ config = {}
+ if os.path.exists(path):
+ with open(path, "r", encoding="utf-8") as f:
+ content = f.read().strip()
+ if content:
+ try:
+ config = json.loads(content)
+ except json.JSONDecodeError:
+ print(f"Warning: Configuration file at '{path}' is not valid JSON. Resetting it.")
+
+ if "mcpServers" not in config:
+ config["mcpServers"] = {}
+
+ config["mcpServers"][name] = server_entry
+
+ # Create directory if needed
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(config, f, indent=2)
+
+ print(f"Successfully registered server '{name}' in: {path}")
+ registered_any = True
+ except Exception as e:
+ print(f"Error writing to config at '{path}': {e}")
+
+ if registered_any:
+ print("\nAll done! Please fully restart Claude Desktop to load your new server.")
+ else:
+ print("Error: Failed to register the server in any configuration files.")
+
+def _build_server_entry(file_path: str):
+ """Build the stdio server entry shared by register and Cursor configs."""
+ return {
+ "command": sys.executable,
+ "args": [os.path.abspath(file_path)],
+ }
+
+def _write_json_atomic(path: str, data):
+ """Replace a JSON config atomically so readers never see a partial write."""
+ import json
+ import tempfile
+
+ directory = os.path.dirname(path)
+ os.makedirs(directory, exist_ok=True)
+ fd, temp_path = tempfile.mkstemp(prefix=".mcp-", suffix=".tmp", dir=directory)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2)
+ f.write("\n")
+ os.replace(temp_path, path)
+ except Exception:
+ try:
+ os.unlink(temp_path)
+ except OSError:
+ pass
+ raise
+
+def register_cursor_server(
+ name: str,
+ file_path: str = 'main.py',
+ *,
+ global_config: bool = False,
+ transport: str = 'command',
+ _build_server_entry,
+ _write_json_atomic,
+):
+ """Merge this project into Cursor's project or user MCP configuration."""
+ import json
+
+ if transport not in ("command", "streamable-http", "sse"):
+ raise ValueError("transport must be command, streamable-http, or sse")
+ if transport == "command" and not os.path.exists(file_path):
+ print(f"Error: Script file '{file_path}' does not exist.")
+ sys.exit(1)
+
+ if global_config:
+ config_path = os.path.join(os.path.expanduser("~"), ".cursor", "mcp.json")
+ else:
+ config_path = os.path.join(os.getcwd(), ".cursor", "mcp.json")
+
+ config = {}
+ if os.path.exists(config_path):
+ try:
+ with open(config_path, "r", encoding="utf-8") as f:
+ config = json.load(f)
+ except (json.JSONDecodeError, OSError):
+ config = {}
+ if not isinstance(config, dict):
+ config = {}
+ servers = config.get("mcpServers")
+ if not isinstance(servers, dict):
+ servers = {}
+ config["mcpServers"] = servers
+
+ if transport == "command":
+ entry = _build_server_entry(file_path)
+ else:
+ route = "mcp" if transport == "streamable-http" else "sse"
+ entry = {"url": f"http://localhost:3000/{route}"}
+ servers[name] = entry
+ _write_json_atomic(config_path, config)
+ print(f"Successfully registered server '{name}' in Cursor config: {config_path}")
diff --git a/nitrostack/cli/_runtime.py b/nitrostack/cli/_runtime.py
new file mode 100644
index 0000000..d5d8340
--- /dev/null
+++ b/nitrostack/cli/_runtime.py
@@ -0,0 +1,112 @@
+"""Runtime ports, environment settings and npm launch helpers."""
+
+import os
+import sys
+import shutil
+import subprocess
+
+
+def _normalize_port(value, label):
+ try:
+ port = int(value)
+ except (TypeError, ValueError):
+ print(f"Error: Invalid {label} '{value}'.")
+ sys.exit(1)
+ if port < 1 or port > 65535:
+ print(f"Error: {label} {port} is out of range (1-65535).")
+ sys.exit(1)
+ return str(port)
+
+def _read_project_env():
+ values = {}
+ env_path = os.path.join(os.getcwd(), ".env")
+ if not os.path.exists(env_path):
+ return values
+ try:
+ with open(env_path, encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, _, val = line.partition("=")
+ values[key.strip()] = val.strip().strip('"').strip("'")
+ except Exception:
+ pass
+ return values
+
+def _resolve_runtime_ports(
+ port = None,
+ widget = None,
+ *,
+ DEFAULT_MCP_PORT,
+ DEFAULT_WIDGETS_PORT,
+ _normalize_port,
+ _read_project_env,
+):
+ """Resolve MCP and widget ports. Explicit --port/--widget flags override defaults."""
+ project_env = _read_project_env()
+ if port is not None:
+ mcp_port = _normalize_port(port, "--port")
+ else:
+ mcp_port = (
+ os.environ.get("PORT")
+ or os.environ.get("MCP_SERVER_PORT")
+ or project_env.get("PORT")
+ or project_env.get("MCP_SERVER_PORT")
+ or DEFAULT_MCP_PORT
+ )
+ mcp_port = str(mcp_port)
+ if widget is None and mcp_port == DEFAULT_WIDGETS_PORT:
+ mcp_port = DEFAULT_MCP_PORT
+
+ if widget is not None:
+ widgets_port = _normalize_port(widget, "--widget")
+ else:
+ widgets_port = os.environ.get("WIDGETS_DEV_PORT") or project_env.get("WIDGETS_DEV_PORT") or DEFAULT_WIDGETS_PORT
+ widgets_port = str(widgets_port)
+ if port is None and widgets_port == DEFAULT_MCP_PORT:
+ widgets_port = DEFAULT_WIDGETS_PORT
+ return mcp_port, widgets_port
+
+def _upsert_env_var(lines, key, value):
+ prefix = f"{key}="
+ updated = False
+ new_lines = []
+ for line in lines:
+ if line.startswith(prefix):
+ new_lines.append(f"{key}={value}\n")
+ updated = True
+ else:
+ new_lines.append(line)
+ if not updated:
+ new_lines.append(f"{key}={value}\n")
+ return new_lines
+
+def _find_npm():
+ npm = shutil.which("npm") or shutil.which("npm.cmd")
+ if not npm:
+ raise FileNotFoundError(
+ "npm was not found on PATH. Install Node.js (https://nodejs.org) and retry."
+ )
+ return npm
+
+def _run_npm(args, *, _find_npm, **kwargs):
+ """Run npm without shell=True. A list + shell=True is treated as `sh -c npm` and drops flags."""
+ kwargs.pop("shell", None)
+ return subprocess.run([_find_npm(), *args], **kwargs)
+
+def _popen_npm(args, *, _find_npm, **kwargs):
+ kwargs.pop("shell", None)
+ return subprocess.Popen([_find_npm(), *args], **kwargs)
+
+def _add_port_flags(parser, *, DEFAULT_MCP_PORT, DEFAULT_WIDGETS_PORT):
+ parser.add_argument(
+ "--port",
+ default=None,
+ help=f"MCP HTTP port (default: {DEFAULT_MCP_PORT}; overrides PORT when set)",
+ )
+ parser.add_argument(
+ "--widget",
+ default=None,
+ help=f"Widget dev server port (default: {DEFAULT_WIDGETS_PORT}; overrides WIDGETS_DEV_PORT when set)",
+ )
diff --git a/nitrostack/cli/_scaffolding.py b/nitrostack/cli/_scaffolding.py
new file mode 100644
index 0000000..ab3ef35
--- /dev/null
+++ b/nitrostack/cli/_scaffolding.py
@@ -0,0 +1,53 @@
+"""Tool and module generation commands."""
+
+import os
+import sys
+
+
+def generate_tool(
+ name: str,
+ *,
+ TOOL_TEMPLATE,
+ _assert_dest_inside_root,
+ _sanitize_widget_route,
+ _validate_generate_name,
+ write_widget_html,
+ write_widget_preview,
+):
+ # Both validators run before anything is written. `_validate_generate_name` and
+ # `_sanitize_widget_route` accept overlapping-but-different character sets (e.g.
+ # `_foo` is a valid identifier but not a valid route; `my-tool` is the reverse),
+ # so validating the route lazily inside `write_widget_html` would leave an orphan
+ # `{name}_tool.py` behind whenever the two disagree — and that orphan then blocks
+ # any retry with "File already exists".
+ try:
+ name = _validate_generate_name(name)
+ _sanitize_widget_route(name)
+ except ValueError as exc:
+ print(f"Error: {exc}")
+ sys.exit(1)
+ filename = f"{name}_tool.py"
+ dest_py = os.path.abspath(filename)
+ try:
+ _assert_dest_inside_root(dest_py, os.getcwd())
+ except ValueError as exc:
+ print(f"Error: {exc}")
+ sys.exit(1)
+ if os.path.exists(filename):
+ print(f"Error: File '{filename}' already exists.")
+ sys.exit(1)
+ camel_name = "".join(part.capitalize() for part in name.split("_"))
+ content = TOOL_TEMPLATE.format(name=name, camel_name=camel_name)
+ with open(filename, "w", encoding="utf-8") as f:
+ f.write(content)
+ try:
+ html_path = write_widget_html(".", name, overwrite=False)
+ except ValueError as exc:
+ print(f"Error: {exc}")
+ sys.exit(1)
+ write_widget_preview(".")
+ print(f"Generated tool boilerplate in '{filename}'")
+ print(f"Generated widget HTML in '{html_path}'")
+
+def generate_module(name: str, *, generate_module_from_template):
+ generate_module_from_template(name)
diff --git a/nitrostack/cli/_servers.py b/nitrostack/cli/_servers.py
new file mode 100644
index 0000000..8bc0930
--- /dev/null
+++ b/nitrostack/cli/_servers.py
@@ -0,0 +1,284 @@
+"""Development and production process lifecycles."""
+
+import os
+import signal
+import sys
+import subprocess
+import time
+
+_DEV_SKIP_DIR_PARTS = frozenset(
+ {
+ "venv",
+ "env",
+ "__pycache__",
+ ".git",
+ ".pytest_cache",
+ "nitrostack.egg-info",
+ "vendor",
+ "node_modules",
+ }
+)
+_CHILD_GRACE_SECONDS = 12
+
+
+def _path_parts(path) -> list[str]:
+ return [part for part in os.path.normpath(os.fspath(path)).split(os.sep) if part]
+
+
+def _watched_project_path(path, watched_extensions: set[str]) -> bool:
+ fspath = os.fspath(path)
+ ext = os.path.splitext(fspath)[1]
+ if ext not in watched_extensions:
+ return False
+ parts = _path_parts(path)
+ basename = parts[-1] if parts else ""
+ if basename == ".env":
+ return True
+ return not any(
+ part in _DEV_SKIP_DIR_PARTS or (part.startswith(".") and part not in {".", ".env"})
+ for part in parts
+ )
+
+
+def _skip_polling_root(root: str) -> bool:
+ rel = os.path.normpath(root)
+ if rel in (".", ""):
+ return False
+ parts = [part for part in rel.split(os.sep) if part and part != "."]
+ return any(part.startswith(".") or part in _DEV_SKIP_DIR_PARTS for part in parts)
+
+
+def _own_group(process: subprocess.Popen) -> int | None:
+ """The child's process group, only when it leads one we created.
+
+ Never return our own group (or init's): signalling it would kill this CLI,
+ and on CI the runner itself.
+ """
+ if sys.platform == "win32":
+ return None
+ pid = getattr(process, "pid", None)
+ if type(pid) is not int or pid <= 1:
+ return None
+ try:
+ pgid = os.getpgid(pid)
+ except OSError:
+ return None
+ if pgid != pid or pgid == os.getpgrp():
+ return None
+ return pgid
+
+
+def _signal_child(process: subprocess.Popen, *, force: bool) -> None:
+ pgid = _own_group(process)
+ if pgid is not None:
+ os.killpg(pgid, signal.SIGKILL if force else signal.SIGTERM)
+ elif force:
+ process.kill()
+ else:
+ process.terminate()
+
+
+def _stop_child(process: subprocess.Popen | None) -> None:
+ if process is None or process.poll() is not None:
+ return
+ try:
+ _signal_child(process, force=False)
+ except (ProcessLookupError, OSError, AttributeError):
+ try:
+ process.terminate()
+ except Exception:
+ pass
+ try:
+ process.wait(timeout=_CHILD_GRACE_SECONDS)
+ return
+ except subprocess.TimeoutExpired:
+ pass
+ try:
+ _signal_child(process, force=True)
+ except (ProcessLookupError, OSError, AttributeError):
+ try:
+ process.kill()
+ except Exception:
+ pass
+ try:
+ process.wait(timeout=3)
+ except Exception:
+ pass
+
+
+def run_dev(port=None, widget=None, *, _popen_npm, _resolve_runtime_ports):
+ target = "main.py"
+ if not os.path.exists(target):
+ print("Error: main.py not found in current directory.")
+ sys.exit(1)
+
+ mcp_port, widgets_port = _resolve_runtime_ports(port, widget)
+
+ print(f"Starting hot-reload development server for {target}...")
+ print(f"MCP server port: {mcp_port}")
+ process = None
+ widgets_process = None
+
+ # Check if Next.js widgets are present
+ widgets_dir = os.path.join(os.getcwd(), "src", "widgets")
+ has_widgets = os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json"))
+ if has_widgets:
+ print(f"Starting widget development server on port {widgets_port}...")
+ try:
+ widgets_process = _popen_npm(
+ ["run", "dev", "--", "--port", str(widgets_port)],
+ cwd=widgets_dir,
+ )
+ except Exception as e:
+ print(f"Warning: Could not start widget development server: {e}")
+
+ def start_process():
+ nonlocal process
+ _stop_child(process)
+ env = os.environ.copy()
+ env["PYTHONPATH"] = os.path.abspath(".")
+ env["PORT"] = mcp_port
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
+ if has_widgets:
+ env["WIDGETS_DEV_PORT"] = str(widgets_port)
+ # Inherit stdout/stderr so server logs and tracebacks stay visible.
+ popen_kwargs = {"env": env, "cwd": os.getcwd()}
+ if sys.platform == "win32":
+ process = subprocess.Popen([sys.executable, target], **popen_kwargs)
+ else:
+ process = subprocess.Popen(
+ [sys.executable, target],
+ start_new_session=True,
+ **popen_kwargs,
+ )
+
+ def cleanup():
+ nonlocal process, widgets_process
+ _stop_child(process)
+ process = None
+ if widgets_process:
+ try:
+ widgets_process.terminate()
+ widgets_process.wait(timeout=5)
+ except Exception:
+ try:
+ widgets_process.kill()
+ except Exception:
+ pass
+
+ try:
+ start_process()
+
+ watched_extensions = {".py", ".env"}
+
+ def get_mtimes():
+ mtimes = {}
+ for root, _, files in os.walk("."):
+ if _skip_polling_root(root):
+ continue
+ for file in files:
+ ext = os.path.splitext(file)[1]
+ if ext in watched_extensions:
+ path = os.path.join(root, file)
+ if _watched_project_path(path, watched_extensions):
+ try:
+ mtimes[path] = os.path.getmtime(path)
+ except Exception:
+ pass
+ return mtimes
+
+ # Try using watchfiles for high-performance, low-CPU file monitoring
+ try:
+ from watchfiles import watch
+ print("Using watchfiles for high-performance file monitoring.")
+
+ while True:
+ for changes in watch("."):
+ should_restart = False
+ for _change_type, path in changes:
+ if _watched_project_path(path, watched_extensions):
+ should_restart = True
+ break
+ if should_restart:
+ print("File changes detected! Restarting server...")
+ start_process()
+ if process and process.poll() is not None:
+ print("Server process exited. Waiting for file changes to restart...")
+
+ except ImportError:
+ print("watchfiles library not found. Falling back to standard polling...")
+ last_mtimes = get_mtimes()
+ try:
+ while True:
+ time.sleep(1)
+ if process and process.poll() is not None:
+ print("Server process exited. Waiting for file changes to restart...")
+ current_mtimes = get_mtimes()
+ changed = False
+ if set(current_mtimes.keys()) != set(last_mtimes.keys()):
+ changed = True
+ else:
+ for path, mtime in current_mtimes.items():
+ if last_mtimes.get(path) != mtime:
+ changed = True
+ break
+ if changed:
+ print("File changes detected! Restarting server...")
+ start_process()
+ last_mtimes = current_mtimes
+ except KeyboardInterrupt:
+ pass
+ except KeyboardInterrupt:
+ print("\nStopping development server...")
+ cleanup()
+
+
+def run_start(port=None, widget=None, *, _popen_npm, _resolve_runtime_ports):
+ target = "main.py"
+ if not os.path.exists(target):
+ print("Error: main.py not found in current directory.")
+ sys.exit(1)
+
+ mcp_port, widgets_port = _resolve_runtime_ports(port, widget)
+
+ print(f"Starting production server for {target}...")
+ print(f"MCP HTTP: http://localhost:{mcp_port}/mcp")
+ env = os.environ.copy()
+ env["PYTHONPATH"] = os.path.abspath(".")
+ env["PORT"] = mcp_port
+ env["WIDGETS_DEV_PORT"] = widgets_port
+ env["NODE_ENV"] = "production"
+ # Select HTTP explicitly rather than letting NODE_ENV=production fall through
+ # to dual. Dual shuts HTTP down when STDIO reaches EOF, so `start` would exit
+ # immediately wherever stdin is not held open (Docker without -i, systemd, CI).
+ # `setdefault` keeps an explicit MCP_TRANSPORT_TYPE from the caller.
+ env.setdefault("MCP_TRANSPORT_TYPE", "http")
+
+ widgets_dir = os.path.join(os.getcwd(), "src", "widgets")
+ widgets_process = None
+ if os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json")):
+ # `next start` needs a production build; Popen would succeed and the child
+ # would fail with a bare "Could not find a production build", so check here.
+ if not os.path.exists(os.path.join(widgets_dir, ".next")):
+ print("Widgets are not built yet — skipping the widget server.")
+ print("Run 'npm run build' inside 'src/widgets', then retry.\n")
+ else:
+ print(f"Starting widget server on port {widgets_port}...")
+ try:
+ widgets_process = _popen_npm(
+ ["run", "start", "--", "--port", str(widgets_port)],
+ cwd=widgets_dir,
+ )
+ except Exception as e:
+ print(f"Warning: Could not start widget server: {e}")
+
+ try:
+ subprocess.run([sys.executable, target], env=env)
+ except KeyboardInterrupt:
+ print("\nStopping server...")
+ finally:
+ if widgets_process:
+ try:
+ widgets_process.terminate()
+ except Exception:
+ pass
\ No newline at end of file
diff --git a/nitrostack/cli/_template_text.py b/nitrostack/cli/_template_text.py
new file mode 100644
index 0000000..4c08fa8
--- /dev/null
+++ b/nitrostack/cli/_template_text.py
@@ -0,0 +1,34 @@
+"""Compatibility template strings, stored as package text assets."""
+
+from importlib.resources import files
+
+
+def _read(name: str) -> str:
+ return files("nitrostack.cli.templates").joinpath(name).read_text(encoding="utf-8")
+
+
+MAIN_TEMPLATE = _read("legacy_main_template.txt")
+APP_MODULE_TEMPLATE = _read("legacy_app_module_template.txt")
+CALC_MODULE_TEMPLATE = _read("legacy_calc_module_template.txt")
+CALC_SERVICE_TEMPLATE = _read("legacy_calc_service_template.txt")
+CALC_TOOLS_TEMPLATE = _read("legacy_calc_tools_template.txt")
+FOOD_APP_MODULE_TEMPLATE = _read("legacy_food_app_module_template.txt")
+FOOD_DELIVERY_MODULE_TEMPLATE = _read("legacy_food_delivery_module_template.txt")
+FOOD_DELIVERY_SERVICE_TEMPLATE = _read("legacy_food_delivery_service_template.txt")
+FOOD_DELIVERY_TOOLS_TEMPLATE = _read("legacy_food_delivery_tools_template.txt")
+FLIGHT_APP_MODULE_TEMPLATE = _read("legacy_flight_app_module_template.txt")
+FLIGHT_OAUTH_GUARD_TEMPLATE = _read("legacy_flight_oauth_guard_template.txt")
+FLIGHT_SYSTEM_HEALTH_TEMPLATE = _read("legacy_flight_system_health_template.txt")
+FLIGHT_DUFFEL_SERVICE_TEMPLATE = _read("legacy_flight_duffel_service_template.txt")
+FLIGHT_MODULE_TEMPLATE = _read("legacy_flight_module_template.txt")
+FLIGHT_TOOLS_TEMPLATE = _read("legacy_flight_tools_template.txt")
+FLIGHT_BOOKING_TOOLS_TEMPLATE = _read("legacy_flight_booking_tools_template.txt")
+FLIGHT_PROMPTS_TEMPLATE = _read("legacy_flight_prompts_template.txt")
+FLIGHT_RESOURCES_TEMPLATE = _read("legacy_flight_resources_template.txt")
+OAUTH_SETUP_TEMPLATE = _read("legacy_oauth_setup_template.txt")
+ENV_TEMPLATE = _read("legacy_env_template.txt")
+REQUIREMENTS_TEMPLATE = _read("legacy_requirements_template.txt")
+TOOL_TEMPLATE = _read("legacy_tool_template.txt")
+WIDGET_PREVIEW_HTML = _read("legacy_widget_preview_html.txt")
+SAMPLE_PIZZA_PREVIEW_JSON = _read("legacy_sample_pizza_preview_json.txt")
+MODULE_TEMPLATE = _read("legacy_module_template.txt")
diff --git a/nitrostack/cli/_widgets.py b/nitrostack/cli/_widgets.py
new file mode 100644
index 0000000..2a9e391
--- /dev/null
+++ b/nitrostack/cli/_widgets.py
@@ -0,0 +1,131 @@
+"""Widget scaffolding and safe output paths."""
+
+import os
+import re
+from pathlib import Path
+
+
+_GENERATE_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+_WIDGET_ROUTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
+
+
+def _validate_generate_name(name: str) -> str:
+ """Reject path segments so ``generate tool ../../ESCAPED`` cannot write outside cwd."""
+ name = (name or "").strip()
+ if not name or os.path.basename(name) != name or ".." in name or not _GENERATE_NAME_RE.fullmatch(name):
+ raise ValueError(
+ "name must be a Python identifier (letters, digits, underscore) "
+ "and cannot contain path separators"
+ )
+ return name
+
+def _sanitize_widget_route(route: str) -> str:
+ route = (route or "").strip()
+ if not route or os.path.basename(route) != route or ".." in route or not _WIDGET_ROUTE_RE.fullmatch(route):
+ raise ValueError("widget route must be a single alphanumeric path segment")
+ return route
+
+def _assert_dest_inside_root(dest: str, root: str) -> str:
+ dest_abs = os.path.realpath(dest)
+ root_abs = os.path.realpath(root)
+ try:
+ common = os.path.commonpath([dest_abs, root_abs])
+ except ValueError as exc:
+ raise ValueError("generated path would escape the project directory") from exc
+ if common != root_abs:
+ raise ValueError("generated path would escape the project directory")
+ return dest_abs
+
+def write_widget_html(
+ project_dir: str,
+ route: str,
+ *,
+ overwrite: bool = False,
+ _assert_dest_inside_root,
+ _sanitize_widget_route,
+) -> str:
+ """Write ``widgets/out/{route}.html`` if missing (Python-only static widget)."""
+ from nitrostack.widgets.route_templates import build_widget_html_for_route
+
+ route = _sanitize_widget_route(route)
+ project_dir = os.path.abspath(project_dir or ".")
+ out_dir = os.path.join(project_dir, "widgets", "out")
+ os.makedirs(out_dir, exist_ok=True)
+ dest = os.path.join(out_dir, f"{route}.html")
+ _assert_dest_inside_root(dest, project_dir)
+ if overwrite or not os.path.exists(dest):
+ with open(dest, "w", encoding="utf-8") as f:
+ f.write(build_widget_html_for_route(route))
+ return dest
+
+def write_widget_preview(
+ project_dir: str,
+ *,
+ SAMPLE_PIZZA_PREVIEW_JSON,
+ WIDGET_PREVIEW_HTML,
+) -> None:
+ from html import escape as html_escape
+
+ from nitrostack.widgets.html_util import json_for_inline_script
+
+ out_dir = os.path.join(project_dir, "widgets", "out")
+ if not os.path.isdir(out_dir):
+ return
+ routes = sorted(p[:-5] for p in os.listdir(out_dir) if p.endswith(".html"))
+ if not routes:
+ return
+ first = "pizza-list" if "pizza-list" in routes else routes[0]
+ default_payload: dict = {"status": "success"}
+ if "pizza-list" in routes or "pizza-map" in routes:
+ import json as json_lib
+
+ default_payload = json_lib.loads(SAMPLE_PIZZA_PREVIEW_JSON)
+ html = (
+ WIDGET_PREVIEW_HTML.replace("__FIRST__", html_escape(first, quote=True))
+ .replace("__ROUTES__", json_for_inline_script(routes))
+ .replace("__DEFAULT_JSON__", html_escape(json_for_inline_script(default_payload), quote=False))
+ )
+ dest = os.path.join(project_dir, "widgets", "preview.html")
+ with open(dest, "w", encoding="utf-8") as f:
+ f.write(html)
+
+def ensure_python_widgets(
+ project_dir: str,
+ *,
+ Path,
+ write_widget_html,
+ write_widget_preview,
+) -> list:
+ """Create missing ``widgets/out/{route}.html`` for every ``@widget`` in the project."""
+ routes = []
+ for root, _dirs, files in os.walk(project_dir):
+ parts = set(root.split(os.sep))
+ if "node_modules" in parts or ".venv" in parts:
+ continue
+ for name in files:
+ if not name.endswith(".py"):
+ continue
+ path = os.path.join(root, name)
+ try:
+ text = Path(path).read_text(encoding="utf-8")
+ except OSError:
+ continue
+ routes.extend(re.findall(r'@widget\(\s*["\']([^"\']+)["\']', text))
+ routes.extend(re.findall(r'WidgetOptions\(\s*route\s*=\s*["\']([^"\']+)["\']', text))
+ # Only routes that were actually scaffolded go into the returned list — callers
+ # print it as "created", so appending before the write would report a widget that
+ # never landed on disk. A rejected route is surfaced rather than skipped silently.
+ unique = []
+ seen = set()
+ for route in routes:
+ if route in seen:
+ continue
+ seen.add(route)
+ try:
+ write_widget_html(project_dir, route, overwrite=False)
+ except ValueError as exc:
+ print(f"Warning: skipped widget route {route!r}: {exc}")
+ continue
+ unique.append(route)
+ write_widget_preview(project_dir)
+ return unique
diff --git a/nitrostack/cli/entry.py b/nitrostack/cli/entry.py
new file mode 100644
index 0000000..f324279
--- /dev/null
+++ b/nitrostack/cli/entry.py
@@ -0,0 +1,54 @@
+"""Fast CLI entry point: argparse and --help without heavy SDK imports."""
+
+from __future__ import annotations
+
+import sys
+
+from nitrostack.cli._config import DEFAULT_MCP_PORT, DEFAULT_WIDGETS_PORT, OFFICIAL_TEMPLATES
+from nitrostack.cli._parser import build_parser
+from nitrostack.cli import _runtime
+
+
+def _add_port_flags(parser):
+ return _runtime._add_port_flags(
+ parser,
+ DEFAULT_MCP_PORT=DEFAULT_MCP_PORT,
+ DEFAULT_WIDGETS_PORT=DEFAULT_WIDGETS_PORT,
+ )
+
+
+def main() -> None:
+ if hasattr(sys.stdout, "reconfigure"):
+ try:
+ sys.stdout.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+ if hasattr(sys.stderr, "reconfigure"):
+ try:
+ sys.stderr.reconfigure(encoding="utf-8")
+ except Exception:
+ pass
+
+ parser, gen_parser = build_parser(
+ _add_port_flags=_add_port_flags,
+ OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES,
+ )
+ args = parser.parse_args()
+
+ if not args.command:
+ parser.print_help()
+ sys.exit(1)
+
+ from nitrostack.cli.main import dispatch_command
+ from nitrostack.cli.telemetry import (
+ maybe_print_first_run_notice,
+ shutdown_telemetry,
+ track_command_invoked,
+ )
+
+ try:
+ maybe_print_first_run_notice()
+ track_command_invoked(args.command)
+ dispatch_command(args, gen_parser)
+ finally:
+ shutdown_telemetry()
diff --git a/nitrostack/cli/install.py b/nitrostack/cli/install.py
index 2bb09d3..ac8c64e 100644
--- a/nitrostack/cli/install.py
+++ b/nitrostack/cli/install.py
@@ -1,20 +1,29 @@
"""Dependency installation wrapper for `nitrostack-py install`."""
from __future__ import annotations
-
import os
import re
import shutil
import subprocess
import sys
-from typing import List, Optional
-
+from typing import List, Optional, Tuple
from nitrostack.cli._shared import write_text_atomic
_TRUE_TOKENS = frozenset({"1", "true", "yes", "on"})
_PEP503_KEEP = re.compile(r"[^A-Za-z0-9._-]+")
_PEP503_DASH = re.compile(r"[-_.]+")
+# eMudhra/emSign CA incident minimums (python.org advisory).
+MIN_PIP_VERSION = (26, 2, 2)
+MIN_UV_VERSION = (0, 13, 4)
+# Hash-pinned wheel taken verbatim from the advisory. Do not edit by hand.
+SECURE_PIP_SPEC = (
+ "pip @ https://files.pythonhosted.org/packages/"
+ "3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/"
+ "pip-26.2.2-py3-none-any.whl"
+ "#sha256=fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70"
+)
+
def _read(path: str) -> str:
with open(path, "r", encoding="utf-8") as handle:
@@ -115,8 +124,68 @@ def ensure_project_venv(root: str) -> str:
return python
+def _parse_version(text: str, tool: str) -> Optional[Tuple[int, int, int]]:
+ """Parse `pip 24.0 from ...` or `uv 0.13.4 (abc 2026-10-20)` into a tuple."""
+ match = re.search(rf"\b{tool}\s+(\d+)\.(\d+)(?:\.(\d+))?", text or "")
+ if not match:
+ return None
+ major, minor, patch = match.groups()
+ return (int(major), int(minor), int(patch or 0))
+
+
+def _tool_version(cmd: List[str], tool: str) -> Optional[Tuple[int, int, int]]:
+ try:
+ result = subprocess.run(cmd, capture_output=True, text=True, check=False)
+ except OSError:
+ return None
+ if result.returncode != 0:
+ return None
+ return _parse_version(result.stdout, tool)
+
+
+def _get_pip_version(python: str) -> Optional[Tuple[int, int, int]]:
+ return _tool_version([python, "-m", "pip", "--version"], "pip")
+
+
+def _get_uv_version(uv: str) -> Optional[Tuple[int, int, int]]:
+ return _tool_version([uv, "--version"], "uv")
+
+
+def _ensure_secure_pip(python: str, cwd: str) -> None:
+ """Make sure the venv's pip is >= 26.2.2 before it downloads anything.
+
+ The venv pip is whatever the interpreter bundled, which can trust the
+ compromised emSign intermediates. The pinned wheel is verified by sha256,
+ so the bootstrap itself cannot be tampered with.
+ """
+ version = _get_pip_version(python)
+ if version is not None and version >= MIN_PIP_VERSION:
+ return
+ print("Updating pip securely before installing dependencies (eMudhra/emSign advisory).")
+ result = subprocess.run([python, "-m", "pip", "install", SECURE_PIP_SPEC], cwd=cwd)
+ if result.returncode != 0:
+ raise RuntimeError(
+ "Secure pip upgrade failed. Upgrade pip using the python.org eMudhra/emSign "
+ "advisory instructions, then retry `nitrostack-py install`."
+ )
+ version = _get_pip_version(python)
+ if version is None or version < MIN_PIP_VERSION:
+ raise RuntimeError(
+ "pip is still below 26.2.2 after the secure upgrade. "
+ "Upgrade pip manually, then retry `nitrostack-py install`."
+ )
+
+def _check_uv_version(uv: str) -> None:
+ version = _get_uv_version(uv)
+ if version is None or version < MIN_UV_VERSION:
+ raise RuntimeError(
+ "uv 0.13.4 or later is required (eMudhra/emSign CA incident). "
+ "Upgrade uv (`uv self update` or reinstall) and retry."
+ )
+
def _run_pip(args: List[str], cwd: str) -> None:
python = ensure_project_venv(cwd)
+ _ensure_secure_pip(python, cwd)
cmd = [python, "-m", "pip", "install", *args]
print(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, cwd=cwd)
@@ -131,6 +200,7 @@ def _run_uv(args: List[str], cwd: str) -> None:
uv = _uv_bin()
if not uv:
raise RuntimeError("uv is not installed")
+ _check_uv_version(uv)
cmd = [uv, *args]
print(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, cwd=cwd)
diff --git a/nitrostack/cli/main.py b/nitrostack/cli/main.py
index e570c03..187b6a8 100644
--- a/nitrostack/cli/main.py
+++ b/nitrostack/cli/main.py
@@ -1,3 +1,33 @@
+"""CLI entry points and backwards-compatible helper imports."""
+
+from nitrostack.cli._config import DEFAULT_PROJECT_NAME, DEFAULT_MCP_PORT, DEFAULT_WIDGETS_PORT, OFFICIAL_TEMPLATES
+from nitrostack.cli._template_text import (
+ MAIN_TEMPLATE,
+ APP_MODULE_TEMPLATE,
+ CALC_MODULE_TEMPLATE,
+ CALC_SERVICE_TEMPLATE,
+ CALC_TOOLS_TEMPLATE,
+ FOOD_APP_MODULE_TEMPLATE,
+ FOOD_DELIVERY_MODULE_TEMPLATE,
+ FOOD_DELIVERY_SERVICE_TEMPLATE,
+ FOOD_DELIVERY_TOOLS_TEMPLATE,
+ FLIGHT_APP_MODULE_TEMPLATE,
+ FLIGHT_OAUTH_GUARD_TEMPLATE,
+ FLIGHT_SYSTEM_HEALTH_TEMPLATE,
+ FLIGHT_DUFFEL_SERVICE_TEMPLATE,
+ FLIGHT_MODULE_TEMPLATE,
+ FLIGHT_TOOLS_TEMPLATE,
+ FLIGHT_BOOKING_TOOLS_TEMPLATE,
+ FLIGHT_PROMPTS_TEMPLATE,
+ FLIGHT_RESOURCES_TEMPLATE,
+ OAUTH_SETUP_TEMPLATE,
+ ENV_TEMPLATE,
+ REQUIREMENTS_TEMPLATE,
+ TOOL_TEMPLATE,
+ WIDGET_PREVIEW_HTML,
+ SAMPLE_PIZZA_PREVIEW_JSON,
+ MODULE_TEMPLATE,
+)
import os
import re
import sys
@@ -6,1853 +36,235 @@
import subprocess
import time
from pathlib import Path
-
from nitrostack.cli.generate import generate_component, generate_module as generate_module_from_template
from nitrostack.cli.install import install_dependencies, lock_with_uv, rewrite_pyproject_identity
from nitrostack.cli.pack import pack_project
from nitrostack.cli.skills import run_skills_flow
+from nitrostack.cli.telemetry import (
+ identify_from_cloud_login,
+ maybe_print_first_run_notice,
+ shutdown_telemetry,
+ track_command_invoked,
+)
from nitrostack.cli.upgrade import upgrade_project
from nitrostack.cli.validators import format_report, validate_project
+from nitrostack.cli._parser import build_parser
+from nitrostack.cli import _widgets
+from nitrostack.cli import _interaction
+from nitrostack.cli import _runtime
+from nitrostack.cli import _project_init
+from nitrostack.cli import _servers
+from nitrostack.cli import _scaffolding
+from nitrostack.cli import _registration
-MAIN_TEMPLATE = """import asyncio
-from nitrostack import McpApplicationFactory
-from app_module import AppModule
-async def main():
- app = await McpApplicationFactory.create(AppModule)
- await app.start()
+_GENERATE_NAME_RE = _widgets._GENERATE_NAME_RE
+_WIDGET_ROUTE_RE = _widgets._WIDGET_ROUTE_RE
-if __name__ == "__main__":
- asyncio.run(main())
-"""
-
-APP_MODULE_TEMPLATE = """from nitrostack import module
-from modules.calculator.calculator_module import CalculatorModule
-
-@module(
- name="app",
- imports=[CalculatorModule],
- controllers=[],
- providers=[],
- exports=[]
-)
-class AppModule:
- pass
-"""
-
-CALC_MODULE_TEMPLATE = """from nitrostack import module
-from modules.calculator.calculator_tools import CalculatorController
-from modules.calculator.calculator_service import CalculatorService
-
-@module(
- name="calculator",
- imports=[],
- controllers=[CalculatorController],
- providers=[CalculatorService],
- exports=[CalculatorService]
-)
-class CalculatorModule:
- pass
-"""
-
-CALC_SERVICE_TEMPLATE = """from nitrostack import injectable
-
-@injectable(deps=[])
-class CalculatorService:
- def add(self, a: float, b: float) -> float:
- return a + b
-"""
-
-CALC_TOOLS_TEMPLATE = """from nitrostack import injectable, tool, ExecutionContext
-from modules.calculator.calculator_service import CalculatorService
-from pydantic import BaseModel
-
-class AddInput(BaseModel):
- a: float
- b: float
-
-@injectable(deps=[CalculatorService])
-class CalculatorController:
- def __init__(self, service: CalculatorService):
- self.service = service
-
- @tool(
- name="add",
- description="Add two numbers together",
- input_schema=AddInput
- )
- async def add(self, input: AddInput, context: ExecutionContext) -> float:
- context.logger.info(f"Adding {input.a} and {input.b}")
- return self.service.add(input.a, input.b)
-"""
-
-FOOD_APP_MODULE_TEMPLATE = """from nitrostack import module
-from modules.food_delivery.food_delivery_module import FoodDeliveryModule
-
-@module(
- name="app",
- imports=[FoodDeliveryModule],
- controllers=[],
- providers=[],
- exports=[]
-)
-class AppModule:
- pass
-"""
-
-FOOD_DELIVERY_MODULE_TEMPLATE = """from nitrostack import module
-from modules.food_delivery.food_delivery_tools import FoodDeliveryController
-from modules.food_delivery.food_delivery_service import FoodDeliveryService
-
-@module(
- name="food_delivery",
- imports=[],
- controllers=[FoodDeliveryController],
- providers=[FoodDeliveryService],
- exports=[FoodDeliveryService]
-)
-class FoodDeliveryModule:
- pass
-"""
-
-FOOD_DELIVERY_SERVICE_TEMPLATE = """from nitrostack import injectable
-
-@injectable(deps=[])
-class FoodDeliveryService:
- def __init__(self):
- # In-memory database of items and orders
- self.menu = {
- "pizza": {"price": 12.99, "prep_time": 15},
- "burger": {"price": 8.99, "prep_time": 10},
- "salad": {"price": 7.49, "prep_time": 5},
- "sushi": {"price": 15.99, "prep_time": 20}
- }
- self.orders = {}
- self.order_counter = 1000
-
- def get_menu(self):
- return self.menu
-
- def place_order(self, item: str, quantity: int) -> dict:
- item_lower = item.lower()
- if item_lower not in self.menu:
- return {"status": "error", "message": f"Item '{item}' not found in the menu."}
-
- self.order_counter += 1
- order_id = f"ORDER-{self.order_counter}"
-
- price = self.menu[item_lower]["price"] * quantity
- prep_time = self.menu[item_lower]["prep_time"]
-
- self.orders[order_id] = {
- "order_id": order_id,
- "item": item_lower,
- "quantity": quantity,
- "total_price": round(price, 2),
- "status": "Preparing",
- "time_remaining": prep_time
- }
- return self.orders[order_id]
-
- def get_order_status(self, order_id: str) -> dict:
- return self.orders.get(order_id, {"status": "error", "message": f"Order {order_id} not found."})
-"""
-
-FOOD_DELIVERY_TOOLS_TEMPLATE = """from nitrostack import injectable, tool, ExecutionContext
-from modules.food_delivery.food_delivery_service import FoodDeliveryService
-from pydantic import BaseModel, Field
-
-class ViewMenuInput(BaseModel):
- pass
-
-class PlaceOrderInput(BaseModel):
- item: str = Field(description="The food item to order (e.g., pizza, burger, salad, sushi)")
- quantity: int = Field(default=1, description="Number of items to order")
-
-class OrderStatusInput(BaseModel):
- order_id: str = Field(description="The ID of the order to track (e.g., ORDER-1001)")
-
-@injectable(deps=[FoodDeliveryService])
-class FoodDeliveryController:
- def __init__(self, service: FoodDeliveryService):
- self.service = service
-
- @tool(
- name="view_menu",
- description="View the menu and list available food items and prices",
- input_schema=ViewMenuInput
- )
- async def view_menu(self, input: ViewMenuInput, context: ExecutionContext) -> dict:
- context.logger.info("Fetching food delivery menu...")
- return {"menu": self.service.get_menu()}
-
- @tool(
- name="place_order",
- description="Place a food delivery order for a menu item",
- input_schema=PlaceOrderInput
- )
- async def place_order(self, input: PlaceOrderInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Placing order for {input.quantity}x {input.item}")
- return self.service.place_order(input.item, input.quantity)
-
- @tool(
- name="track_order",
- description="Track the status of an existing food delivery order",
- input_schema=OrderStatusInput
- )
- async def track_order(self, input: OrderStatusInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Tracking order status for {input.order_id}")
- return self.service.get_order_status(input.order_id)
-"""
-
-FLIGHT_APP_MODULE_TEMPLATE = """from nitrostack import module, ConfigModule, OAuthModule
-from modules.flights.flights_module import FlightsModule
-from health.system_health import SystemHealthCheck
-import os
-
-@module(
- name="app",
- imports=[
- ConfigModule.for_root(
- env_file_path=".env",
- defaults={"RESOURCE_URI": "https://mcplocal", "PORT": "3000"}
- ),
- # Configure OAuth resource protection
- OAuthModule.for_root(
- resource_uri=os.environ.get("RESOURCE_URI", "https://mcplocal"),
- authorization_servers=[os.environ.get("AUTH_SERVER_URL", "https://dev-5dt0utuk315713tjm.us.auth0.com")],
- scopes_supported=["read", "write", "admin"],
- token_introspection_endpoint=os.environ.get("INTROSPECTION_ENDPOINT"),
- token_introspection_client_id=os.environ.get("INTROSPECTION_CLIENT_ID"),
- token_introspection_client_secret=os.environ.get("INTROSPECTION_CLIENT_SECRET"),
- audience=os.environ.get("TOKEN_AUDIENCE"),
- issuer=os.environ.get("TOKEN_ISSUER")
- ),
- FlightsModule
- ],
- controllers=[],
- providers=[SystemHealthCheck],
- exports=[]
-)
-class AppModule:
- pass
-"""
-
-FLIGHT_OAUTH_GUARD_TEMPLATE = """from nitrostack import ExecutionContext
-
-def create_scope_guard(required_scopes: list):
- class ScopeGuard:
- async def can_activate(self, context: ExecutionContext) -> bool:
- user_scopes = getattr(context.auth, "scopes", [])
- missing_scopes = [s for s in required_scopes if s not in user_scopes]
- if missing_scopes:
- raise ValueError(
- f"Insufficient scope. Required: {', '.join(required_scopes)}. "
- f"Missing: {', '.join(missing_scopes)}"
- )
- return True
- return ScopeGuard
-"""
-
-FLIGHT_SYSTEM_HEALTH_TEMPLATE = """import time
-from nitrostack import health_check
-
-class SystemHealthCheck:
- def __init__(self):
- self.start_time = time.time()
-
- @health_check("system")
- def check_system(self) -> bool:
- uptime = time.time() - self.start_time
- return uptime >= 0
-"""
-
-FLIGHT_DUFFEL_SERVICE_TEMPLATE = """import os
-import sys
-import json
-import urllib.request
-import urllib.parse
-from typing import List, Dict, Any, Optional
-from nitrostack import injectable
-
-@injectable()
-class DuffelService:
- def __init__(self):
- self.api_key = os.environ.get("DUFFEL_API_KEY")
- self.is_mock = not self.api_key or self.api_key.startswith("your-") or len(self.api_key) < 5
-
- def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
- if self.is_mock:
- raise ValueError("Duffel API key is not configured. Running in mock mode.")
-
- headers = {
- "Authorization": f"Bearer {self.api_key}",
- "Duffel-Version": "v2",
- "Content-Type": "application/json"
- }
- url = f"https://api.duffel.com{path}"
- req_data = json.dumps({"data": data}).encode("utf-8") if data else None
-
- req = urllib.request.Request(url, data=req_data, headers=headers, method=method)
- try:
- with urllib.request.urlopen(req, timeout=10) as response:
- res_payload = json.loads(response.read().decode("utf-8"))
- return res_payload.get("data", {})
- except Exception as e:
- sys.stderr.write(f"Duffel API Request failed: {e}\\n")
- sys.stderr.flush()
- raise e
-
- async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": "orq_mock123456",
- "offers": [
- {
- "id": "off_mock123456",
- "total_amount": "450.00",
- "total_currency": "USD",
- "expires_at": "2026-12-31T12:00:00Z",
- "slices": [
- {
- "origin": {"iata_code": params["origin"], "name": "Origin Airport", "city_name": "Origin City"},
- "destination": {"iata_code": params["destination"], "name": "Dest Airport", "city_name": "Dest City"},
- "duration": "PT6H30M",
- "segments": [
- {
- "id": "seg_outbound",
- "origin": {"iata_code": params["origin"]},
- "destination": {"iata_code": params["destination"]},
- "departing_at": f"{params['departureDate']}T08:00:00Z",
- "arriving_at": f"{params['departureDate']}T14:30:00Z",
- "marketing_carrier": {"name": "Mock Airlines"},
- "marketing_carrier_flight_number": "MK123",
- "aircraft": {"name": "Boeing 787"}
- }
- ]
- }
- ]
- }
- ]
- }
-
- slices = [
- {
- "origin": params["origin"],
- "destination": params["destination"],
- "departure_date": params["departureDate"]
- }
- ]
- if params.get("returnDate"):
- slices.append({
- "origin": params["destination"],
- "destination": params["origin"],
- "departure_date": params["returnDate"]
- })
-
- duffel_params = {
- "slices": slices,
- "passengers": params.get("passengers", [{"type": "adult"}]),
- "cabin_class": params.get("cabinClass", "economy"),
- "return_offers": True
- }
- res = self._request("POST", "/air/offer_requests", duffel_params)
- return {
- "id": res.get("id"),
- "offers": res.get("offers", []),
- "passengers": res.get("passengers", []),
- "slices": res.get("slices", [])
- }
-
- async def get_offer(self, offer_id: str) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": offer_id,
- "total_amount": "450.00",
- "total_currency": "USD",
- "expires_at": "2026-12-31T12:00:00Z",
- "slices": [
- {
- "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
- "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
- "duration": "PT6H30M",
- "segments": [
- {
- "id": "seg_mock",
- "origin": {"iata_code": "JFK"},
- "destination": {"iata_code": "LAX"},
- "departing_at": "2026-07-15T08:00:00Z",
- "arriving_at": "2026-07-15T14:30:00Z",
- "marketing_carrier": {"name": "Mock Airlines"},
- "marketing_carrier_flight_number": "MK123",
- "aircraft": {"name": "Boeing 787"}
- }
- ]
- }
- ]
- }
- return self._request("GET", f"/air/offers/{offer_id}")
-
- async def get_seats_for_offer(self, offer_id: str) -> List[Dict[str, Any]]:
- if self.is_mock:
- return [
- {
- "cabin_class": "economy",
- "rows": [
- {
- "row_number": 10,
- "sections": [
- {
- "elements": [
- {
- "type": "seat",
- "id": "seat_10a",
- "designator": "10A",
- "available_services": [{"total_amount": "25.00", "total_currency": "USD"}],
- "disclosures": ["window"]
- },
- {
- "type": "seat",
- "id": "seat_10b",
- "designator": "10B",
- "available_services": [{"total_amount": "0.00", "total_currency": "USD"}],
- "disclosures": ["middle"]
- }
- ]
- }
- ]
- }
- ]
- }
- ]
- res = self._request("GET", f"/air/seat_maps?offer_id={offer_id}")
- return res if isinstance(res, list) else []
-
- async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": "ord_mock123456",
- "status": "held",
- "total_amount": "450.00",
- "total_currency": "USD",
- "expires_at": "2026-12-31T12:00:00Z",
- "booking_reference": "ABCXYZ",
- "passengers": [
- {
- "id": f"pax_{idx}",
- "given_name": p["given_name"],
- "family_name": p["family_name"],
- "type": "adult"
- } for idx, p in enumerate(params["passengers"])
- ],
- "slices": [
- {
- "origin": {"iata_code": "JFK"},
- "destination": {"iata_code": "LAX"},
- "duration": "PT6H30M",
- "segments": [
- {
- "departing_at": "2026-07-15T08:00:00Z",
- "arriving_at": "2026-07-15T14:30:00Z"
- }
- ]
- }
- ]
- }
-
- order_payload = {
- "selected_offers": params["selectedOffers"],
- "passengers": params["passengers"],
- "type": "hold"
- }
- return self._request("POST", "/air/orders", order_payload)
-
- async def get_order(self, order_id: str) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": order_id,
- "status": "held",
- "total_amount": "450.00",
- "total_currency": "USD",
- "booking_reference": "ABCXYZ",
- "created_at": "2026-06-25T12:00:00Z",
- "expires_at": "2026-12-31T12:00:00Z",
- "passengers": [
- {
- "id": "pax_0",
- "given_name": "John",
- "family_name": "Doe",
- "type": "adult",
- "email": "john@example.com",
- "phone_number": "+1234567890"
- }
- ],
- "slices": [
- {
- "id": "sli_mock",
- "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
- "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
- "duration": "PT6H30M",
- "segments": [
- {
- "id": "seg_mock",
- "origin": {"iata_code": "JFK"},
- "destination": {"iata_code": "LAX"},
- "departing_at": "2026-07-15T08:00:00Z",
- "arriving_at": "2026-07-15T14:30:00Z",
- "marketing_carrier": {"name": "Mock Airlines"},
- "marketing_carrier_flight_number": "MK123",
- "aircraft": {"name": "Boeing 787"}
- }
- ]
- }
- ]
- }
- return self._request("GET", f"/air/orders/{order_id}")
-
- async def cancel_order(self, order_id: str) -> Dict[str, Any]:
- if self.is_mock:
- return {
- "id": "ocr_mock123456",
- "refund_amount": "450.00",
- "refund_currency": "USD",
- "confirmed_at": "2026-06-25T12:30:00Z"
- }
- cancel_payload = {"order_id": order_id}
- return self._request("POST", "/air/order_cancellations", cancel_payload)
-
- async def get_airlines(self) -> List[Dict[str, Any]]:
- if self.is_mock:
- return [
- {"iata_code": "AA", "name": "American Airlines"},
- {"iata_code": "DL", "name": "Delta Air Lines"},
- {"iata_code": "UA", "name": "United Airlines"},
- {"iata_code": "BA", "name": "British Airways"}
- ]
- res = self._request("GET", "/air/airlines")
- return res if isinstance(res, list) else []
-"""
-
-FLIGHT_MODULE_TEMPLATE = """from nitrostack import module
-from modules.flights.flights_tools import FlightTools
-from modules.flights.booking_tools import BookingTools
-from modules.flights.flights_prompts import FlightPrompts
-from modules.flights.flights_resources import FlightResources
-from services.duffel_service import DuffelService
-
-@module(
- name="flights",
- controllers=[FlightTools, BookingTools, FlightPrompts, FlightResources],
- providers=[DuffelService],
- exports=[DuffelService]
-)
-class FlightsModule:
- pass
-"""
-
-FLIGHT_TOOLS_TEMPLATE = """from nitrostack import injectable, tool, use_guards, OAuthGuard, ExecutionContext
-from services.duffel_service import DuffelService
-from guards.oauth_guard import create_scope_guard
-from pydantic import BaseModel, Field
-from typing import Optional
-
-class SearchFlightsInput(BaseModel):
- origin: str = Field(description="Origin airport IATA code (e.g., 'JFK', 'LHR')")
- destination: str = Field(description="Destination airport IATA code (e.g., 'LAX', 'CDG')")
- departureDate: str = Field(description="Departure date in YYYY-MM-DD format")
- returnDate: Optional[str] = Field(default=None, description="Return date in YYYY-MM-DD format for round trip")
- adults: int = Field(default=1, description="Number of adult passengers (18+)")
- cabinClass: str = Field(default="economy", description="Preferred cabin class (economy, premium_economy, business, first)")
-
-class FlightDetailsInput(BaseModel):
- offerId: str = Field(description="The flight offer ID from search results")
-
-class AirportSearchInput(BaseModel):
- query: str = Field(description="The search query for airports (e.g., 'London', 'New York')")
-
-class GetAirlinesInput(BaseModel):
- pass
-
-@injectable(deps=[DuffelService])
-class FlightTools:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @tool(
- name="search_flights",
- title="Search Flights",
- description="Search for flight offers based on origin, destination, dates, and preferences.",
- input_schema=SearchFlightsInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- async def search_flights(self, input: SearchFlightsInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Searching flights from {input.origin} to {input.destination}")
- res = await self.service.search_flights(input.model_dump())
- return res
-
- @tool(
- name="get_flight_details",
- title="Get Flight Details",
- description="Get detailed information about a specific flight offer including baggage allowance, conditions.",
- input_schema=FlightDetailsInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- async def get_flight_details(self, input: FlightDetailsInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Fetching flight details for offer {input.offerId}")
- res = await self.service.get_offer(input.offerId)
- return res
-
- @tool(
- name="search_airports",
- title="Search Airports",
- description="Search for airports by query string.",
- input_schema=AirportSearchInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- async def search_airports(self, input: AirportSearchInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Searching airports for query: {input.query}")
- return {"airports": [{"iataCode": "JFK", "name": "John F. Kennedy Airport"}]}
-
- @tool(
- name="get_airlines",
- title="Get Airlines",
- description="Get list of common airlines.",
- input_schema=GetAirlinesInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- async def get_airlines(self, input: GetAirlinesInput, context: ExecutionContext) -> dict:
- context.logger.info("Fetching common airlines")
- res = await self.service.get_airlines()
- return {"airlines": res}
-"""
-
-FLIGHT_BOOKING_TOOLS_TEMPLATE = """from nitrostack import injectable, tool, use_guards, OAuthGuard, ExecutionContext
-from services.duffel_service import DuffelService
-from guards.oauth_guard import create_scope_guard
-from pydantic import BaseModel, Field
-import json
-
-class CreateOrderInput(BaseModel):
- offerId: str = Field(description="The offer ID to book")
- passengers: str = Field(description="JSON string containing array of passenger objects. Each passenger must have: title (mr/ms/mrs/miss/dr), givenName (first name), familyName (last name), gender (M/F), bornOn (YYYY-MM-DD), email, phoneNumber.")
-
-class OrderDetailsInput(BaseModel):
- orderId: str = Field(description="The order ID")
-
-class SeatMapInput(BaseModel):
- offerId: str = Field(description="The offer ID to get seats for")
-
-class CancelOrderInput(BaseModel):
- orderId: str = Field(description="The order ID to cancel")
-
-@injectable(deps=[DuffelService])
-class BookingTools:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @tool(
- name="create_order",
- title="Create Order",
- description="Create a flight order with hold (no payment required). Collect passenger details first.",
- input_schema=CreateOrderInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["write"]))
- async def create_order(self, input: CreateOrderInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Creating flight order for offer {input.offerId}")
- try:
- passengers_array = json.loads(input.passengers)
- except Exception:
- raise ValueError("Invalid passengers JSON format")
-
- passengers = []
- for p in passengers_array:
- passengers.append({
- "title": p.get("title", "mr"),
- "given_name": p.get("givenName"),
- "family_name": p.get("familyName"),
- "gender": p.get("gender", "M"),
- "born_on": p.get("bornOn"),
- "email": p.get("email"),
- "phone_number": p.get("phoneNumber")
- })
-
- order_params = {
- "selectedOffers": [input.offerId],
- "passengers": passengers
- }
- res = await self.service.create_order(order_params)
- return res
-
- @tool(
- name="get_order_details",
- title="Get Order Details",
- description="Get detailed information about an order.",
- input_schema=OrderDetailsInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- async def get_order_details(self, input: OrderDetailsInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Fetching details for order {input.orderId}")
- res = await self.service.get_order(input.orderId)
- return res
-
- @tool(
- name="get_seat_map",
- title="Get Seat Map",
- description="Get available seats for a flight offer to allow seat selection.",
- input_schema=SeatMapInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["read"]))
- async def get_seat_map(self, input: SeatMapInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Fetching seat map for offer {input.offerId}")
- res = await self.service.get_seats_for_offer(input.offerId)
- return {"offerId": input.offerId, "cabins": res}
-
- @tool(
- name="cancel_order",
- title="Cancel Order",
- description="Cancel a flight order and request refund if applicable.",
- input_schema=CancelOrderInput
- )
- @use_guards(OAuthGuard, create_scope_guard(["write"]))
- async def cancel_order(self, input: CancelOrderInput, context: ExecutionContext) -> dict:
- context.logger.info(f"Cancelling order {input.orderId}")
- res = await self.service.cancel_order(input.orderId)
- return res
-"""
-
-FLIGHT_PROMPTS_TEMPLATE = """from nitrostack import injectable, prompt, ExecutionContext
-from services.duffel_service import DuffelService
-from typing import List
-
-@injectable(deps=[DuffelService])
-class FlightPrompts:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @prompt(
- name="flight_search_assistant",
- description="An AI assistant specialized in helping users search for flights and make booking decisions."
- )
- async def flight_search_assistant(self, args: dict, context: ExecutionContext) -> str:
- return "You are a professional flight booking assistant. Help the user search for flights using search_flights, search_airports, and assist in booking holds."
- @prompt(
- name="flight_comparison",
- description="Compare multiple flight offers and provide recommendations."
- )
- async def flight_comparison(self, args: dict, context: ExecutionContext) -> str:
- return "Compare the provided flight offer details, check layover times, durations, and pricing, and give the user a summary of best options."
-"""
-
-FLIGHT_RESOURCES_TEMPLATE = """from nitrostack import injectable, resource, ExecutionContext
-from services.duffel_service import DuffelService
-
-@injectable(deps=[DuffelService])
-class FlightResources:
- def __init__(self, service: DuffelService):
- self.service = service
-
- @resource(
- uri="flight://popular-routes",
- name="Popular Flight Routes",
- description="Information about popular routes and pricing",
- mime_type="application/json"
- )
- async def popular_routes(self, context: ExecutionContext) -> dict:
- return {
- "routes": [
- {"route": "JFK -> LAX", "price": "$200-400"},
- {"route": "LHR -> JFK", "price": "$400-800"}
- ]
- }
-
- @resource(
- uri="flight://booking-guide",
- name="Flight Booking Guide",
- description="Guide on searching and booking flights",
- mime_type="text/markdown"
- )
- async def booking_guide(self, context: ExecutionContext) -> str:
- return "# Flight Booking Guide\\n\\n1. Search flights.\\n2. Collect passenger info.\\n3. Create order hold."
-"""
-
-OAUTH_SETUP_TEMPLATE = """# OAuth 2.1 Server Setup Guide
-
-To run your flight booking MCP server with OAuth 2.1 protection, you need to configure an OAuth authorization server (like Keycloak, Auth0, Hydra, or a local mock OAuth server).
-
-## 1. Local Configuration
-
-Add the following environment variables to your `.env` file to configure resource protection:
-
-```env
-# --- Enforcement gate -------------------------------------------------------
-# Unset / false (default): tokens are NOT enforced. Studio and Inspector can
-# call tools without authenticating, against mock data. Best for local dev.
-# true: Bearer tokens are enforced. If no verifier (JWKS_URI or an
-# introspection endpoint) is configured, the server still starts but rejects
-# every protected request -- fail closed, never fail open.
-OAUTH_REQUIRED=true
-
-# --- Server identity --------------------------------------------------------
-RESOURCE_URI=http://localhost:3000/mcp
-AUTH_SERVER_URL=https://your-tenant.us.auth0.com
-
-# --- Token verification: pick ONE of the two ---------------------------------
-# 1) JWKS -- verifies signatures locally, no network call per request.
-JWKS_URI=https://your-tenant.us.auth0.com/.well-known/jwks.json
-
-# 2) Or RFC 7662 introspection -- asks the authorization server per token.
-# Both spellings are accepted; OAUTH_INTROSPECTION_ENDPOINT wins if both set.
-# OAUTH_INTROSPECTION_ENDPOINT=http://localhost:3000/oauth/introspect
-# INTROSPECTION_ENDPOINT=http://localhost:3000/oauth/introspect
-# INTROSPECTION_CLIENT_ID=your-introspection-client-id
-# INTROSPECTION_CLIENT_SECRET=your-introspection-client-secret
-
-# --- Token claim validation --------------------------------------------------
-# Audience must match, or the token is rejected (RFC 8707). Defaults to RESOURCE_URI.
-TOKEN_AUDIENCE=http://localhost:3000/mcp
-TOKEN_ISSUER=https://your-tenant.us.auth0.com/
-
-# --- Dynamic Client Registration (RFC 7591, optional, off by default) --------
-# Serves only the statically configured client below. Requires BOTH the flag
-# and OAUTH_CLIENT_ID -- without a client id it stays disabled.
-# OAUTH_ENABLE_CLIENT_REGISTRATION=true
-# OAUTH_CLIENT_ID=your-client-id
-# OAUTH_CLIENT_SECRET=your-client-secret
-
-# --- Tuning ------------------------------------------------------------------
-# Seconds to cache a successful introspection result (default 300; 0 disables).
-# OAUTH_TOKEN_CACHE_SECONDS=300
-# Port for the .well-known discovery server (default 3005).
-# OAUTH_DISCOVERY_PORT=3005
-```
-
-## 2. Protected Routes
-
-The tools in this server use the `@use_guards(OAuthGuard, create_scope_guard([...]))` decorators to automatically protect endpoints:
-* **Public**: No guards (or custom public filters).
-* **Read-Protected**: Requires valid access token with `read` scope.
-* **Write-Protected**: Requires valid access token with `write` scope.
-
-When calling protected tools, the client must pass a valid Bearer token in the `Authorization` header.
-"""
-
-ENV_TEMPLATE = """PORT=3000
-NODE_ENV=development
-"""
-
-DEFAULT_PROJECT_NAME = "my-mcp-server"
-DEFAULT_MCP_PORT = "3000"
-DEFAULT_WIDGETS_PORT = "3001"
-
-# Official CLI names → on-disk template directories.
-OFFICIAL_TEMPLATES = {
- "python-starter": "starter",
- "python-pizzaz": "pizzaz",
- "python-oauth": "flight-booking",
-}
-
-REQUIREMENTS_TEMPLATE = """nitrostack
-"""
-
-TOOL_TEMPLATE = """from nitrostack import tool, widget, ExecutionContext
-from pydantic import BaseModel
-
-class {camel_name}Input(BaseModel):
- # Add input parameters here
- pass
-
-@tool(
- name="{name}",
- description="Implement your tool description here",
- input_schema={camel_name}Input
-)
-@widget("{name}")
-async def {name}_handler(input: {camel_name}Input, context: ExecutionContext):
- context.logger.info("Executing tool {name}")
- return {{"status": "success"}}
-"""
-
-WIDGET_PREVIEW_HTML = """
-
-
-
- Widget preview
-
-
-
-
- This static file does not follow MCP Inspector tool calls.
- Inspector JSON is the live result (e.g. all matching pizza shops). Open
- http://localhost:3000/widgets/preview with the server running to
- render that same output, or paste structuredContent below and Inject.
-
-
-
-
-
-
-
-
-"""
-
-SAMPLE_PIZZA_PREVIEW_JSON = """{
- "shops": [
- {
- "id": "tonys-pizza",
- "name": "Tony's New York Pizza",
- "address": "123 Main St, San Francisco, CA 94102",
- "rating": 4.5,
- "priceLevel": 2,
- "openNow": true,
- "image": "https://images.unsplash.com/photo-1513104890138-7c749659a591"
- }
- ],
- "totalShops": 1
-}"""
-
-
-_GENERATE_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
-_WIDGET_ROUTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
-
-
-def _validate_generate_name(name: str) -> str:
- """Reject path segments so ``generate tool ../../ESCAPED`` cannot write outside cwd."""
- name = (name or "").strip()
- if not name or os.path.basename(name) != name or ".." in name or not _GENERATE_NAME_RE.fullmatch(name):
- raise ValueError(
- "name must be a Python identifier (letters, digits, underscore) "
- "and cannot contain path separators"
- )
- return name
+_validate_generate_name = _widgets._validate_generate_name
-def _sanitize_widget_route(route: str) -> str:
- route = (route or "").strip()
- if not route or os.path.basename(route) != route or ".." in route or not _WIDGET_ROUTE_RE.fullmatch(route):
- raise ValueError("widget route must be a single alphanumeric path segment")
- return route
+_sanitize_widget_route = _widgets._sanitize_widget_route
-def _assert_dest_inside_root(dest: str, root: str) -> str:
- dest_abs = os.path.realpath(dest)
- root_abs = os.path.realpath(root)
- try:
- common = os.path.commonpath([dest_abs, root_abs])
- except ValueError as exc:
- raise ValueError("generated path would escape the project directory") from exc
- if common != root_abs:
- raise ValueError("generated path would escape the project directory")
- return dest_abs
+_assert_dest_inside_root = _widgets._assert_dest_inside_root
def write_widget_html(project_dir: str, route: str, *, overwrite: bool = False) -> str:
- """Write ``widgets/out/{route}.html`` if missing (Python-only static widget)."""
- from nitrostack.widgets.route_templates import build_widget_html_for_route
-
- route = _sanitize_widget_route(route)
- project_dir = os.path.abspath(project_dir or ".")
- out_dir = os.path.join(project_dir, "widgets", "out")
- os.makedirs(out_dir, exist_ok=True)
- dest = os.path.join(out_dir, f"{route}.html")
- _assert_dest_inside_root(dest, project_dir)
- if overwrite or not os.path.exists(dest):
- with open(dest, "w", encoding="utf-8") as f:
- f.write(build_widget_html_for_route(route))
- return dest
+ 'Write ``widgets/out/{route}.html`` if missing (Python-only static widget).'
+ return _widgets.write_widget_html(
+ project_dir,
+ route,
+ overwrite=overwrite,
+ _assert_dest_inside_root=_assert_dest_inside_root,
+ _sanitize_widget_route=_sanitize_widget_route,
+ )
def write_widget_preview(project_dir: str) -> None:
- from html import escape as html_escape
-
- from nitrostack.widgets.html_util import json_for_inline_script
-
- out_dir = os.path.join(project_dir, "widgets", "out")
- if not os.path.isdir(out_dir):
- return
- routes = sorted(p[:-5] for p in os.listdir(out_dir) if p.endswith(".html"))
- if not routes:
- return
- first = "pizza-list" if "pizza-list" in routes else routes[0]
- default_payload: dict = {"status": "success"}
- if "pizza-list" in routes or "pizza-map" in routes:
- import json as json_lib
-
- default_payload = json_lib.loads(SAMPLE_PIZZA_PREVIEW_JSON)
- html = (
- WIDGET_PREVIEW_HTML.replace("__FIRST__", html_escape(first, quote=True))
- .replace("__ROUTES__", json_for_inline_script(routes))
- .replace("__DEFAULT_JSON__", html_escape(json_for_inline_script(default_payload), quote=False))
+ return _widgets.write_widget_preview(
+ project_dir,
+ SAMPLE_PIZZA_PREVIEW_JSON=SAMPLE_PIZZA_PREVIEW_JSON,
+ WIDGET_PREVIEW_HTML=WIDGET_PREVIEW_HTML,
)
- dest = os.path.join(project_dir, "widgets", "preview.html")
- with open(dest, "w", encoding="utf-8") as f:
- f.write(html)
def ensure_python_widgets(project_dir: str) -> list:
- """Create missing ``widgets/out/{route}.html`` for every ``@widget`` in the project."""
- routes = []
- for root, _dirs, files in os.walk(project_dir):
- parts = set(root.split(os.sep))
- if "node_modules" in parts or ".venv" in parts:
- continue
- for name in files:
- if not name.endswith(".py"):
- continue
- path = os.path.join(root, name)
- try:
- text = Path(path).read_text(encoding="utf-8")
- except OSError:
- continue
- routes.extend(re.findall(r'@widget\(\s*["\']([^"\']+)["\']', text))
- routes.extend(re.findall(r'WidgetOptions\(\s*route\s*=\s*["\']([^"\']+)["\']', text))
- # Only routes that were actually scaffolded go into the returned list — callers
- # print it as "created", so appending before the write would report a widget that
- # never landed on disk. A rejected route is surfaced rather than skipped silently.
- unique = []
- seen = set()
- for route in routes:
- if route in seen:
- continue
- seen.add(route)
- try:
- write_widget_html(project_dir, route, overwrite=False)
- except ValueError as exc:
- print(f"Warning: skipped widget route {route!r}: {exc}")
- continue
- unique.append(route)
- write_widget_preview(project_dir)
- return unique
-
-MODULE_TEMPLATE = """from nitrostack import module
-
-@module(
- name="{name}",
- imports=[],
- controllers=[],
- providers=[],
- exports=[]
-)
-class {camel_name}Module:
- pass
-"""
-
-def print_banner():
- banner = """\033[34m╔══════════════════════════════════════════════════════════╗
-║ ║
-║ _ _ ___ _____ ____ ___ ║
-║ | \\ | ||_ _|_ _| _ \\ / _ \\ ║
-║ | \\| | | | | | | |_) | | | | ║
-║ | |\\ | | | | | | _ <| |_| | ║
-║ |_| \\_||___| |_| |_| \\_\\\\___/ ║
-║ ║
-║ \033[1;34mNITROSTACK\033[0;34m — Official MCP Framework ║
-║ ║
-╚══════════════════════════════════════════════════════════╝\033[0m"""
- print(banner)
+ 'Create missing ``widgets/out/{route}.html`` for every ``@widget`` in the project.'
+ return _widgets.ensure_python_widgets(
+ project_dir,
+ Path=Path,
+ write_widget_html=write_widget_html,
+ write_widget_preview=write_widget_preview,
+ )
+
+
+print_banner = _interaction.print_banner
+
+
+_stdin_is_interactive = _interaction._stdin_is_interactive
+
def _prompt(message: str, default: str = "") -> str:
- default_hint = f" [{default}]" if default else ""
- sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m{default_hint} ")
- sys.stdout.flush()
- try:
- value = sys.stdin.readline().strip()
- except Exception:
- value = ""
- return value or default
+ return _interaction._prompt(message, default, _stdin_is_interactive=_stdin_is_interactive)
def _resolve_template(template: str) -> str:
- key = (template or "").strip().lower()
- if key not in OFFICIAL_TEMPLATES:
- names = ", ".join(OFFICIAL_TEMPLATES)
- print(f"Error: Unknown template '{template}'. Use one of: {names}")
- sys.exit(1)
- return key
+ return _interaction._resolve_template(template, OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES)
def _prompt_template() -> str:
- print("\033[32m? \033[1;37mChoose a template:\033[0m")
- print(" \033[34m1. python-starter\033[0m Starter — simple calculator for learning basics")
- print(" \033[34m2. python-pizzaz\033[0m Advanced — pizza shop finder with maps & widgets")
- print(" \033[34m3. python-oauth\033[0m Flight booking with OAuth 2.1 auth")
- by_choice = {
- "1": "python-starter",
- "2": "python-pizzaz",
- "3": "python-oauth",
- }
- while True:
- choice = _prompt("Enter choice (1-3) or template name", "1")
- if choice in by_choice:
- return by_choice[choice]
- if choice.lower() in OFFICIAL_TEMPLATES:
- return choice.lower()
- print("Please enter 1, 2, 3, or an explicit template name (python-starter, python-pizzaz, python-oauth).")
-
-
-def _normalize_port(value, label):
- try:
- port = int(value)
- except (TypeError, ValueError):
- print(f"Error: Invalid {label} '{value}'.")
- sys.exit(1)
- if port < 1 or port > 65535:
- print(f"Error: {label} {port} is out of range (1-65535).")
- sys.exit(1)
- return str(port)
-
-
-def _read_project_env():
- values = {}
- env_path = os.path.join(os.getcwd(), ".env")
- if not os.path.exists(env_path):
- return values
- try:
- with open(env_path, encoding="utf-8") as f:
- for line in f:
- line = line.strip()
- if not line or line.startswith("#") or "=" not in line:
- continue
- key, _, val = line.partition("=")
- values[key.strip()] = val.strip().strip('"').strip("'")
- except Exception:
- pass
- return values
+ return _interaction._prompt_template(OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES, _prompt=_prompt)
+
+
+def _prompt_yes_no(message: str, default_yes: bool = True) -> bool:
+ return _interaction._prompt_yes_no(message, default_yes, _stdin_is_interactive=_stdin_is_interactive)
+
+
+_normalize_port = _runtime._normalize_port
+
+
+_read_project_env = _runtime._read_project_env
def _resolve_runtime_ports(port=None, widget=None):
- """Resolve MCP and widget ports. Explicit --port/--widget flags override defaults."""
- project_env = _read_project_env()
- if port is not None:
- mcp_port = _normalize_port(port, "--port")
- else:
- mcp_port = (
- os.environ.get("PORT")
- or os.environ.get("MCP_SERVER_PORT")
- or project_env.get("PORT")
- or project_env.get("MCP_SERVER_PORT")
- or DEFAULT_MCP_PORT
- )
- mcp_port = str(mcp_port)
- if widget is None and mcp_port == DEFAULT_WIDGETS_PORT:
- mcp_port = DEFAULT_MCP_PORT
-
- if widget is not None:
- widgets_port = _normalize_port(widget, "--widget")
- else:
- widgets_port = os.environ.get("WIDGETS_DEV_PORT") or project_env.get("WIDGETS_DEV_PORT") or DEFAULT_WIDGETS_PORT
- widgets_port = str(widgets_port)
- if port is None and widgets_port == DEFAULT_MCP_PORT:
- widgets_port = DEFAULT_WIDGETS_PORT
- return mcp_port, widgets_port
-
-
-def _upsert_env_var(lines, key, value):
- prefix = f"{key}="
- updated = False
- new_lines = []
- for line in lines:
- if line.startswith(prefix):
- new_lines.append(f"{key}={value}\n")
- updated = True
- else:
- new_lines.append(line)
- if not updated:
- new_lines.append(f"{key}={value}\n")
- return new_lines
+ 'Resolve MCP and widget ports. Explicit --port/--widget flags override defaults.'
+ return _runtime._resolve_runtime_ports(
+ port,
+ widget,
+ DEFAULT_MCP_PORT=DEFAULT_MCP_PORT,
+ DEFAULT_WIDGETS_PORT=DEFAULT_WIDGETS_PORT,
+ _normalize_port=_normalize_port,
+ _read_project_env=_read_project_env,
+ )
-def _prompt_yes_no(message: str, default_yes: bool = True) -> bool:
- hint = "Y/n" if default_yes else "y/N"
- sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m ({hint}) ")
- sys.stdout.flush()
- try:
- ans = sys.stdin.readline().strip().lower()
- except Exception:
- ans = ""
- if not ans:
- return default_yes
- if ans in ("y", "yes"):
- return True
- if ans in ("n", "no"):
- return False
- return default_yes
-
-
-def _find_npm():
- npm = shutil.which("npm") or shutil.which("npm.cmd")
- if not npm:
- raise FileNotFoundError(
- "npm was not found on PATH. Install Node.js (https://nodejs.org) and retry."
- )
- return npm
+_upsert_env_var = _runtime._upsert_env_var
+
+
+_find_npm = _runtime._find_npm
def _run_npm(args, **kwargs):
- """Run npm without shell=True. A list + shell=True is treated as `sh -c npm` and drops flags."""
- kwargs.pop("shell", None)
- return subprocess.run([_find_npm(), *args], **kwargs)
+ 'Run npm without shell=True. A list + shell=True is treated as `sh -c npm` and drops flags.'
+ return _runtime._run_npm(args, _find_npm=_find_npm, **kwargs)
def _popen_npm(args, **kwargs):
- kwargs.pop("shell", None)
- return subprocess.Popen([_find_npm(), *args], **kwargs)
+ return _runtime._popen_npm(args, _find_npm=_find_npm, **kwargs)
def _add_port_flags(parser):
- parser.add_argument(
- "--port",
- default=None,
- help=f"MCP HTTP port (default: {DEFAULT_MCP_PORT}; overrides PORT when set)",
- )
- parser.add_argument(
- "--widget",
- default=None,
- help=f"Widget dev server port (default: {DEFAULT_WIDGETS_PORT}; overrides WIDGETS_DEV_PORT when set)",
+ return _runtime._add_port_flags(
+ parser,
+ DEFAULT_MCP_PORT=DEFAULT_MCP_PORT,
+ DEFAULT_WIDGETS_PORT=DEFAULT_WIDGETS_PORT,
)
def init_project(name: str = None, template: str = None, skip_install: bool = False, port=None, widget=None, force: bool = False):
- print_banner()
-
- # 1. Project name — optional CLI arg, otherwise the next readline
- if not name:
- name = _prompt("Project name", DEFAULT_PROJECT_NAME)
- name = (name or "").strip()
- if not name:
- print("Error: Project name cannot be empty.")
- sys.exit(1)
-
- # 2. Overwrite check
- if os.path.exists(name):
- sys.stdout.write(f"\033[32m? \033[1;37mDirectory '{name}' already exists. Overwrite?\033[0m (Yes/No) [No]: ")
- sys.stdout.flush()
- ans = sys.stdin.readline().strip().lower()
- if ans not in ("y", "yes"):
- print("Initialization cancelled.")
- sys.exit(0)
- shutil.rmtree(name, ignore_errors=True)
-
- # 3. Select template (explicit python-* names)
- if not template:
- template = _prompt_template()
- else:
- template = _resolve_template(template)
-
- # 4. Description and Author
- description = _prompt("Description", "My awesome MCP server")
- author = _prompt("Author", "developer")
-
- # 5. Install dependencies (Y/n). --skip-install skips the prompt.
- if skip_install:
- install_deps = False
- else:
- install_deps = _prompt_yes_no("Install dependencies", default_yes=True)
-
- mcp_port = _normalize_port(port, "--port") if port is not None else DEFAULT_MCP_PORT
- widgets_port = _normalize_port(widget, "--widget") if widget is not None else DEFAULT_WIDGETS_PORT
-
- # 6. Copy template directory
- import nitrostack
- package_dir = os.path.dirname(nitrostack.__file__)
- template_dir = OFFICIAL_TEMPLATES[template]
- template_src_dir = os.path.join(package_dir, "templates", template_dir)
-
- if not os.path.exists(template_src_dir):
- print(f"Error: Template '{template}' not found at '{template_src_dir}'.")
- sys.exit(1)
-
- shutil.copytree(template_src_dir, name)
- rewrite_pyproject_identity(
- os.path.join(name, "pyproject.toml"),
- name=os.path.basename(os.path.abspath(name)),
- description=description,
+ return _project_init.init_project(
+ name,
+ template,
+ skip_install,
+ port,
+ widget,
+ force,
+ DEFAULT_MCP_PORT=DEFAULT_MCP_PORT,
+ DEFAULT_PROJECT_NAME=DEFAULT_PROJECT_NAME,
+ DEFAULT_WIDGETS_PORT=DEFAULT_WIDGETS_PORT,
+ OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES,
+ _normalize_port=_normalize_port,
+ _prompt=_prompt,
+ _prompt_template=_prompt_template,
+ _prompt_yes_no=_prompt_yes_no,
+ _resolve_template=_resolve_template,
+ _run_npm=_run_npm,
+ _stdin_is_interactive=_stdin_is_interactive,
+ _upsert_env_var=_upsert_env_var,
+ ensure_python_widgets=ensure_python_widgets,
+ install_dependencies=install_dependencies,
+ lock_with_uv=lock_with_uv,
+ print_banner=print_banner,
+ rewrite_pyproject_identity=rewrite_pyproject_identity,
+ run_skills_flow=run_skills_flow,
+ )
+
+
+def run_login(user_id: str, email: str, org_id: str | None = None):
+ """Associate the anonymous CLI distinct id with a NitroCloud user (analytics)."""
+ identify_from_cloud_login(
+ user_id=(user_id or "").strip(),
+ email=(email or "").strip(),
+ organization_id=(org_id or "").strip() or None,
)
- from nitrostack.cli.vendor import ensure_vendored_nitrostack
- ensure_vendored_nitrostack(name)
- lock_with_uv(name)
- widget_routes = ensure_python_widgets(name)
- print("\n\033[32m✓\033[0m Project created")
- if widget_routes:
- print(f"\033[32m✓\033[0m Python widgets: {', '.join(widget_routes)}")
- print(" HTML in widgets/out/ — preview: widgets/preview.html")
-
- # 7. Update .env file
- env_path = os.path.join(name, ".env")
- if os.path.exists(env_path):
- with open(env_path, "r", encoding="utf-8") as f:
- lines = f.readlines()
- new_lines = []
- for line in lines:
- if line.startswith("SERVER_NAME="):
- new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n')
- elif line.startswith("SERVER_DESC="):
- new_lines.append(f'SERVER_DESC="{description}"\n')
- elif line.startswith("SERVER_AUTHOR="):
- new_lines.append(f'SERVER_AUTHOR="{author}"\n')
- else:
- new_lines.append(line)
- has_name = any(line.startswith("SERVER_NAME=") for line in new_lines)
- has_desc = any(line.startswith("SERVER_DESC=") for line in new_lines)
- has_author = any(line.startswith("SERVER_AUTHOR=") for line in new_lines)
- if not has_name:
- new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n')
- if not has_desc:
- new_lines.append(f'SERVER_DESC="{description}"\n')
- if not has_author:
- new_lines.append(f'SERVER_AUTHOR="{author}"\n')
- new_lines = _upsert_env_var(new_lines, "PORT", mcp_port)
- new_lines = _upsert_env_var(new_lines, "WIDGETS_DEV_PORT", widgets_port)
- new_lines = _upsert_env_var(new_lines, "NITROSTACK_APP_MODE", "universal")
- with open(env_path, "w", encoding="utf-8") as f:
- f.writelines(new_lines)
-
- # 8. Update widgets package.json
- widgets_package_path = os.path.join(name, "src", "widgets", "package.json")
- if os.path.exists(widgets_package_path):
- import json
- try:
- with open(widgets_package_path, "r", encoding="utf-8") as f:
- pkg = json.load(f)
- pkg["name"] = f"{name}-widgets"
- # The port is passed once by the CLI (`npm run dev -- --port N`), so it
- # is deliberately not baked into the script.
- scripts = pkg.setdefault("scripts", {})
- scripts["dev"] = "next dev"
- scripts["start"] = "next start"
- with open(widgets_package_path, "w", encoding="utf-8") as f:
- json.dump(pkg, f, indent=2)
- except Exception:
- pass
-
- # 9. Install Python deps (requirements.txt / pyproject.toml), then widget npm if present.
- if install_deps:
- print("Installing dependencies...")
- try:
- install_dependencies(cwd=name)
- print("\033[32m✓\033[0m Dependencies installed")
- except Exception as e:
- print(f"Warning: Failed to install dependencies: {e}")
- print("Please run 'nitrostack-py install' from the project directory.\n")
- widgets_dir = os.path.join(name, "src", "widgets")
- if os.path.exists(widgets_dir):
- print("Installing widget dependencies...")
- try:
- _run_npm(["--version"], capture_output=True, check=True, text=True)
- _run_npm(["install"], cwd=widgets_dir, check=True)
- print("\033[32m✓\033[0m Widget dependencies installed\n")
- except FileNotFoundError as e:
- print(f"Warning: {e}")
- print("Please run 'npm install' inside 'src/widgets' manually.\n")
- except subprocess.CalledProcessError as e:
- detail = (getattr(e, "stderr", None) or getattr(e, "stdout", None) or str(e)).strip()
- print(f"Warning: Failed to install widget dependencies: {detail}")
- print("Please run 'npm install' inside 'src/widgets' manually.\n")
- else:
- print("\033[32m✓\033[0m Skipped dependency install")
-
- run_skills_flow(os.path.abspath(name), force=force)
-
- # Success Card
- abs_path = os.path.abspath(name)
- success_box = f"""\033[36m╔══════════════════════════════════════════════════════════╗
-║ \033[32m✓ Project Ready\033[36m ║
-║ ║
-║ Name: {name:<48} ║
-║ Template: {template:<44} ║
-║ Path: {abs_path:<48} ║
-╚══════════════════════════════════════════════════════════╝\033[0m"""
- print(success_box)
-
- # Next Steps
- print("\n\033[1;37mNext steps:\033[0m")
- print(f" 1. \033[34mcd {name}\033[0m")
- if template == "python-oauth":
- print(" 2. Configure OAuth credentials in your \033[34m.env\033[0m file")
- print(" See \033[34mOAUTH_SETUP.md\033[0m for provider guides")
- else:
- print(" 2. Configure environment variables in \033[34m.env\033[0m")
- print(" 3. Start development server: \033[34mnitrostack-py dev\033[0m (or `python -m nitrostack.cli.main dev`)")
- print(" 4. Preview widgets: \033[34mhttp://localhost:3000/widgets/preview\033[0m (server running)")
- print(" Static file (manual JSON): \033[34mopen widgets/preview.html\033[0m")
- print(" 5. Inspector (HTTP): \033[34mMCP_TRANSPORT_TYPE=http MCP_STATELESS=true NITROSTACK_APP_MODE=universal python main.py\033[0m")
- print(" Connect Streamable HTTP to \033[34mhttp://localhost:3000/mcp\033[0m with \033[34mAuthentication = Off\033[0m")
- print(" Apps tab renders the widget from live \033[34mstructuredContent\033[0m (not widgets/preview.html)")
- if template == "python-pizzaz":
- print(" For open shops only set \033[34mopenNow=true\033[0m (list) or \033[34mfilter=open_now\033[0m (map)")
- print(" 6. NitroStudio: open this folder as a project; Studio starts and connects it.")
- print("\nHappy coding! 🚀\n")
def run_dev(port=None, widget=None):
- target = "main.py"
- if not os.path.exists(target):
- print("Error: main.py not found in current directory.")
- sys.exit(1)
-
- mcp_port, widgets_port = _resolve_runtime_ports(port, widget)
-
- print(f"Starting hot-reload development server for {target}...")
- print(f"MCP server port: {mcp_port}")
- process = None
- widgets_process = None
-
- # Check if Next.js widgets are present
- widgets_dir = os.path.join(os.getcwd(), "src", "widgets")
- has_widgets = os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json"))
- if has_widgets:
- print(f"Starting widget development server on port {widgets_port}...")
- try:
- widgets_process = _popen_npm(
- ["run", "dev", "--", "--port", str(widgets_port)],
- cwd=widgets_dir,
- )
- except Exception as e:
- print(f"Warning: Could not start widget development server: {e}")
-
- def start_process():
- nonlocal process
- if process:
- try:
- process.terminate()
- process.wait(timeout=2)
- except Exception:
- try:
- process.kill()
- except Exception:
- pass
- env = os.environ.copy()
- env["PYTHONPATH"] = os.path.abspath(".")
- env["PORT"] = mcp_port
- if has_widgets:
- env["WIDGETS_DEV_PORT"] = str(widgets_port)
- process = subprocess.Popen([sys.executable, target], env=env)
-
- def cleanup():
- nonlocal process, widgets_process
- if process:
- try:
- process.terminate()
- except Exception:
- pass
- if widgets_process:
- try:
- widgets_process.terminate()
- except Exception:
- pass
-
- try:
- start_process()
-
- watched_extensions = {".py", ".env"}
-
- def get_mtimes():
- mtimes = {}
- for root, dirs, files in os.walk("."):
- if any(part.startswith(".") or part in ("venv", "env", "__pycache__") for part in root.split(os.sep)):
- continue
- for file in files:
- ext = os.path.splitext(file)[1]
- if ext in watched_extensions:
- path = os.path.join(root, file)
- try:
- mtimes[path] = os.path.getmtime(path)
- except Exception:
- pass
- return mtimes
-
- # Try using watchfiles for high-performance, low-CPU file monitoring
- try:
- from watchfiles import watch
- print("Using watchfiles for high-performance file monitoring.")
-
- while True:
- for changes in watch("."):
- should_restart = False
- for change_type, path in changes:
- ext = os.path.splitext(path)[1]
- if ext in watched_extensions:
- parts = os.path.normpath(path).split(os.sep)
- if not any(p in parts for p in ("venv", "env", "__pycache__", ".git", ".pytest_cache", "nitrostack.egg-info")):
- should_restart = True
- break
- if should_restart:
- print("File changes detected! Restarting server...")
- start_process()
-
- time.sleep(0.5)
- if process and process.poll() is not None:
- print("Server process exited. Waiting for file changes to restart...")
-
- except ImportError:
- print("watchfiles library not found. Falling back to standard polling...")
- last_mtimes = get_mtimes()
- try:
- while True:
- time.sleep(1)
- if process and process.poll() is not None:
- print("Server process exited. Waiting for file changes to restart...")
- current_mtimes = get_mtimes()
- changed = False
- if set(current_mtimes.keys()) != set(last_mtimes.keys()):
- changed = True
- else:
- for path, mtime in current_mtimes.items():
- if last_mtimes.get(path) != mtime:
- changed = True
- break
- if changed:
- print("File changes detected! Restarting server...")
- start_process()
- last_mtimes = current_mtimes
- except KeyboardInterrupt:
- pass
- except KeyboardInterrupt:
- print("\nStopping development server...")
- cleanup()
+ return _servers.run_dev(
+ port,
+ widget,
+ _popen_npm=_popen_npm,
+ _resolve_runtime_ports=_resolve_runtime_ports,
+ )
+
def run_start(port=None, widget=None):
- target = "main.py"
- if not os.path.exists(target):
- print("Error: main.py not found in current directory.")
- sys.exit(1)
-
- mcp_port, widgets_port = _resolve_runtime_ports(port, widget)
-
- print(f"Starting production server for {target}...")
- print(f"MCP HTTP: http://localhost:{mcp_port}/mcp")
- env = os.environ.copy()
- env["PYTHONPATH"] = os.path.abspath(".")
- env["PORT"] = mcp_port
- env["WIDGETS_DEV_PORT"] = widgets_port
- env["NODE_ENV"] = "production"
- # Select HTTP explicitly rather than letting NODE_ENV=production fall through
- # to dual. Dual shuts HTTP down when STDIO reaches EOF, so `start` would exit
- # immediately wherever stdin is not held open (Docker without -i, systemd, CI).
- # `setdefault` keeps an explicit MCP_TRANSPORT_TYPE from the caller.
- env.setdefault("MCP_TRANSPORT_TYPE", "http")
-
- widgets_dir = os.path.join(os.getcwd(), "src", "widgets")
- widgets_process = None
- if os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json")):
- # `next start` needs a production build; Popen would succeed and the child
- # would fail with a bare "Could not find a production build", so check here.
- if not os.path.exists(os.path.join(widgets_dir, ".next")):
- print("Widgets are not built yet — skipping the widget server.")
- print("Run 'npm run build' inside 'src/widgets', then retry.\n")
- else:
- print(f"Starting widget server on port {widgets_port}...")
- try:
- widgets_process = _popen_npm(
- ["run", "start", "--", "--port", str(widgets_port)],
- cwd=widgets_dir,
- )
- except Exception as e:
- print(f"Warning: Could not start widget server: {e}")
-
- try:
- subprocess.run([sys.executable, target], env=env)
- except KeyboardInterrupt:
- print("\nStopping server...")
- finally:
- if widgets_process:
- try:
- widgets_process.terminate()
- except Exception:
- pass
+ return _servers.run_start(
+ port,
+ widget,
+ _popen_npm=_popen_npm,
+ _resolve_runtime_ports=_resolve_runtime_ports,
+ )
+
def generate_tool(name: str):
- # Both validators run before anything is written. `_validate_generate_name` and
- # `_sanitize_widget_route` accept overlapping-but-different character sets (e.g.
- # `_foo` is a valid identifier but not a valid route; `my-tool` is the reverse),
- # so validating the route lazily inside `write_widget_html` would leave an orphan
- # `{name}_tool.py` behind whenever the two disagree — and that orphan then blocks
- # any retry with "File already exists".
- try:
- name = _validate_generate_name(name)
- _sanitize_widget_route(name)
- except ValueError as exc:
- print(f"Error: {exc}")
- sys.exit(1)
- filename = f"{name}_tool.py"
- dest_py = os.path.abspath(filename)
- try:
- _assert_dest_inside_root(dest_py, os.getcwd())
- except ValueError as exc:
- print(f"Error: {exc}")
- sys.exit(1)
- if os.path.exists(filename):
- print(f"Error: File '{filename}' already exists.")
- sys.exit(1)
- camel_name = "".join(part.capitalize() for part in name.split("_"))
- content = TOOL_TEMPLATE.format(name=name, camel_name=camel_name)
- with open(filename, "w", encoding="utf-8") as f:
- f.write(content)
- try:
- html_path = write_widget_html(".", name, overwrite=False)
- except ValueError as exc:
- print(f"Error: {exc}")
- sys.exit(1)
- write_widget_preview(".")
- print(f"Generated tool boilerplate in '{filename}'")
- print(f"Generated widget HTML in '{html_path}'")
+ return _scaffolding.generate_tool(
+ name,
+ TOOL_TEMPLATE=TOOL_TEMPLATE,
+ _assert_dest_inside_root=_assert_dest_inside_root,
+ _sanitize_widget_route=_sanitize_widget_route,
+ _validate_generate_name=_validate_generate_name,
+ write_widget_html=write_widget_html,
+ write_widget_preview=write_widget_preview,
+ )
+
def generate_module(name: str):
- generate_module_from_template(name)
-
-def get_claude_config_paths():
- paths = []
- home = os.path.expanduser("~")
-
- # Windows
- if sys.platform == "win32":
- appdata = os.environ.get("APPDATA")
- if appdata:
- paths.append(os.path.join(appdata, "Claude", "claude_desktop_config.json"))
- # Windows Store app path
- localappdata = os.environ.get("LOCALAPPDATA")
- if localappdata:
- store_dir = os.path.join(localappdata, "Packages")
- if os.path.exists(store_dir):
- try:
- for folder in os.listdir(store_dir):
- if folder.startswith("Claude_"):
- paths.append(os.path.join(store_dir, folder, "LocalCache", "Roaming", "Claude", "claude_desktop_config.json"))
- except Exception:
- pass
- # macOS
- elif sys.platform == "darwin":
- paths.append(os.path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"))
- # Linux
- else:
- paths.append(os.path.join(home, ".config", "Claude", "claude_desktop_config.json"))
-
- return [p for p in paths if os.path.exists(os.path.dirname(p))]
+ return _scaffolding.generate_module(name, generate_module_from_template=generate_module_from_template)
-def register_server(name: str, file_path: str):
- import json
-
- if not os.path.exists(file_path):
- print(f"Error: Script file '{file_path}' does not exist.")
- sys.exit(1)
-
- abs_file_path = os.path.abspath(file_path)
- python_exe = sys.executable
-
- config_paths = get_claude_config_paths()
- if not config_paths:
- print("Error: Could not find any Claude Desktop installation directories.")
- print("Please ensure Claude Desktop is installed on your machine.")
- sys.exit(1)
-
- registered_any = False
- for path in config_paths:
- try:
- config = {}
- if os.path.exists(path):
- with open(path, "r", encoding="utf-8") as f:
- content = f.read().strip()
- if content:
- try:
- config = json.loads(content)
- except json.JSONDecodeError:
- print(f"Warning: Configuration file at '{path}' is not valid JSON. Resetting it.")
-
- if "mcpServers" not in config:
- config["mcpServers"] = {}
-
- config["mcpServers"][name] = {
- "command": python_exe,
- "args": [abs_file_path]
- }
-
- # Create directory if needed
- os.makedirs(os.path.dirname(path), exist_ok=True)
- with open(path, "w", encoding="utf-8") as f:
- json.dump(config, f, indent=2)
-
- print(f"Successfully registered server '{name}' in: {path}")
- registered_any = True
- except Exception as e:
- print(f"Error writing to config at '{path}': {e}")
-
- if registered_any:
- print("\nAll done! Please fully restart Claude Desktop to load your new server.")
- else:
- print("Error: Failed to register the server in any configuration files.")
-def main():
- if hasattr(sys.stdout, "reconfigure"):
- try:
- sys.stdout.reconfigure(encoding="utf-8")
- except Exception:
- pass
- if hasattr(sys.stderr, "reconfigure"):
- try:
- sys.stderr.reconfigure(encoding="utf-8")
- except Exception:
- pass
-
- parser = argparse.ArgumentParser(
- prog="nitrostack-py",
- description="nitrostack-py CLI — Scaffold, develop, pack, and run NitroStack Python MCP servers",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog=(
- "examples:\n"
- " nitrostack-py init my-server\n"
- " nitrostack-py generate guard MyGuard\n"
- " nitrostack-py pack --dry-run\n"
- " nitrostack-py upgrade --dry-run\n"
- " nitrostack-py install --production\n"
- " nitrostack-py validate\n"
- ),
- )
- subparsers = parser.add_subparsers(dest="command", metavar="command")
-
- # init command
- init_parser = subparsers.add_parser("init", help="Initialize a new NitroStack MCP server project")
- init_parser.add_argument("name", nargs="?", default=None, help="Name of the project directory (prompted if omitted)")
- init_parser.add_argument(
- "--template",
- choices=list(OFFICIAL_TEMPLATES.keys()),
- default=None,
- help="Template to use: python-starter, python-pizzaz, python-oauth (default: interactive prompt)",
- )
- init_parser.add_argument("--skip-install", action="store_true", help="Skip installing Python (and widget npm) dependencies")
- init_parser.add_argument(
- "--force",
- action="store_true",
- help="Overwrite existing agent skill directories when installing",
- )
- _add_port_flags(init_parser)
+get_claude_config_paths = _registration.get_claude_config_paths
- # dev command
- dev_parser = subparsers.add_parser("dev", help="Start the hot-reloading development server")
- _add_port_flags(dev_parser)
- # start command
- start_parser = subparsers.add_parser("start", help="Start the production server")
- _add_port_flags(start_parser)
+def register_server(name: str, file_path: str):
+ return _registration.register_server(
+ name,
+ file_path,
+ _build_server_entry=_build_server_entry,
+ get_claude_config_paths=get_claude_config_paths,
+ )
- # register command
- reg_parser = subparsers.add_parser("register", help="Register server script inside Claude Desktop configuration")
- reg_parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="Name of the server (defaults to folder name)")
- reg_parser.add_argument("--file", default="main.py", help="Python script to register (defaults to main.py)")
- # generate command
- gen_parser = subparsers.add_parser(
- "generate",
- help="Generate boilerplate code (tool, module, guard, pipe, interceptor, filter, service)",
- )
- gen_subparsers = gen_parser.add_subparsers(dest="generator", metavar="type")
-
- tool_parser = gen_subparsers.add_parser("tool", help="Generate a new tool boilerplate")
- tool_parser.add_argument("name", help="Name of the tool")
-
- mod_parser = gen_subparsers.add_parser("module", help="Generate a new module boilerplate")
- mod_parser.add_argument("name", help="Name of the module")
-
- for kind, kind_help in (
- ("guard", "Generate an authorization guard"),
- ("pipe", "Generate a validation/transform pipe"),
- ("interceptor", "Generate an execution interceptor"),
- ("filter", "Generate an exception filter"),
- ("service", "Generate an injectable service"),
- ):
- kind_parser = gen_subparsers.add_parser(kind, help=kind_help)
- kind_parser.add_argument("name", help=f"Name of the {kind}")
-
- # pack command
- pack_parser = subparsers.add_parser(
- "pack",
- help="Build a deployable wheel of the current project (excludes .env by default)",
- )
- pack_parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Show files that would be packed without creating the artifact",
- )
- pack_parser.add_argument(
- "--include-env",
- action="store_true",
- help="Include .env files in the wheel (use with caution!)",
- )
+_build_server_entry = _registration._build_server_entry
- # upgrade command
- upgrade_parser = subparsers.add_parser(
- "upgrade",
- help="Update the nitrostack dependency to the latest (or a specific) PyPI version",
- )
- upgrade_parser.add_argument(
- "--version",
- dest="target_version",
- metavar="X.Y.Z",
- help="Pin nitrostack to this version instead of the latest PyPI release",
- )
- upgrade_parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Show the version change without modifying pyproject.toml",
- )
- upgrade_parser.add_argument(
- "--allow-downgrade",
- action="store_true",
- help="Allow --version to pin an older release than the one currently declared",
- )
- # install command
- install_parser = subparsers.add_parser(
- "install",
- help="Install project dependencies from pyproject.toml / requirements.txt",
- )
- install_parser.add_argument(
- "--production",
- action="store_true",
- help="Skip development dependencies (optional extras and requirements-dev.txt)",
- )
+_write_json_atomic = _registration._write_json_atomic
- # validate command
- subparsers.add_parser(
- "validate",
- help="Lint project config, @mcp_app imports, and @module() class references",
- )
- args = parser.parse_args()
+def register_cursor_server(name: str, file_path: str = "main.py", *, global_config: bool = False, transport: str = "command"):
+ "Merge this project into Cursor's project or user MCP configuration."
+ return _registration.register_cursor_server(
+ name,
+ file_path,
+ global_config=global_config,
+ transport=transport,
+ _build_server_entry=_build_server_entry,
+ _write_json_atomic=_write_json_atomic,
+ )
- if not args.command:
- parser.print_help()
- sys.exit(1)
+def dispatch_command(args, gen_parser) -> None:
def _run_command(fn, *fn_args, **fn_kwargs):
try:
return fn(*fn_args, **fn_kwargs)
@@ -1875,6 +287,13 @@ def _run_command(fn, *fn_args, **fn_kwargs):
run_start(port=args.port, widget=args.widget)
elif args.command == "register":
register_server(args.name, args.file)
+ elif args.command == "cursor":
+ register_cursor_server(
+ args.name,
+ args.file,
+ global_config=args.global_config,
+ transport=args.transport,
+ )
elif args.command == "generate":
if not args.generator:
gen_parser.print_help()
@@ -1901,6 +320,17 @@ def _run_command(fn, *fn_args, **fn_kwargs):
print(format_report(issues))
if any(issue.severity == "error" for issue in issues):
sys.exit(1)
+ elif args.command == "login":
+ _run_command(run_login, args.user_id, args.email, args.org_id)
+
+
+def main():
+ from nitrostack.cli.entry import main as _entry_main
+
+ _entry_main()
+
if __name__ == "__main__":
- main()
+ from nitrostack.cli.entry import main as _entry_main
+
+ _entry_main()
diff --git a/nitrostack/cli/pack.py b/nitrostack/cli/pack.py
index 221a6bc..717da4f 100644
--- a/nitrostack/cli/pack.py
+++ b/nitrostack/cli/pack.py
@@ -24,425 +24,45 @@
read_text,
requirement_name,
)
-
-_EXCLUDE_DIR_NAMES = EXCLUDE_DIR_NAMES
-
-_EXCLUDE_SUFFIXES = {
- ".pyc",
- ".pyo",
- ".pyd",
- ".so",
- ".dll",
- ".egg",
-}
-
-_EXCLUDE_NAME_GLOBS = {
- "*.egg-info",
-}
-
-ENV_EXAMPLE_STUB = """PORT=8000
-NODE_ENV=development
-"""
-
-_PYPROJECT_TEMPLATE = """[build-system]
-requires = ["setuptools>=61.0.0"]
-build-backend = "setuptools.build_meta"
-
-[project]
-name = "{name}"
-version = "{version}"
-description = "Packed NitroStack MCP server"
-requires-python = ">=3.10"
-dependencies = {deps}
-
-[tool.setuptools]
-py-modules = {py_modules}
-
-[tool.setuptools.packages.find]
-where = ["."]
-namespaces = true
-exclude = ["tests*", "venv*", "node_modules*", "src.widgets*"]
-
-[tool.setuptools.package-data]
-"*" = [".env.example", "requirements.txt", "*.md"]
-"""
-
-
-def _is_secret_env(name: str) -> bool:
- if name == ".env.example":
- return False
- return name == ".env" or name.startswith(".env.")
-
-
-def _load_gitignore_patterns(root: str) -> List[Tuple[str, bool]]:
- """Return (pattern, is_negation) pairs from .gitignore if present."""
- path = os.path.join(root, ".gitignore")
- patterns: List[Tuple[str, bool]] = []
- if not os.path.isfile(path):
- return patterns
- try:
- with open(path, "r", encoding="utf-8") as handle:
- for raw in handle:
- line = raw.strip()
- if not line or line.startswith("#"):
- continue
- negated = line.startswith("!")
- if negated:
- line = line[1:]
- patterns.append((line.rstrip("/"), negated))
- except OSError:
- return []
- return patterns
-
-
-def _matches_gitignore(rel_posix: str, patterns: Sequence[Tuple[str, bool]]) -> bool:
- ignored = False
- basename = rel_posix.rsplit("/", 1)[-1]
- for pattern, negated in patterns:
- pat = pattern[2:] if pattern.startswith("./") else pattern
- hit = (
- fnmatch(rel_posix, pat)
- or fnmatch(rel_posix, pat.rstrip("/") + "/*")
- or fnmatch(basename, pat)
- or (pat.endswith("/") and (rel_posix.startswith(pat) or rel_posix.startswith(pat.rstrip("/"))))
- )
- if hit:
- ignored = not negated
- return ignored
-
-
-def _should_exclude(
- rel_posix: str,
- name: str,
- is_dir: bool,
- gitignore: Sequence[Tuple[str, bool]],
- *,
- include_env: bool = False,
-) -> bool:
- if name == ".env.example":
- return False
- if _is_secret_env(name) and not include_env:
- return True
- if name in _EXCLUDE_DIR_NAMES and is_dir:
- return True
- if any(fnmatch(name, glob) for glob in _EXCLUDE_NAME_GLOBS):
- return True
- if any(name.endswith(suffix) for suffix in _EXCLUDE_SUFFIXES):
- return True
- if name.endswith(".egg-info") or ".egg-info/" in rel_posix:
- return True
- if _matches_gitignore(rel_posix, gitignore):
- return True
- return False
-
-
-def collect_pack_files(root: str, *, include_env: bool = False) -> List[str]:
- """Return posix-relative paths that would be included in a pack."""
- gitignore = _load_gitignore_patterns(root)
- included: List[str] = []
- root = os.path.abspath(root)
-
- for dirpath, dirnames, filenames in os.walk(root):
- rel_dir = os.path.relpath(dirpath, root)
- rel_dir_posix = "" if rel_dir == "." else rel_dir.replace("\\", "/")
-
- kept_dirs = []
- for dirname in dirnames:
- child_rel = f"{rel_dir_posix}/{dirname}" if rel_dir_posix else dirname
- if _should_exclude(child_rel, dirname, True, gitignore, include_env=include_env):
- continue
- kept_dirs.append(dirname)
- dirnames[:] = kept_dirs
-
- for filename in filenames:
- child_rel = f"{rel_dir_posix}/{filename}" if rel_dir_posix else filename
- if _should_exclude(child_rel, filename, False, gitignore, include_env=include_env):
- continue
- included.append(child_rel)
-
- if ".env.example" not in included:
- included.append(".env.example")
- included.sort()
- return included
-
-
-def _read_text(path: str) -> str:
- return read_text(path)
-
-
-def _parse_pyproject_field(text: str, field: str) -> Optional[str]:
- match = re.search(rf'^{field}\s*=\s*["\']([^"\']+)["\']', text, re.MULTILINE)
- return match.group(1) if match else None
-
-
-def _parse_pyproject_dependencies(text: str) -> List[str]:
- return parse_pyproject_dependencies(text)
-
-
-def _parse_requirements(path: str) -> List[str]:
- return parse_requirements(path)
-
-
-def _project_name_and_version(root: str) -> Tuple[str, str]:
- pyproject = os.path.join(root, "pyproject.toml")
- if os.path.isfile(pyproject):
- text = _read_text(pyproject)
- name = _parse_pyproject_field(text, "name")
- version = _parse_pyproject_field(text, "version")
- if name and version:
- return name, version
- if name:
- return name, version or "0.1.0"
- return os.path.basename(os.path.abspath(root)) or "nitrostack-project", "0.1.0"
-
-
-def _normalize_dist_name(name: str) -> str:
- normalized = re.sub(r"[-_.]+", "-", name).strip("-").lower()
- return normalized or "nitrostack-project"
-
-
-def _pep503_wheel_name(name: str) -> str:
- return re.sub(r"[-_.]+", "_", name)
-
-
-def _requirement_name(req: str) -> str:
- return requirement_name(req)
-
-
-def requirements_from_project(root: str) -> List[str]:
- pyproject = os.path.join(root, "pyproject.toml")
- req_path = os.path.join(root, "requirements.txt")
- deps: List[str] = []
- name, _ = _project_name_and_version(root)
- if os.path.isfile(pyproject):
- deps = _parse_pyproject_dependencies(_read_text(pyproject))
- if not deps and os.path.isfile(req_path):
- deps = _parse_requirements(req_path)
- deps = [item.lstrip("\ufeff").strip() for item in deps if item.lstrip("\ufeff").strip()]
- has_nitrostack = any(_requirement_name(item) == "nitrostack" for item in deps)
- if not has_nitrostack and name.lower() != "nitrostack":
- deps = ["nitrostack", *deps]
- return deps
-
-
-def write_requirements_txt(root: str, deps: Sequence[str]) -> str:
- path = os.path.join(root, "requirements.txt")
- body = "".join(f"{dep}\n" for dep in deps) if deps else "nitrostack\n"
- with open(path, "w", encoding="utf-8") as handle:
- handle.write(body)
- return path
-
-
-def _ensure_env_example(root: str) -> str:
- path = os.path.join(root, ".env.example")
- if not os.path.isfile(path):
- with open(path, "w", encoding="utf-8") as handle:
- handle.write(ENV_EXAMPLE_STUB)
- return path
-
-
-def _discover_py_modules_and_packages(root: str) -> Tuple[List[str], List[str]]:
- py_modules: List[str] = []
- packages: Set[str] = set()
- for dirpath, dirnames, filenames in os.walk(root):
- dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_DIR_NAMES and not d.endswith(".egg-info")]
- rel_dir = os.path.relpath(dirpath, root)
- if rel_dir == ".":
- for filename in filenames:
- if filename.endswith(".py") and filename != "setup.py":
- py_modules.append(os.path.splitext(filename)[0])
- continue
- parts = rel_dir.replace("\\", "/").split("/")
- if any(part in _EXCLUDE_DIR_NAMES for part in parts):
- continue
- if any(filename.endswith(".py") for filename in filenames):
- packages.add(".".join(parts))
- return sorted(py_modules), sorted(packages)
+from nitrostack.cli.telemetry import track_deploy_completed, track_deploy_failed
+
+# Keep the original import surface while implementations live by responsibility.
+from nitrostack.cli._pack_files import (
+ _EXCLUDE_DIR_NAMES, _EXCLUDE_NAME_GLOBS, _EXCLUDE_SUFFIXES,
+ _collect_staging_bytes, _copy_selected, _is_secret_env,
+ _load_gitignore_patterns, _matches_gitignore, _rmtree, _should_exclude,
+ collect_pack_files,
+)
+from nitrostack.cli._pack_metadata import (
+ ENV_EXAMPLE_STUB, _PYPROJECT_TEMPLATE, _discover_py_modules_and_packages,
+ _ensure_env_example, _ensure_pyproject, _normalize_dist_name,
+ _parse_pyproject_dependencies, _parse_pyproject_field, _parse_requirements,
+ _pep503_wheel_name, _project_name_and_version, _read_text, _requirement_name,
+ _toml_list, requirements_from_project, write_requirements_txt,
+)
+from nitrostack.cli import _pack_wheel
+from nitrostack.cli._pack_wheel import (
+ _inject_into_wheel, _is_valid_wheel, _setuptools_build_wheel,
+ _sha256_record, _write_purelib_wheel,
+)
-def _toml_list(values: Iterable[str]) -> str:
- items = ", ".join(f'"{v}"' for v in values)
- return f"[{items}]"
+def _secret_env_paths_in_pack(files: Sequence[str]) -> List[str]:
+ return sorted(rel for rel in files if _is_secret_env(rel.rsplit("/", 1)[-1]))
-def _ensure_pyproject(root: str, name: str, version: str, deps: Sequence[str]) -> None:
- path = os.path.join(root, "pyproject.toml")
- if os.path.isfile(path):
+def _warn_including_env_files(env_files: Sequence[str]) -> None:
+ if not env_files:
return
- py_modules, _packages = _discover_py_modules_and_packages(root)
- content = _PYPROJECT_TEMPLATE.format(
- name=_normalize_dist_name(name),
- version=version,
- deps=_toml_list(deps),
- py_modules=_toml_list(py_modules),
- )
- with open(path, "w", encoding="utf-8") as handle:
- handle.write(content)
-
-
-def _rmtree(path: str) -> None:
- def _onerror(func, p, _exc):
- try:
- os.chmod(p, stat.S_IWRITE)
- func(p)
- except OSError:
- pass
-
- shutil.rmtree(path, onerror=_onerror)
-
-
-def _copy_selected(src_root: str, dest_root: str, files: Sequence[str]) -> None:
- for rel in files:
- if rel == ".env.example":
- continue # handled separately so a stub can be created
- src = os.path.join(src_root, rel.replace("/", os.sep))
- dest = os.path.join(dest_root, rel.replace("/", os.sep))
- if not os.path.isfile(src):
- continue
- os.makedirs(os.path.dirname(dest) or dest_root, exist_ok=True)
- shutil.copy2(src, dest)
-
-
-def _sha256_record(data: bytes) -> str:
- import base64
- import hashlib
-
- digest = hashlib.sha256(data).digest()
- return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
-
-
-def _inject_into_wheel(wheel_path: str, files: Sequence[Tuple[str, str]]) -> None:
- """Add extra files to a built wheel and rewrite RECORD so the wheel stays valid."""
- with zipfile.ZipFile(wheel_path, "r") as src:
- contents = {name: src.read(name) for name in src.namelist()}
-
- for arcname, source in files:
- posix = arcname.replace("\\", "/")
- if posix in contents or not os.path.isfile(source):
- continue
- with open(source, "rb") as handle:
- contents[posix] = handle.read()
-
- record_name = next((n for n in contents if n.endswith(".dist-info/RECORD")), None)
- if record_name:
- rows = []
- for name in sorted(contents):
- if name == record_name:
- continue
- data = contents[name]
- rows.append(f"{name},{_sha256_record(data)},{len(data)}")
- rows.append(f"{record_name},,")
- contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8")
-
- tmp_path = wheel_path + ".tmp"
- with zipfile.ZipFile(tmp_path, "w", compression=zipfile.ZIP_DEFLATED) as dest:
- for name, data in contents.items():
- dest.writestr(name, data)
- os.replace(tmp_path, wheel_path)
-
-
-def _is_valid_wheel(path: str) -> bool:
- if not zipfile.is_zipfile(path):
- return False
- with zipfile.ZipFile(path, "r") as zf:
- names = zf.namelist()
- has_wheel = any(n.endswith(".dist-info/WHEEL") for n in names)
- has_meta = any(n.endswith(".dist-info/METADATA") for n in names)
- has_record = any(n.endswith(".dist-info/RECORD") for n in names)
- if not (has_wheel and has_meta and has_record):
- return False
- wheel_name = next(n for n in names if n.endswith(".dist-info/WHEEL"))
- body = zf.read(wheel_name).decode("utf-8", errors="replace")
- return "Wheel-Version:" in body
-
-
-def _collect_staging_bytes(src_root: str, *, include_env: bool = False) -> dict:
- contents = {}
- for dirpath, dirnames, filenames in os.walk(src_root):
- dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_DIR_NAMES and not d.endswith(".egg-info")]
- for filename in filenames:
- if any(filename.endswith(suffix) for suffix in _EXCLUDE_SUFFIXES):
- continue
- if _is_secret_env(filename) and not include_env:
- continue
- full = os.path.join(dirpath, filename)
- rel = os.path.relpath(full, src_root).replace("\\", "/")
- with open(full, "rb") as handle:
- contents[rel] = handle.read()
- return contents
-
-
-def _write_purelib_wheel(
- src_root: str,
- wheel_dir: str,
- name: str,
- version: str,
- deps: Sequence[str],
- *,
- include_env: bool = False,
-) -> str:
- """Write a PEP 427 py3-none-any wheel from the staged project files."""
- os.makedirs(wheel_dir, exist_ok=True)
- dist_name = _pep503_wheel_name(_normalize_dist_name(name))
- display_name = _normalize_dist_name(name)
- wheel_filename = f"{dist_name}-{version}-py3-none-any.whl"
- wheel_path = os.path.join(wheel_dir, wheel_filename)
- dist_info = f"{dist_name}-{version}.dist-info"
-
- contents = _collect_staging_bytes(src_root, include_env=include_env)
- metadata_lines = [
- "Metadata-Version: 2.1",
- f"Name: {display_name}",
- f"Version: {version}",
- "Summary: Packed NitroStack MCP server",
- "Requires-Python: >=3.10",
- ]
- for dep in deps:
- metadata_lines.append(f"Requires-Dist: {dep}")
- contents[f"{dist_info}/METADATA"] = ("\n".join(metadata_lines) + "\n").encode("utf-8")
- contents[f"{dist_info}/WHEEL"] = (
- "Wheel-Version: 1.0\n"
- "Generator: nitrostack-py pack\n"
- "Root-Is-Purelib: true\n"
- "Tag: py3-none-any\n"
- ).encode("utf-8")
-
- record_name = f"{dist_info}/RECORD"
- rows = []
- for arcname in sorted(contents):
- data = contents[arcname]
- rows.append(f"{arcname},{_sha256_record(data)},{len(data)}")
- rows.append(f"{record_name},,")
- contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8")
-
- with zipfile.ZipFile(wheel_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
- for arcname, data in contents.items():
- zf.writestr(arcname, data)
- return wheel_path
-
-
-def _setuptools_build_wheel(wheel_dir: str) -> str:
- from setuptools.build_meta import build_wheel as setuptools_build_wheel
- return setuptools_build_wheel(wheel_dir)
+ listed = ", ".join(env_files)
+ print(f"Warning: Including .env files in the wheel (use with caution!): {listed}")
def _build_wheel_with_setuptools(src_root: str, wheel_dir: str) -> Optional[str]:
- """Use the setuptools PEP 517 backend when it is importable."""
- os.makedirs(wheel_dir, exist_ok=True)
- previous = os.getcwd()
- try:
- os.chdir(src_root)
- filename = _setuptools_build_wheel(wheel_dir)
- except ImportError as exc:
- print(f"Warning: setuptools build backend unavailable, falling back: {exc}")
- return None
- except Exception as exc:
- print(f"Warning: setuptools build failed, falling back: {exc}")
- return None
- finally:
- os.chdir(previous)
- path = os.path.join(wheel_dir, filename)
- return path if os.path.isfile(path) else None
+ """Resolve the backend callback here so existing facade patches still apply."""
+ return _pack_wheel._build_wheel_with_setuptools(
+ src_root, wheel_dir, build_backend=_setuptools_build_wheel,
+ )
def _build_wheel(
@@ -454,24 +74,14 @@ def _build_wheel(
*,
include_env: bool = False,
) -> str:
- os.makedirs(wheel_dir, exist_ok=True)
- built = _build_wheel_with_setuptools(src_root, wheel_dir)
- if built:
- return built
- return _write_purelib_wheel(
- src_root, wheel_dir, name, version, deps, include_env=include_env
- )
-
+ def _write_purelib_with_env(sr, wd, n, v, d):
+ return _write_purelib_wheel(sr, wd, n, v, d, include_env=include_env)
-def _secret_env_paths_in_pack(files: Sequence[str]) -> List[str]:
- return sorted(rel for rel in files if _is_secret_env(rel.rsplit("/", 1)[-1]))
-
-
-def _warn_including_env_files(env_files: Sequence[str]) -> None:
- if not env_files:
- return
- listed = ", ".join(env_files)
- print(f"Warning: Including .env files in the wheel (use with caution!): {listed}")
+ return _pack_wheel._build_wheel(
+ src_root, wheel_dir, name, version, deps,
+ build_with_setuptools=_build_wheel_with_setuptools,
+ write_purelib=_write_purelib_with_env,
+ )
def pack_project(
@@ -509,33 +119,39 @@ def pack_project(
staging = tempfile.mkdtemp(prefix="nitrostack-pack-")
wheel_tmp = tempfile.mkdtemp(prefix="nitrostack-wheel-")
try:
- _copy_selected(root, staging, files)
- _ensure_env_example(staging)
- deps = requirements_from_project(root)
- write_requirements_txt(staging, deps)
- _ensure_pyproject(staging, name, version, deps)
-
- wheel_path = _build_wheel(
- staging, wheel_tmp, name, version, deps, include_env=include_env
- )
- extra = []
- env_example = os.path.join(staging, ".env.example")
- reqs = os.path.join(staging, "requirements.txt")
- extra.append((".env.example", env_example))
- extra.append(("requirements.txt", reqs))
- if include_env:
- for rel in _secret_env_paths_in_pack(files):
- extra.append((rel, os.path.join(staging, rel.replace("/", os.sep))))
- _inject_into_wheel(wheel_path, extra)
-
- if not _is_valid_wheel(wheel_path):
- raise RuntimeError(f"Built file is not a valid wheel: {wheel_path}")
-
- os.makedirs(dest_dir, exist_ok=True)
- final_path = os.path.join(dest_dir, os.path.basename(wheel_path))
- shutil.copy2(wheel_path, final_path)
- print(f"\nCreated wheel: {final_path}")
- return {"files": files, "wheel": final_path, "dry_run": False}
+ try:
+ _copy_selected(root, staging, files)
+ _ensure_env_example(staging)
+ deps = requirements_from_project(root)
+ write_requirements_txt(staging, deps)
+ _ensure_pyproject(staging, name, version, deps)
+
+ wheel_path = _build_wheel(
+ staging, wheel_tmp, name, version, deps, include_env=include_env,
+ )
+ extra = []
+ env_example = os.path.join(staging, ".env.example")
+ reqs = os.path.join(staging, "requirements.txt")
+ extra.append((".env.example", env_example))
+ extra.append(("requirements.txt", reqs))
+ if include_env:
+ for rel in _secret_env_paths_in_pack(files):
+ extra.append((rel, os.path.join(staging, rel.replace("/", os.sep))))
+ _inject_into_wheel(wheel_path, extra)
+
+ if not _is_valid_wheel(wheel_path):
+ raise RuntimeError(f"Built file is not a valid wheel: {wheel_path}")
+
+ os.makedirs(dest_dir, exist_ok=True)
+ final_path = os.path.join(dest_dir, os.path.basename(wheel_path))
+ shutil.copy2(wheel_path, final_path)
+ print(f"\nCreated wheel: {final_path}")
+ track_deploy_completed()
+ return {"files": files, "wheel": final_path, "dry_run": False}
+ except Exception as exc:
+ name_t = type(exc).__name__
+ track_deploy_failed(error_code=name_t[:80])
+ raise
finally:
_rmtree(staging)
- _rmtree(wheel_tmp)
+ _rmtree(wheel_tmp)
\ No newline at end of file
diff --git a/nitrostack/cli/telemetry.py b/nitrostack/cli/telemetry.py
new file mode 100644
index 0000000..edd854d
--- /dev/null
+++ b/nitrostack/cli/telemetry.py
@@ -0,0 +1,313 @@
+"""Opt-out PostHog telemetry for the NitroStack Python CLI (`nitrostack-py`).
+
+Non-blocking: events are queued by the PostHog SDK; call :func:`shutdown_telemetry`
+at process exit (short flush timeout). Never raises into user command paths.
+"""
+
+from __future__ import annotations
+
+import atexit
+import hashlib
+import logging
+import os
+import platform
+import socket
+import sys
+import threading
+from importlib import metadata
+from pathlib import Path
+from typing import Any, Dict, Mapping, Optional
+
+logger = logging.getLogger(__name__)
+
+PRODUCT = "python_sdk"
+SURFACE = "terminal"
+
+# Public PostHog project key (same CLI/SDK ingest as the TypeScript CLI).
+# Override with NITROSTACK_POSTHOG_KEY.
+DEFAULT_POSTHOG_PROJECT_KEY = "phc_" + "OufG1OuiamSbCBMVHfO70IyFWKBzsiaDpOWqcNwtz6G"
+DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com"
+
+_TRUE = frozenset({"1", "true", "yes", "on"})
+_FALSE = frozenset({"0", "false", "no", "off"})
+
+_POSTHOG_LOCK = threading.Lock()
+_client: Any = None
+_posthog_unavailable = False
+_anonymous_distinct_id: Optional[str] = None
+_distinct_id_override: Optional[str] = None
+_shutdown_done = False
+
+
+def _env_truthy(name: str) -> bool:
+ v = (os.environ.get(name) or "").strip().lower()
+ return v in _TRUE
+
+
+def _env_falsy(name: str) -> bool:
+ v = (os.environ.get(name) or "").strip().lower()
+ return v in _FALSE
+
+
+def resolved_posthog_api_key() -> str:
+ """PostHog project API key: ``NITROSTACK_POSTHOG_KEY`` if set, else built-in default."""
+ env = (os.environ.get("NITROSTACK_POSTHOG_KEY") or "").strip()
+ if env:
+ return env
+ return DEFAULT_POSTHOG_PROJECT_KEY
+
+
+def resolved_posthog_host() -> str:
+ """PostHog ingest host (default US Cloud)."""
+ return (os.environ.get("NITROSTACK_POSTHOG_HOST") or DEFAULT_POSTHOG_HOST).strip()
+
+
+def is_telemetry_disabled() -> bool:
+ """True when capture must not run (opt-out, tests, CI, or missing configuration)."""
+ if _env_truthy("DO_NOT_TRACK") or _env_truthy("PYTEST_CURRENT_TEST"):
+ return True
+ if _env_falsy("NITROSTACK_TELEMETRY"):
+ return True
+ if (os.environ.get("NITROSTACK_TELEMETRY") or "").strip() == "":
+ if _env_truthy("CI") or os.environ.get("GITHUB_ACTIONS"):
+ return True
+ return False
+
+
+def _sdk_version() -> str:
+ try:
+ return metadata.version("nitrostack")
+ except metadata.PackageNotFoundError:
+ return "unknown"
+
+
+def _runtime_environment() -> str:
+ explicit = (os.environ.get("NITROSTACK_ENVIRONMENT") or "").strip().lower()
+ if explicit in ("production", "staging", "development"):
+ return explicit
+ node_env = (os.environ.get("NODE_ENV") or "").lower()
+ if _env_truthy("NITROSTACK_PRODUCTION") or node_env == "production":
+ return "production"
+ if (os.environ.get("ENVIRONMENT") or "").strip().lower() == "staging":
+ return "staging"
+ return "development"
+
+
+def _anonymous_id_from_machine() -> str:
+ global _anonymous_distinct_id
+ if _anonymous_distinct_id is not None:
+ return _anonymous_distinct_id
+ try:
+ user = os.environ.get("USER") or os.environ.get("USERNAME") or "unknown"
+ raw = f"{socket.gethostname()}:{user}".encode("utf-8", errors="replace")
+ _anonymous_distinct_id = hashlib.sha256(raw).hexdigest()[:16]
+ except Exception:
+ _anonymous_distinct_id = "anonymous"
+ return _anonymous_distinct_id
+
+
+def get_distinct_id() -> str:
+ """Current analytics distinct id (Cloud user id after login, else anonymous hash)."""
+ if _distinct_id_override:
+ return _distinct_id_override
+ return _anonymous_id_from_machine()
+
+
+def _super_properties() -> Dict[str, Any]:
+ return {
+ "product": PRODUCT,
+ "surface": SURFACE,
+ "environment": _runtime_environment(),
+ "app_version": _sdk_version(),
+ "python_version": platform.python_version(),
+ "sdk_version": _sdk_version(),
+ "os_platform": sys.platform,
+ "os_arch": platform.machine() or "unknown",
+ }
+
+
+def _get_client() -> Any:
+ global _client, _posthog_unavailable
+ if is_telemetry_disabled():
+ return None
+ if _posthog_unavailable:
+ return None
+ with _POSTHOG_LOCK:
+ if _client is None:
+ try:
+ from posthog import Posthog
+ except ImportError:
+ _posthog_unavailable = True
+ logger.debug("nitrostack telemetry: posthog package not installed")
+ return None
+
+ api_key = resolved_posthog_api_key()
+ host = resolved_posthog_host()
+ _client = Posthog(
+ api_key,
+ host=host,
+ flush_at=10,
+ flush_interval=0.5,
+ )
+ return _client
+
+
+def track_event(event: str, properties: Optional[Mapping[str, Any]] = None) -> None:
+ """Fire-and-forget capture; swallowed on failure."""
+ if is_telemetry_disabled():
+ return
+ client = _get_client()
+ if client is None:
+ return
+ props: Dict[str, Any] = dict(_super_properties())
+ if properties:
+ props.update(dict(properties))
+ try:
+ client.capture(distinct_id=get_distinct_id(), event=event, properties=props)
+ except Exception:
+ logger.debug("nitrostack telemetry: capture failed", exc_info=True)
+
+
+def track_command_invoked(command: str) -> None:
+ track_event("cli_command_invoked", {"command": command})
+
+
+def track_init_completed(
+ *,
+ template: str,
+ skip_install: bool,
+ duration_ms: int,
+ has_custom_description: bool,
+) -> None:
+ track_event(
+ "cli_init_completed",
+ {
+ "template": template,
+ "skip_install": skip_install,
+ "duration_ms": duration_ms,
+ "has_custom_description": has_custom_description,
+ },
+ )
+
+
+def track_deploy_completed() -> None:
+ track_event("cli_deploy_completed", {})
+
+
+def track_deploy_failed(*, error_code: str) -> None:
+ track_event("cli_deploy_failed", {"error_code": error_code})
+
+
+def identify_from_cloud_login(
+ *,
+ user_id: str,
+ email: str,
+ organization_id: Optional[str] = None,
+) -> None:
+ """Alias anonymous device id to Cloud user id, identify, optional org group, then journey event.
+
+ Call when a future `login` flow succeeds, matching intended TS CLI behaviour (#9).
+ """
+ global _distinct_id_override
+ if is_telemetry_disabled():
+ return
+ client = _get_client()
+ if client is None:
+ return
+ anonymous = _anonymous_id_from_machine()
+ uid = (user_id or "").strip()
+ em = (email or "").strip()
+ if not uid or not em:
+ return
+ props = _super_properties()
+ props["user_email"] = em
+ props["cloud_user_id"] = uid
+ try:
+ client.alias(previous_id=anonymous, distinct_id=uid)
+ client.identify(distinct_id=uid, properties={"email": em})
+ if organization_id:
+ client.group_identify(
+ "organization",
+ organization_id,
+ properties={},
+ distinct_id=uid,
+ )
+ _distinct_id_override = uid
+ client.capture(
+ distinct_id=uid,
+ event="cli_login_completed",
+ properties={
+ **props,
+ "user_email": em,
+ "cloud_user_id": uid,
+ },
+ )
+ except Exception:
+ logger.debug("nitrostack telemetry: identify/login failed", exc_info=True)
+
+
+def _config_dir() -> Path:
+ if sys.platform == "win32":
+ base = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA")
+ if base:
+ return Path(base) / "NitroStack"
+ return Path.home() / ".config" / "nitrostack"
+
+
+def _first_run_flag_path() -> Path:
+ return _config_dir() / ".telemetry_first_run_notice_shown"
+
+
+def maybe_print_first_run_notice() -> None:
+ """One-line notice on first CLI invocation (when telemetry may send)."""
+ if is_telemetry_disabled():
+ return
+ path = _first_run_flag_path()
+ try:
+ if path.exists():
+ return
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("1\n", encoding="utf-8")
+ except OSError:
+ return
+ msg = (
+ "NitroStack: anonymous usage telemetry is enabled. "
+ "Disable with DO_NOT_TRACK=1 or NITROSTACK_TELEMETRY=0.\n"
+ )
+ try:
+ sys.stderr.write(msg)
+ sys.stderr.flush()
+ except OSError:
+ pass
+
+
+def shutdown_telemetry(timeout: float = 2.0) -> None:
+ """Flush queued events without blocking the user indefinitely."""
+ global _client, _shutdown_done
+ if _shutdown_done:
+ return
+ _shutdown_done = True
+ c = _client
+ if c is None:
+ return
+
+ def _run() -> None:
+ try:
+ c.shutdown()
+ except Exception:
+ logger.debug("nitrostack telemetry: shutdown failed", exc_info=True)
+
+ t = threading.Thread(target=_run, name="nitrostack-telemetry-shutdown", daemon=True)
+ t.start()
+ t.join(timeout=timeout)
+
+
+def _atexit_shutdown() -> None:
+ if is_telemetry_disabled():
+ return
+ shutdown_telemetry()
+
+
+# Avoid duplicate handlers under pytest reloads; tests call shutdown explicitly.
+if not os.environ.get("PYTEST_CURRENT_TEST"):
+ atexit.register(_atexit_shutdown)
diff --git a/nitrostack/cli/templates/legacy_app_module_template.txt b/nitrostack/cli/templates/legacy_app_module_template.txt
new file mode 100644
index 0000000..5e018a5
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_app_module_template.txt
@@ -0,0 +1,12 @@
+from nitrostack import module
+from modules.calculator.calculator_module import CalculatorModule
+
+@module(
+ name="app",
+ imports=[CalculatorModule],
+ controllers=[],
+ providers=[],
+ exports=[]
+)
+class AppModule:
+ pass
diff --git a/nitrostack/cli/templates/legacy_calc_module_template.txt b/nitrostack/cli/templates/legacy_calc_module_template.txt
new file mode 100644
index 0000000..2996ee1
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_calc_module_template.txt
@@ -0,0 +1,13 @@
+from nitrostack import module
+from modules.calculator.calculator_tools import CalculatorController
+from modules.calculator.calculator_service import CalculatorService
+
+@module(
+ name="calculator",
+ imports=[],
+ controllers=[CalculatorController],
+ providers=[CalculatorService],
+ exports=[CalculatorService]
+)
+class CalculatorModule:
+ pass
diff --git a/nitrostack/cli/templates/legacy_calc_service_template.txt b/nitrostack/cli/templates/legacy_calc_service_template.txt
new file mode 100644
index 0000000..f90382d
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_calc_service_template.txt
@@ -0,0 +1,6 @@
+from nitrostack import injectable
+
+@injectable(deps=[])
+class CalculatorService:
+ def add(self, a: float, b: float) -> float:
+ return a + b
diff --git a/nitrostack/cli/templates/legacy_calc_tools_template.txt b/nitrostack/cli/templates/legacy_calc_tools_template.txt
new file mode 100644
index 0000000..6a216db
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_calc_tools_template.txt
@@ -0,0 +1,21 @@
+from nitrostack import injectable, tool, ExecutionContext
+from modules.calculator.calculator_service import CalculatorService
+from pydantic import BaseModel
+
+class AddInput(BaseModel):
+ a: float
+ b: float
+
+@injectable(deps=[CalculatorService])
+class CalculatorController:
+ def __init__(self, service: CalculatorService):
+ self.service = service
+
+ @tool(
+ name="add",
+ description="Add two numbers together",
+ input_schema=AddInput
+ )
+ async def add(self, input: AddInput, context: ExecutionContext) -> float:
+ context.logger.info(f"Adding {input.a} and {input.b}")
+ return self.service.add(input.a, input.b)
diff --git a/nitrostack/cli/templates/legacy_env_template.txt b/nitrostack/cli/templates/legacy_env_template.txt
new file mode 100644
index 0000000..766252b
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_env_template.txt
@@ -0,0 +1,2 @@
+PORT=3000
+NODE_ENV=development
diff --git a/nitrostack/cli/templates/legacy_flight_app_module_template.txt b/nitrostack/cli/templates/legacy_flight_app_module_template.txt
new file mode 100644
index 0000000..f7e8bae
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_app_module_template.txt
@@ -0,0 +1,31 @@
+from nitrostack import module, ConfigModule, OAuthModule
+from modules.flights.flights_module import FlightsModule
+from health.system_health import SystemHealthCheck
+import os
+
+@module(
+ name="app",
+ imports=[
+ ConfigModule.for_root(
+ env_file_path=".env",
+ defaults={"RESOURCE_URI": "https://mcplocal", "PORT": "3000"}
+ ),
+ # Configure OAuth resource protection
+ OAuthModule.for_root(
+ resource_uri=os.environ.get("RESOURCE_URI", "https://mcplocal"),
+ authorization_servers=[os.environ.get("AUTH_SERVER_URL", "https://dev-5dt0utuk315713tjm.us.auth0.com")],
+ scopes_supported=["read", "write", "admin"],
+ token_introspection_endpoint=os.environ.get("INTROSPECTION_ENDPOINT"),
+ token_introspection_client_id=os.environ.get("INTROSPECTION_CLIENT_ID"),
+ token_introspection_client_secret=os.environ.get("INTROSPECTION_CLIENT_SECRET"),
+ audience=os.environ.get("TOKEN_AUDIENCE"),
+ issuer=os.environ.get("TOKEN_ISSUER")
+ ),
+ FlightsModule
+ ],
+ controllers=[],
+ providers=[SystemHealthCheck],
+ exports=[]
+)
+class AppModule:
+ pass
diff --git a/nitrostack/cli/templates/legacy_flight_booking_tools_template.txt b/nitrostack/cli/templates/legacy_flight_booking_tools_template.txt
new file mode 100644
index 0000000..c6ccb02
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_booking_tools_template.txt
@@ -0,0 +1,92 @@
+from nitrostack import injectable, tool, use_guards, OAuthGuard, ExecutionContext
+from services.duffel_service import DuffelService
+from guards.oauth_guard import create_scope_guard
+from pydantic import BaseModel, Field
+import json
+
+class CreateOrderInput(BaseModel):
+ offerId: str = Field(description="The offer ID to book")
+ passengers: str = Field(description="JSON string containing array of passenger objects. Each passenger must have: title (mr/ms/mrs/miss/dr), givenName (first name), familyName (last name), gender (M/F), bornOn (YYYY-MM-DD), email, phoneNumber.")
+
+class OrderDetailsInput(BaseModel):
+ orderId: str = Field(description="The order ID")
+
+class SeatMapInput(BaseModel):
+ offerId: str = Field(description="The offer ID to get seats for")
+
+class CancelOrderInput(BaseModel):
+ orderId: str = Field(description="The order ID to cancel")
+
+@injectable(deps=[DuffelService])
+class BookingTools:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @tool(
+ name="create_order",
+ title="Create Order",
+ description="Create a flight order with hold (no payment required). Collect passenger details first.",
+ input_schema=CreateOrderInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["write"]))
+ async def create_order(self, input: CreateOrderInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Creating flight order for offer {input.offerId}")
+ try:
+ passengers_array = json.loads(input.passengers)
+ except Exception:
+ raise ValueError("Invalid passengers JSON format")
+
+ passengers = []
+ for p in passengers_array:
+ passengers.append({
+ "title": p.get("title", "mr"),
+ "given_name": p.get("givenName"),
+ "family_name": p.get("familyName"),
+ "gender": p.get("gender", "M"),
+ "born_on": p.get("bornOn"),
+ "email": p.get("email"),
+ "phone_number": p.get("phoneNumber")
+ })
+
+ order_params = {
+ "selectedOffers": [input.offerId],
+ "passengers": passengers
+ }
+ res = await self.service.create_order(order_params)
+ return res
+
+ @tool(
+ name="get_order_details",
+ title="Get Order Details",
+ description="Get detailed information about an order.",
+ input_schema=OrderDetailsInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ async def get_order_details(self, input: OrderDetailsInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Fetching details for order {input.orderId}")
+ res = await self.service.get_order(input.orderId)
+ return res
+
+ @tool(
+ name="get_seat_map",
+ title="Get Seat Map",
+ description="Get available seats for a flight offer to allow seat selection.",
+ input_schema=SeatMapInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ async def get_seat_map(self, input: SeatMapInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Fetching seat map for offer {input.offerId}")
+ res = await self.service.get_seats_for_offer(input.offerId)
+ return {"offerId": input.offerId, "cabins": res}
+
+ @tool(
+ name="cancel_order",
+ title="Cancel Order",
+ description="Cancel a flight order and request refund if applicable.",
+ input_schema=CancelOrderInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["write"]))
+ async def cancel_order(self, input: CancelOrderInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Cancelling order {input.orderId}")
+ res = await self.service.cancel_order(input.orderId)
+ return res
diff --git a/nitrostack/cli/templates/legacy_flight_duffel_service_template.txt b/nitrostack/cli/templates/legacy_flight_duffel_service_template.txt
new file mode 100644
index 0000000..8eaa8b7
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_duffel_service_template.txt
@@ -0,0 +1,264 @@
+import os
+import sys
+import json
+import urllib.request
+import urllib.parse
+from typing import List, Dict, Any, Optional
+from nitrostack import injectable
+
+@injectable()
+class DuffelService:
+ def __init__(self):
+ self.api_key = os.environ.get("DUFFEL_API_KEY")
+ self.is_mock = not self.api_key or self.api_key.startswith("your-") or len(self.api_key) < 5
+
+ def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+ if self.is_mock:
+ raise ValueError("Duffel API key is not configured. Running in mock mode.")
+
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Duffel-Version": "v2",
+ "Content-Type": "application/json"
+ }
+ url = f"https://api.duffel.com{path}"
+ req_data = json.dumps({"data": data}).encode("utf-8") if data else None
+
+ req = urllib.request.Request(url, data=req_data, headers=headers, method=method)
+ try:
+ with urllib.request.urlopen(req, timeout=10) as response:
+ res_payload = json.loads(response.read().decode("utf-8"))
+ return res_payload.get("data", {})
+ except Exception as e:
+ sys.stderr.write(f"Duffel API Request failed: {e}\n")
+ sys.stderr.flush()
+ raise e
+
+ async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": "orq_mock123456",
+ "offers": [
+ {
+ "id": "off_mock123456",
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "slices": [
+ {
+ "origin": {"iata_code": params["origin"], "name": "Origin Airport", "city_name": "Origin City"},
+ "destination": {"iata_code": params["destination"], "name": "Dest Airport", "city_name": "Dest City"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "id": "seg_outbound",
+ "origin": {"iata_code": params["origin"]},
+ "destination": {"iata_code": params["destination"]},
+ "departing_at": f"{params['departureDate']}T08:00:00Z",
+ "arriving_at": f"{params['departureDate']}T14:30:00Z",
+ "marketing_carrier": {"name": "Mock Airlines"},
+ "marketing_carrier_flight_number": "MK123",
+ "aircraft": {"name": "Boeing 787"}
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+
+ slices = [
+ {
+ "origin": params["origin"],
+ "destination": params["destination"],
+ "departure_date": params["departureDate"]
+ }
+ ]
+ if params.get("returnDate"):
+ slices.append({
+ "origin": params["destination"],
+ "destination": params["origin"],
+ "departure_date": params["returnDate"]
+ })
+
+ duffel_params = {
+ "slices": slices,
+ "passengers": params.get("passengers", [{"type": "adult"}]),
+ "cabin_class": params.get("cabinClass", "economy"),
+ "return_offers": True
+ }
+ res = self._request("POST", "/air/offer_requests", duffel_params)
+ return {
+ "id": res.get("id"),
+ "offers": res.get("offers", []),
+ "passengers": res.get("passengers", []),
+ "slices": res.get("slices", [])
+ }
+
+ async def get_offer(self, offer_id: str) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": offer_id,
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "slices": [
+ {
+ "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
+ "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "id": "seg_mock",
+ "origin": {"iata_code": "JFK"},
+ "destination": {"iata_code": "LAX"},
+ "departing_at": "2026-07-15T08:00:00Z",
+ "arriving_at": "2026-07-15T14:30:00Z",
+ "marketing_carrier": {"name": "Mock Airlines"},
+ "marketing_carrier_flight_number": "MK123",
+ "aircraft": {"name": "Boeing 787"}
+ }
+ ]
+ }
+ ]
+ }
+ return self._request("GET", f"/air/offers/{offer_id}")
+
+ async def get_seats_for_offer(self, offer_id: str) -> List[Dict[str, Any]]:
+ if self.is_mock:
+ return [
+ {
+ "cabin_class": "economy",
+ "rows": [
+ {
+ "row_number": 10,
+ "sections": [
+ {
+ "elements": [
+ {
+ "type": "seat",
+ "id": "seat_10a",
+ "designator": "10A",
+ "available_services": [{"total_amount": "25.00", "total_currency": "USD"}],
+ "disclosures": ["window"]
+ },
+ {
+ "type": "seat",
+ "id": "seat_10b",
+ "designator": "10B",
+ "available_services": [{"total_amount": "0.00", "total_currency": "USD"}],
+ "disclosures": ["middle"]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ res = self._request("GET", f"/air/seat_maps?offer_id={offer_id}")
+ return res if isinstance(res, list) else []
+
+ async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": "ord_mock123456",
+ "status": "held",
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "booking_reference": "ABCXYZ",
+ "passengers": [
+ {
+ "id": f"pax_{idx}",
+ "given_name": p["given_name"],
+ "family_name": p["family_name"],
+ "type": "adult"
+ } for idx, p in enumerate(params["passengers"])
+ ],
+ "slices": [
+ {
+ "origin": {"iata_code": "JFK"},
+ "destination": {"iata_code": "LAX"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "departing_at": "2026-07-15T08:00:00Z",
+ "arriving_at": "2026-07-15T14:30:00Z"
+ }
+ ]
+ }
+ ]
+ }
+
+ order_payload = {
+ "selected_offers": params["selectedOffers"],
+ "passengers": params["passengers"],
+ "type": "hold"
+ }
+ return self._request("POST", "/air/orders", order_payload)
+
+ async def get_order(self, order_id: str) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": order_id,
+ "status": "held",
+ "total_amount": "450.00",
+ "total_currency": "USD",
+ "booking_reference": "ABCXYZ",
+ "created_at": "2026-06-25T12:00:00Z",
+ "expires_at": "2026-12-31T12:00:00Z",
+ "passengers": [
+ {
+ "id": "pax_0",
+ "given_name": "John",
+ "family_name": "Doe",
+ "type": "adult",
+ "email": "john@example.com",
+ "phone_number": "+1234567890"
+ }
+ ],
+ "slices": [
+ {
+ "id": "sli_mock",
+ "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"},
+ "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"},
+ "duration": "PT6H30M",
+ "segments": [
+ {
+ "id": "seg_mock",
+ "origin": {"iata_code": "JFK"},
+ "destination": {"iata_code": "LAX"},
+ "departing_at": "2026-07-15T08:00:00Z",
+ "arriving_at": "2026-07-15T14:30:00Z",
+ "marketing_carrier": {"name": "Mock Airlines"},
+ "marketing_carrier_flight_number": "MK123",
+ "aircraft": {"name": "Boeing 787"}
+ }
+ ]
+ }
+ ]
+ }
+ return self._request("GET", f"/air/orders/{order_id}")
+
+ async def cancel_order(self, order_id: str) -> Dict[str, Any]:
+ if self.is_mock:
+ return {
+ "id": "ocr_mock123456",
+ "refund_amount": "450.00",
+ "refund_currency": "USD",
+ "confirmed_at": "2026-06-25T12:30:00Z"
+ }
+ cancel_payload = {"order_id": order_id}
+ return self._request("POST", "/air/order_cancellations", cancel_payload)
+
+ async def get_airlines(self) -> List[Dict[str, Any]]:
+ if self.is_mock:
+ return [
+ {"iata_code": "AA", "name": "American Airlines"},
+ {"iata_code": "DL", "name": "Delta Air Lines"},
+ {"iata_code": "UA", "name": "United Airlines"},
+ {"iata_code": "BA", "name": "British Airways"}
+ ]
+ res = self._request("GET", "/air/airlines")
+ return res if isinstance(res, list) else []
diff --git a/nitrostack/cli/templates/legacy_flight_module_template.txt b/nitrostack/cli/templates/legacy_flight_module_template.txt
new file mode 100644
index 0000000..a7b3d9f
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_module_template.txt
@@ -0,0 +1,15 @@
+from nitrostack import module
+from modules.flights.flights_tools import FlightTools
+from modules.flights.booking_tools import BookingTools
+from modules.flights.flights_prompts import FlightPrompts
+from modules.flights.flights_resources import FlightResources
+from services.duffel_service import DuffelService
+
+@module(
+ name="flights",
+ controllers=[FlightTools, BookingTools, FlightPrompts, FlightResources],
+ providers=[DuffelService],
+ exports=[DuffelService]
+)
+class FlightsModule:
+ pass
diff --git a/nitrostack/cli/templates/legacy_flight_oauth_guard_template.txt b/nitrostack/cli/templates/legacy_flight_oauth_guard_template.txt
new file mode 100644
index 0000000..03c3a07
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_oauth_guard_template.txt
@@ -0,0 +1,14 @@
+from nitrostack import ExecutionContext
+
+def create_scope_guard(required_scopes: list):
+ class ScopeGuard:
+ async def can_activate(self, context: ExecutionContext) -> bool:
+ user_scopes = getattr(context.auth, "scopes", [])
+ missing_scopes = [s for s in required_scopes if s not in user_scopes]
+ if missing_scopes:
+ raise ValueError(
+ f"Insufficient scope. Required: {', '.join(required_scopes)}. "
+ f"Missing: {', '.join(missing_scopes)}"
+ )
+ return True
+ return ScopeGuard
diff --git a/nitrostack/cli/templates/legacy_flight_prompts_template.txt b/nitrostack/cli/templates/legacy_flight_prompts_template.txt
new file mode 100644
index 0000000..a6b797b
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_prompts_template.txt
@@ -0,0 +1,22 @@
+from nitrostack import injectable, prompt, ExecutionContext
+from services.duffel_service import DuffelService
+from typing import List
+
+@injectable(deps=[DuffelService])
+class FlightPrompts:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @prompt(
+ name="flight_search_assistant",
+ description="An AI assistant specialized in helping users search for flights and make booking decisions."
+ )
+ async def flight_search_assistant(self, args: dict, context: ExecutionContext) -> str:
+ return "You are a professional flight booking assistant. Help the user search for flights using search_flights, search_airports, and assist in booking holds."
+
+ @prompt(
+ name="flight_comparison",
+ description="Compare multiple flight offers and provide recommendations."
+ )
+ async def flight_comparison(self, args: dict, context: ExecutionContext) -> str:
+ return "Compare the provided flight offer details, check layover times, durations, and pricing, and give the user a summary of best options."
diff --git a/nitrostack/cli/templates/legacy_flight_resources_template.txt b/nitrostack/cli/templates/legacy_flight_resources_template.txt
new file mode 100644
index 0000000..f542dd0
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_resources_template.txt
@@ -0,0 +1,30 @@
+from nitrostack import injectable, resource, ExecutionContext
+from services.duffel_service import DuffelService
+
+@injectable(deps=[DuffelService])
+class FlightResources:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @resource(
+ uri="flight://popular-routes",
+ name="Popular Flight Routes",
+ description="Information about popular routes and pricing",
+ mime_type="application/json"
+ )
+ async def popular_routes(self, context: ExecutionContext) -> dict:
+ return {
+ "routes": [
+ {"route": "JFK -> LAX", "price": "$200-400"},
+ {"route": "LHR -> JFK", "price": "$400-800"}
+ ]
+ }
+
+ @resource(
+ uri="flight://booking-guide",
+ name="Flight Booking Guide",
+ description="Guide on searching and booking flights",
+ mime_type="text/markdown"
+ )
+ async def booking_guide(self, context: ExecutionContext) -> str:
+ return "# Flight Booking Guide\n\n1. Search flights.\n2. Collect passenger info.\n3. Create order hold."
diff --git a/nitrostack/cli/templates/legacy_flight_system_health_template.txt b/nitrostack/cli/templates/legacy_flight_system_health_template.txt
new file mode 100644
index 0000000..1e1a3bb
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_system_health_template.txt
@@ -0,0 +1,11 @@
+import time
+from nitrostack import health_check
+
+class SystemHealthCheck:
+ def __init__(self):
+ self.start_time = time.time()
+
+ @health_check("system")
+ def check_system(self) -> bool:
+ uptime = time.time() - self.start_time
+ return uptime >= 0
diff --git a/nitrostack/cli/templates/legacy_flight_tools_template.txt b/nitrostack/cli/templates/legacy_flight_tools_template.txt
new file mode 100644
index 0000000..fc5ed8a
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_flight_tools_template.txt
@@ -0,0 +1,74 @@
+from nitrostack import injectable, tool, use_guards, OAuthGuard, ExecutionContext
+from services.duffel_service import DuffelService
+from guards.oauth_guard import create_scope_guard
+from pydantic import BaseModel, Field
+from typing import Optional
+
+class SearchFlightsInput(BaseModel):
+ origin: str = Field(description="Origin airport IATA code (e.g., 'JFK', 'LHR')")
+ destination: str = Field(description="Destination airport IATA code (e.g., 'LAX', 'CDG')")
+ departureDate: str = Field(description="Departure date in YYYY-MM-DD format")
+ returnDate: Optional[str] = Field(default=None, description="Return date in YYYY-MM-DD format for round trip")
+ adults: int = Field(default=1, description="Number of adult passengers (18+)")
+ cabinClass: str = Field(default="economy", description="Preferred cabin class (economy, premium_economy, business, first)")
+
+class FlightDetailsInput(BaseModel):
+ offerId: str = Field(description="The flight offer ID from search results")
+
+class AirportSearchInput(BaseModel):
+ query: str = Field(description="The search query for airports (e.g., 'London', 'New York')")
+
+class GetAirlinesInput(BaseModel):
+ pass
+
+@injectable(deps=[DuffelService])
+class FlightTools:
+ def __init__(self, service: DuffelService):
+ self.service = service
+
+ @tool(
+ name="search_flights",
+ title="Search Flights",
+ description="Search for flight offers based on origin, destination, dates, and preferences.",
+ input_schema=SearchFlightsInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ async def search_flights(self, input: SearchFlightsInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Searching flights from {input.origin} to {input.destination}")
+ res = await self.service.search_flights(input.model_dump())
+ return res
+
+ @tool(
+ name="get_flight_details",
+ title="Get Flight Details",
+ description="Get detailed information about a specific flight offer including baggage allowance, conditions.",
+ input_schema=FlightDetailsInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ async def get_flight_details(self, input: FlightDetailsInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Fetching flight details for offer {input.offerId}")
+ res = await self.service.get_offer(input.offerId)
+ return res
+
+ @tool(
+ name="search_airports",
+ title="Search Airports",
+ description="Search for airports by query string.",
+ input_schema=AirportSearchInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ async def search_airports(self, input: AirportSearchInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Searching airports for query: {input.query}")
+ return {"airports": [{"iataCode": "JFK", "name": "John F. Kennedy Airport"}]}
+
+ @tool(
+ name="get_airlines",
+ title="Get Airlines",
+ description="Get list of common airlines.",
+ input_schema=GetAirlinesInput
+ )
+ @use_guards(OAuthGuard, create_scope_guard(["read"]))
+ async def get_airlines(self, input: GetAirlinesInput, context: ExecutionContext) -> dict:
+ context.logger.info("Fetching common airlines")
+ res = await self.service.get_airlines()
+ return {"airlines": res}
diff --git a/nitrostack/cli/templates/legacy_food_app_module_template.txt b/nitrostack/cli/templates/legacy_food_app_module_template.txt
new file mode 100644
index 0000000..f0c130a
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_food_app_module_template.txt
@@ -0,0 +1,12 @@
+from nitrostack import module
+from modules.food_delivery.food_delivery_module import FoodDeliveryModule
+
+@module(
+ name="app",
+ imports=[FoodDeliveryModule],
+ controllers=[],
+ providers=[],
+ exports=[]
+)
+class AppModule:
+ pass
diff --git a/nitrostack/cli/templates/legacy_food_delivery_module_template.txt b/nitrostack/cli/templates/legacy_food_delivery_module_template.txt
new file mode 100644
index 0000000..f8f1431
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_food_delivery_module_template.txt
@@ -0,0 +1,13 @@
+from nitrostack import module
+from modules.food_delivery.food_delivery_tools import FoodDeliveryController
+from modules.food_delivery.food_delivery_service import FoodDeliveryService
+
+@module(
+ name="food_delivery",
+ imports=[],
+ controllers=[FoodDeliveryController],
+ providers=[FoodDeliveryService],
+ exports=[FoodDeliveryService]
+)
+class FoodDeliveryModule:
+ pass
diff --git a/nitrostack/cli/templates/legacy_food_delivery_service_template.txt b/nitrostack/cli/templates/legacy_food_delivery_service_template.txt
new file mode 100644
index 0000000..f2eddaf
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_food_delivery_service_template.txt
@@ -0,0 +1,41 @@
+from nitrostack import injectable
+
+@injectable(deps=[])
+class FoodDeliveryService:
+ def __init__(self):
+ # In-memory database of items and orders
+ self.menu = {
+ "pizza": {"price": 12.99, "prep_time": 15},
+ "burger": {"price": 8.99, "prep_time": 10},
+ "salad": {"price": 7.49, "prep_time": 5},
+ "sushi": {"price": 15.99, "prep_time": 20}
+ }
+ self.orders = {}
+ self.order_counter = 1000
+
+ def get_menu(self):
+ return self.menu
+
+ def place_order(self, item: str, quantity: int) -> dict:
+ item_lower = item.lower()
+ if item_lower not in self.menu:
+ return {"status": "error", "message": f"Item '{item}' not found in the menu."}
+
+ self.order_counter += 1
+ order_id = f"ORDER-{self.order_counter}"
+
+ price = self.menu[item_lower]["price"] * quantity
+ prep_time = self.menu[item_lower]["prep_time"]
+
+ self.orders[order_id] = {
+ "order_id": order_id,
+ "item": item_lower,
+ "quantity": quantity,
+ "total_price": round(price, 2),
+ "status": "Preparing",
+ "time_remaining": prep_time
+ }
+ return self.orders[order_id]
+
+ def get_order_status(self, order_id: str) -> dict:
+ return self.orders.get(order_id, {"status": "error", "message": f"Order {order_id} not found."})
diff --git a/nitrostack/cli/templates/legacy_food_delivery_tools_template.txt b/nitrostack/cli/templates/legacy_food_delivery_tools_template.txt
new file mode 100644
index 0000000..46efa3f
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_food_delivery_tools_template.txt
@@ -0,0 +1,45 @@
+from nitrostack import injectable, tool, ExecutionContext
+from modules.food_delivery.food_delivery_service import FoodDeliveryService
+from pydantic import BaseModel, Field
+
+class ViewMenuInput(BaseModel):
+ pass
+
+class PlaceOrderInput(BaseModel):
+ item: str = Field(description="The food item to order (e.g., pizza, burger, salad, sushi)")
+ quantity: int = Field(default=1, description="Number of items to order")
+
+class OrderStatusInput(BaseModel):
+ order_id: str = Field(description="The ID of the order to track (e.g., ORDER-1001)")
+
+@injectable(deps=[FoodDeliveryService])
+class FoodDeliveryController:
+ def __init__(self, service: FoodDeliveryService):
+ self.service = service
+
+ @tool(
+ name="view_menu",
+ description="View the menu and list available food items and prices",
+ input_schema=ViewMenuInput
+ )
+ async def view_menu(self, input: ViewMenuInput, context: ExecutionContext) -> dict:
+ context.logger.info("Fetching food delivery menu...")
+ return {"menu": self.service.get_menu()}
+
+ @tool(
+ name="place_order",
+ description="Place a food delivery order for a menu item",
+ input_schema=PlaceOrderInput
+ )
+ async def place_order(self, input: PlaceOrderInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Placing order for {input.quantity}x {input.item}")
+ return self.service.place_order(input.item, input.quantity)
+
+ @tool(
+ name="track_order",
+ description="Track the status of an existing food delivery order",
+ input_schema=OrderStatusInput
+ )
+ async def track_order(self, input: OrderStatusInput, context: ExecutionContext) -> dict:
+ context.logger.info(f"Tracking order status for {input.order_id}")
+ return self.service.get_order_status(input.order_id)
diff --git a/nitrostack/cli/templates/legacy_main_template.txt b/nitrostack/cli/templates/legacy_main_template.txt
new file mode 100644
index 0000000..6de69ef
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_main_template.txt
@@ -0,0 +1,10 @@
+import asyncio
+from nitrostack import McpApplicationFactory
+from app_module import AppModule
+
+async def main():
+ app = await McpApplicationFactory.create(AppModule)
+ await app.start()
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/nitrostack/cli/templates/legacy_module_template.txt b/nitrostack/cli/templates/legacy_module_template.txt
new file mode 100644
index 0000000..c3fcb8f
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_module_template.txt
@@ -0,0 +1,11 @@
+from nitrostack import module
+
+@module(
+ name="{name}",
+ imports=[],
+ controllers=[],
+ providers=[],
+ exports=[]
+)
+class {camel_name}Module:
+ pass
diff --git a/nitrostack/cli/templates/legacy_oauth_setup_template.txt b/nitrostack/cli/templates/legacy_oauth_setup_template.txt
new file mode 100644
index 0000000..c704b1d
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_oauth_setup_template.txt
@@ -0,0 +1,59 @@
+# OAuth 2.1 Server Setup Guide
+
+To run your flight booking MCP server with OAuth 2.1 protection, you need to configure an OAuth authorization server (like Keycloak, Auth0, Hydra, or a local mock OAuth server).
+
+## 1. Local Configuration
+
+Add the following environment variables to your `.env` file to configure resource protection:
+
+```env
+# --- Enforcement gate -------------------------------------------------------
+# Unset / false (default): tokens are NOT enforced. Studio and Inspector can
+# call tools without authenticating, against mock data. Best for local dev.
+# true: Bearer tokens are enforced. If no verifier (JWKS_URI or an
+# introspection endpoint) is configured, the server still starts but rejects
+# every protected request -- fail closed, never fail open.
+OAUTH_REQUIRED=true
+
+# --- Server identity --------------------------------------------------------
+RESOURCE_URI=http://localhost:3000/mcp
+AUTH_SERVER_URL=https://your-tenant.us.auth0.com
+
+# --- Token verification: pick ONE of the two ---------------------------------
+# 1) JWKS -- verifies signatures locally, no network call per request.
+JWKS_URI=https://your-tenant.us.auth0.com/.well-known/jwks.json
+
+# 2) Or RFC 7662 introspection -- asks the authorization server per token.
+# Both spellings are accepted; OAUTH_INTROSPECTION_ENDPOINT wins if both set.
+# OAUTH_INTROSPECTION_ENDPOINT=http://localhost:3000/oauth/introspect
+# INTROSPECTION_ENDPOINT=http://localhost:3000/oauth/introspect
+# INTROSPECTION_CLIENT_ID=your-introspection-client-id
+# INTROSPECTION_CLIENT_SECRET=your-introspection-client-secret
+
+# --- Token claim validation --------------------------------------------------
+# Audience must match, or the token is rejected (RFC 8707). Defaults to RESOURCE_URI.
+TOKEN_AUDIENCE=http://localhost:3000/mcp
+TOKEN_ISSUER=https://your-tenant.us.auth0.com/
+
+# --- Dynamic Client Registration (RFC 7591, optional, off by default) --------
+# Serves only the statically configured client below. Requires BOTH the flag
+# and OAUTH_CLIENT_ID -- without a client id it stays disabled.
+# OAUTH_ENABLE_CLIENT_REGISTRATION=true
+# OAUTH_CLIENT_ID=your-client-id
+# OAUTH_CLIENT_SECRET=your-client-secret
+
+# --- Tuning ------------------------------------------------------------------
+# Seconds to cache a successful introspection result (default 300; 0 disables).
+# OAUTH_TOKEN_CACHE_SECONDS=300
+# Port for the .well-known discovery server (default 3005).
+# OAUTH_DISCOVERY_PORT=3005
+```
+
+## 2. Protected Routes
+
+The tools in this server use the `@use_guards(OAuthGuard, create_scope_guard([...]))` decorators to automatically protect endpoints:
+* **Public**: No guards (or custom public filters).
+* **Read-Protected**: Requires valid access token with `read` scope.
+* **Write-Protected**: Requires valid access token with `write` scope.
+
+When calling protected tools, the client must pass a valid Bearer token in the `Authorization` header.
diff --git a/nitrostack/cli/templates/legacy_requirements_template.txt b/nitrostack/cli/templates/legacy_requirements_template.txt
new file mode 100644
index 0000000..9e875ce
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_requirements_template.txt
@@ -0,0 +1 @@
+nitrostack
diff --git a/nitrostack/cli/templates/legacy_sample_pizza_preview_json.txt b/nitrostack/cli/templates/legacy_sample_pizza_preview_json.txt
new file mode 100644
index 0000000..60d81b4
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_sample_pizza_preview_json.txt
@@ -0,0 +1,14 @@
+{
+ "shops": [
+ {
+ "id": "tonys-pizza",
+ "name": "Tony's New York Pizza",
+ "address": "123 Main St, San Francisco, CA 94102",
+ "rating": 4.5,
+ "priceLevel": 2,
+ "openNow": true,
+ "image": "https://images.unsplash.com/photo-1513104890138-7c749659a591"
+ }
+ ],
+ "totalShops": 1
+}
\ No newline at end of file
diff --git a/nitrostack/cli/templates/legacy_tool_template.txt b/nitrostack/cli/templates/legacy_tool_template.txt
new file mode 100644
index 0000000..84759fa
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_tool_template.txt
@@ -0,0 +1,16 @@
+from nitrostack import tool, widget, ExecutionContext
+from pydantic import BaseModel
+
+class {camel_name}Input(BaseModel):
+ # Add input parameters here
+ pass
+
+@tool(
+ name="{name}",
+ description="Implement your tool description here",
+ input_schema={camel_name}Input
+)
+@widget("{name}")
+async def {name}_handler(input: {camel_name}Input, context: ExecutionContext):
+ context.logger.info("Executing tool {name}")
+ return {{"status": "success"}}
diff --git a/nitrostack/cli/templates/legacy_widget_preview_html.txt b/nitrostack/cli/templates/legacy_widget_preview_html.txt
new file mode 100644
index 0000000..83222c7
--- /dev/null
+++ b/nitrostack/cli/templates/legacy_widget_preview_html.txt
@@ -0,0 +1,52 @@
+
+
+
+
+ Widget preview
+
+
+
+
+ This static file does not follow MCP Inspector tool calls.
+ Inspector JSON is the live result (e.g. all matching pizza shops). Open
+ http://localhost:3000/widgets/preview with the server running to
+ render that same output, or paste structuredContent below and Inject.
+
+
+
+
+
+
+
+
diff --git a/nitrostack/cli/upgrade.py b/nitrostack/cli/upgrade.py
index 64e600a..121e0a6 100644
--- a/nitrostack/cli/upgrade.py
+++ b/nitrostack/cli/upgrade.py
@@ -123,6 +123,16 @@ def fetch_nitrostack_wheel(version: str, timeout: float = 60.0) -> bytes:
return data
+def _is_source_reference(text: str, match: re.Match) -> bool:
+ """Keep uv source-table keys and local source paths out of version upgrades."""
+ tables = re.findall(r"(?m)^\s*\[([^\]\n]+)\]", text[:match.start()])
+ if tables and (tables[-1] == "tool.uv.sources" or tables[-1].startswith("tool.uv.sources.")):
+ return True
+ return bool(re.match(r"\s*=(?!=)", text[match.end():])) or (
+ match.start() > 0 and text[match.start() - 1] in "/\\"
+ )
+
+
def _pyproject_dependencies(text: str) -> Tuple[int, int]:
"""Span of `[project].dependencies`, or (0, 0). Specs elsewhere (e.g. a
`[tool.uv.sources]` entry named nitrostack) must not be rewritten."""
@@ -141,19 +151,25 @@ def _replace_pyproject_spec(text: str, spec: str) -> Tuple[str, int]:
def find_current_spec(text: str) -> Optional[str]:
- match = _DEP_RE.search(text)
- if not match:
- return None
- spec = (match.group(2) + (match.group(3) or "")).strip()
- return spec
+ for match in _DEP_RE.finditer(text):
+ # A [tool.uv.sources] key is not a dependency requirement.
+ if not _is_source_reference(text, match):
+ return (match.group(2) + (match.group(3) or "")).strip()
+ return None
def replace_nitrostack_spec(text: str, spec: str) -> Tuple[str, int]:
+ count = 0
def _sub(match: re.Match) -> str:
+ nonlocal count
+ if _is_source_reference(text, match):
+ return match.group(0)
+ count += 1
quote = match.group(1) or ""
return f"{quote}{spec}{quote}"
- return _DEP_RE.subn(_sub, text)
+ updated = _DEP_RE.sub(_sub, text)
+ return updated, count
def _add_to_pyproject_dependencies(text: str, spec: str) -> str:
diff --git a/nitrostack/cli/validators.py b/nitrostack/cli/validators.py
index 3015aa4..7c41867 100644
--- a/nitrostack/cli/validators.py
+++ b/nitrostack/cli/validators.py
@@ -11,6 +11,7 @@
from dataclasses import dataclass
from typing import Any, Iterable, List, Optional, Sequence, Set, Tuple
+from nitrostack.cli.widget_routes import collect_widget_routes
from packaging.specifiers import InvalidSpecifier, SpecifierSet
from packaging.version import InvalidVersion, Version
@@ -377,6 +378,60 @@ def validate_module_references(root: str) -> List[ValidationIssue]:
return issues
+_WIDGET_ROUTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
+
+
+def _collect_widget_routes(root: str) -> List[Tuple[str, str]]:
+ root_abs = os.path.abspath(root)
+ sources: List[Tuple[str, str]] = []
+
+ for path in sorted(_iter_python_files(root)):
+ rel_path = os.path.relpath(path, root_abs)
+ parts = os.path.normpath(rel_path).split(os.sep)
+
+ # Ignore a vendored copy of the NitroStack SDK.
+ if "vendor" in parts and "nitrostack" in parts:
+ continue
+
+ try:
+ sources.append((rel_path, _read(path)))
+ except OSError:
+ continue
+
+ return collect_widget_routes(sources)
+
+
+
+def validate_widgets(root: str) -> List[ValidationIssue]:
+ issues: List[ValidationIssue] = []
+ for route, source in _collect_widget_routes(root):
+ if not _WIDGET_ROUTE_RE.fullmatch(route):
+ issues.append(ValidationIssue(
+ "warning",
+ f"@widget route {route!r} is not a single alphanumeric path segment",
+ "Use letters, digits, '-' or '_' only; the route maps to widgets/out/.html.",
+ source,
+ ))
+ continue
+ rel = os.path.join("widgets", "out", f"{route}.html")
+ uri = f"ui://widget/{route}.html"
+ html_path = os.path.join(root, rel)
+ if not os.path.isfile(html_path):
+ issues.append(ValidationIssue(
+ "warning",
+ f"widget route {route!r} -> {rel} -> {uri}: file is missing",
+ f"Create {rel} with the widget HTML.",
+ source,
+ ))
+ elif not _read(html_path).strip():
+ issues.append(ValidationIssue(
+ "warning",
+ f"widget route {route!r} -> {rel} -> {uri}: file is empty",
+ f"Add widget HTML to {rel}.",
+ rel,
+ ))
+ return issues
+
def validate_project(root: Optional[str] = None) -> List[ValidationIssue]:
root = os.path.abspath(root or os.getcwd())
if root not in sys.path:
@@ -385,6 +440,7 @@ def validate_project(root: Optional[str] = None) -> List[ValidationIssue]:
issues.extend(validate_dependencies(root))
issues.extend(validate_mcp_app_imports(root))
issues.extend(validate_module_references(root))
+ issues.extend(validate_widgets(root))
return issues
diff --git a/nitrostack/cli/vendor.py b/nitrostack/cli/vendor.py
index 08abbea..21dfbbc 100644
--- a/nitrostack/cli/vendor.py
+++ b/nitrostack/cli/vendor.py
@@ -19,10 +19,16 @@
from pathlib import Path
from typing import List, Optional
-from nitrostack.cli._shared import loads_toml, write_text_atomic
+from nitrostack.cli._shared import loads_toml, requirement_name, write_text_atomic
VENDOR_REL = os.path.join("vendor", "nitrostack")
-_PLAIN_REQUIREMENT = "nitrostack"
+
+
+def runtime_nitrostack_requirement() -> str:
+ """PEP 508 requirement pinning at least the SDK version running this CLI."""
+ return f"nitrostack>={_distribution_version()}"
+
+
_PATH_PINS = frozenset({"./vendor/nitrostack", "-e ./vendor/nitrostack"})
_NAMED_REQUIREMENT = re.compile(
r"^(?:-e\s+|--editable\s+)?nitrostack"
@@ -125,7 +131,7 @@ def _write_minimal_pyproject(
f"{deps}"
"]\n\n"
"[project.scripts]\n"
- 'nitrostack-py = "nitrostack.cli.main:main"\n\n'
+ 'nitrostack-py = "nitrostack.cli.entry:main"\n\n'
"[tool.setuptools.packages.find]\n"
'include = ["nitrostack*"]\n\n'
"[tool.setuptools]\n"
@@ -257,8 +263,9 @@ def replace_vendored_nitrostack(project: str, wheel: Optional[bytes] = None) ->
def _pin_text(text: str) -> str:
- """Keep `[project].dependencies` as a plain name (valid wheel Requires-Dist)."""
- return _QUOTED_NITROSTACK.sub(lambda match: f"{match.group(1)}nitrostack{match.group(1)}", text)
+ """Keep `[project].dependencies` on `nitrostack` with a minimum SDK version."""
+ spec = runtime_nitrostack_requirement()
+ return _QUOTED_NITROSTACK.sub(lambda match: f"{match.group(1)}{spec}{match.group(1)}", text)
def _pin_requirements(path: Path) -> None:
@@ -270,7 +277,7 @@ def _pin_requirements(path: Path) -> None:
for line in lines:
stripped = line.strip()
if stripped in _PATH_PINS or _NAMED_REQUIREMENT.match(stripped):
- out.append(f"{_PLAIN_REQUIREMENT}\n")
+ out.append(f"{runtime_nitrostack_requirement()}\n")
else:
out.append(line)
path.write_text("".join(out), encoding="utf-8")
@@ -296,6 +303,12 @@ def _ensure_uv_source(text: str) -> str:
return text + '\n[tool.uv.sources]\nnitrostack = { path = "vendor/nitrostack" }\n'
+def apply_runtime_nitrostack_pins(deps: List[str]) -> List[str]:
+ """Ensure each ``nitrostack`` entry carries at least the running SDK version."""
+ spec = runtime_nitrostack_requirement()
+ return [spec if requirement_name(dep) == "nitrostack" else dep for dep in deps]
+
+
def pin_project_to_vendor(project: Path) -> None:
pyproject = project / "pyproject.toml"
if pyproject.is_file():
diff --git a/nitrostack/cli/widget_routes.py b/nitrostack/cli/widget_routes.py
new file mode 100644
index 0000000..c878e4f
--- /dev/null
+++ b/nitrostack/cli/widget_routes.py
@@ -0,0 +1,294 @@
+"""Static discovery of ``@widget`` routes for ``nitrostack-py validate``.
+
+Nothing is imported or run. Each project file is parsed and routes are found in three
+ways: a string literal (``@widget("card")``), a ``WidgetOptions`` call with a literal
+route, and a call to a *factory*, meaning a function whose parameter reaches
+``WidgetOptions(route=...)`` (``@widget(my_widget("pizza-map"))``).
+
+``widget`` and ``WidgetOptions`` only count when they resolve to the SDK's own, directly,
+through ``import nitrostack``, or through a project module that re-exports them, so
+``@pytest.mark.widget("smoke")`` is ignored.
+
+A factory call only counts when the name resolves, through the calling module's own
+definitions and imports, to a real factory, and the string sits in the argument that
+feeds ``route``. So ``panel("x")`` is ignored when ``panel`` never passes that argument
+to ``route``, or when it is an unrelated ``panel`` from another module.
+"""
+
+from __future__ import annotations
+
+import ast
+import os
+import re
+from dataclasses import dataclass, field
+from typing import Dict, Iterable, List, Optional, Tuple
+
+# Only used for a file that does not parse, so a broken file still gets its literal routes.
+_LEGACY_DECORATOR_RE = re.compile(r"""@widget\(\s*["']([^"']+)["']""")
+_LEGACY_OPTIONS_RE = re.compile(r"""WidgetOptions\(\s*route\s*=\s*["']([^"']+)["']""")
+
+_WIDGET_OPTIONS = object() # the SDK's WidgetOptions class
+_WIDGET = object() # the SDK's @widget decorator
+_NITROSTACK = object() # the nitrostack package or one of its submodules
+_PLAIN = object() # a project function or class that is not a factory
+
+
+@dataclass(frozen=True)
+class _Factory:
+ param: str # the parameter that feeds WidgetOptions.route
+ index: int # its position among the positional parameters, -1 if keyword-only
+
+
+@dataclass
+class _Namespace:
+ """A project module or a class, with the names it defines."""
+
+ name: str
+ defs: Dict[str, object] = field(default_factory=dict)
+
+
+@dataclass
+class _Module:
+ name: str
+ package: Tuple[str, ...]
+ tree: Optional[ast.Module]
+ text: str
+ ns: _Namespace
+ imports: Dict[str, Tuple[str, str]] = field(default_factory=dict) # local -> (module, attr)
+ funcs: List[Tuple[ast.AST, str, _Namespace]] = field(default_factory=list) # node, kind, owner
+
+
+def _dotted(rel_path: str) -> Tuple[str, Tuple[str, ...]]:
+ parts = os.path.normpath(rel_path).split(os.sep)
+ parts[-1] = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1]
+ is_package = parts[-1] == "__init__"
+ if is_package:
+ parts = parts[:-1]
+ return ".".join(parts), tuple(parts if is_package else parts[:-1])
+
+
+def _is_nitrostack(module: str) -> bool:
+ return module == "nitrostack" or module.startswith("nitrostack.")
+
+
+class _Project:
+ def __init__(self, sources: Iterable[Tuple[str, str]]):
+ self.modules: Dict[str, _Module] = {}
+ self.order: List[Tuple[str, _Module]] = []
+ for rel_path, text in sources:
+ name, package = _dotted(rel_path)
+ try:
+ tree: Optional[ast.Module] = ast.parse(text)
+ except (SyntaxError, ValueError):
+ tree = None
+ module = _Module(name, package, tree, text, _Namespace(name))
+ self.order.append((rel_path, module))
+ self.modules[name] = module
+ if tree is not None:
+ self._index(module)
+ self._find_factories()
+
+ # -- indexing ---------------------------------------------------------------
+
+ def _index(self, module: _Module) -> None:
+ assert module.tree is not None
+ for node in ast.walk(module.tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.asname:
+ module.imports[alias.asname] = (alias.name, "")
+ else:
+ top = alias.name.split(".")[0]
+ module.imports[top] = (top, "")
+ elif isinstance(node, ast.ImportFrom):
+ source = self._absolute(module, node)
+ if source is None:
+ continue
+ for alias in node.names:
+ if alias.name != "*":
+ module.imports[alias.asname or alias.name] = (source, alias.name)
+ for node in module.tree.body:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ module.ns.defs[node.name] = _PLAIN
+ module.funcs.append((node, "func", module.ns))
+ elif isinstance(node, ast.ClassDef):
+ cls = _Namespace(f"{module.name}.{node.name}")
+ module.ns.defs[node.name] = cls
+ for item in node.body:
+ kind = self._method_kind(item)
+ if kind:
+ cls.defs[item.name] = _PLAIN
+ module.funcs.append((item, kind, cls))
+
+ @staticmethod
+ def _method_kind(item: ast.AST) -> Optional[str]:
+ if not isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ return None
+ names = {d.id for d in item.decorator_list if isinstance(d, ast.Name)}
+ if "staticmethod" in names:
+ return "static"
+ return "class" if "classmethod" in names else None # instance methods need an object
+
+ @staticmethod
+ def _absolute(module: _Module, node: ast.ImportFrom) -> Optional[str]:
+ if not node.level:
+ return node.module
+ keep = len(module.package) - (node.level - 1)
+ if keep < 0:
+ return None
+ base = list(module.package[:keep]) + ([node.module] if node.module else [])
+ return ".".join(base)
+
+ # -- name resolution --------------------------------------------------------
+
+ def _find(self, dotted: str) -> Optional[_Module]:
+ if dotted in self.modules:
+ return self.modules[dotted]
+ matches = [m for key, m in self.modules.items() if key.endswith("." + dotted)]
+ return matches[0] if len(matches) == 1 else None # e.g. a src/ layout
+
+ @staticmethod
+ def _sdk(attr: str) -> object:
+ if attr == "WidgetOptions":
+ return _WIDGET_OPTIONS
+ return _WIDGET if attr == "widget" else _NITROSTACK
+
+ def _binding(self, module: _Module, name: str, seen: set) -> object:
+ """What ``name`` means inside ``module``, following re-exports through project modules."""
+ if (module.name, name) in seen: # an import cycle
+ return None
+ seen.add((module.name, name))
+ if name in module.ns.defs:
+ return module.ns.defs[name]
+ imported = module.imports.get(name)
+ if not imported:
+ return None
+ source, attr = imported
+ if _is_nitrostack(source):
+ return self._sdk(attr)
+ found = self._find(source)
+ if not attr:
+ return found.ns if found else None
+ if found:
+ bound = self._binding(found, attr, seen)
+ if bound is not None:
+ return bound
+ sub = self._find(f"{source}.{attr}") # ``from pkg import module``
+ return sub.ns if sub else None
+
+ def _name(self, module: _Module, name: str) -> object:
+ bound = self._binding(module, name, set())
+ if bound is None and name not in module.ns.defs and name not in module.imports:
+ return self._sdk(name) if name in ("WidgetOptions", "widget") else None
+ return bound
+
+ def resolve(self, expr: ast.AST, module: _Module) -> object:
+ if isinstance(expr, ast.Name):
+ return self._name(module, expr.id)
+ if isinstance(expr, ast.Attribute):
+ base = self.resolve(expr.value, module)
+ if base is _NITROSTACK:
+ return self._sdk(expr.attr)
+ if isinstance(base, _Namespace):
+ if expr.attr in base.defs:
+ return base.defs[expr.attr]
+ sub = self._find(f"{base.name}.{expr.attr}")
+ return sub.ns if sub else None
+ return None
+
+ @staticmethod
+ def route_arg(call: ast.Call, target: object) -> Optional[ast.AST]:
+ """The expression passed where ``target`` expects the route, if it is passed at all."""
+ if target is _WIDGET_OPTIONS:
+ name, index = "route", 0
+ elif isinstance(target, _Factory):
+ name, index = target.param, target.index
+ else:
+ return None
+ if 0 <= index < len(call.args):
+ if any(isinstance(arg, ast.Starred) for arg in call.args[: index + 1]):
+ return None
+ return call.args[index]
+ for keyword in call.keywords:
+ if keyword.arg == name:
+ return keyword.value
+ return None
+
+ # -- factories --------------------------------------------------------------
+
+ def _factory_of(self, module: _Module, fn: ast.AST, kind: str) -> Optional[_Factory]:
+ positional = [a.arg for a in fn.args.posonlyargs + fn.args.args] # type: ignore[attr-defined]
+ if kind == "class":
+ positional = positional[1:]
+ params = positional + [a.arg for a in fn.args.kwonlyargs] # type: ignore[attr-defined]
+ reassigned = {
+ n.id for n in ast.walk(fn) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)
+ }
+ for call in (n for n in ast.walk(fn) if isinstance(n, ast.Call)):
+ expr = self.route_arg(call, self.resolve(call.func, module))
+ if isinstance(expr, ast.Name) and expr.id in params and expr.id not in reassigned:
+ return _Factory(expr.id, positional.index(expr.id) if expr.id in positional else -1)
+ return None
+
+ def _find_factories(self) -> None:
+ # Repeat so a function that forwards its parameter to another factory is found too.
+ for _ in range(sum(len(m.funcs) for _, m in self.order) + 1):
+ changed = False
+ for _, module in self.order:
+ for fn, kind, owner in module.funcs:
+ if owner.defs.get(fn.name) is not _PLAIN: # type: ignore[attr-defined]
+ continue
+ factory = self._factory_of(module, fn, kind)
+ if factory:
+ owner.defs[fn.name] = factory # type: ignore[attr-defined]
+ changed = True
+ if not changed:
+ break
+
+ # -- routes -----------------------------------------------------------------
+
+ def _literal(self, expr: Optional[ast.AST]) -> Optional[str]:
+ if isinstance(expr, ast.Constant) and isinstance(expr.value, str):
+ return expr.value
+ return None
+
+ def routes_in(self, module: _Module) -> List[str]:
+ if module.tree is None:
+ return _LEGACY_DECORATOR_RE.findall(module.text) + _LEGACY_OPTIONS_RE.findall(module.text)
+ found: List[Tuple[int, int, str]] = []
+ for node in ast.walk(module.tree):
+ for decorator in getattr(node, "decorator_list", []):
+ is_widget = (
+ isinstance(decorator, ast.Call)
+ and self.resolve(decorator.func, module) is _WIDGET
+ )
+ if isinstance(decorator, ast.Call) and is_widget and decorator.args:
+ route = self._decorator_route(decorator.args[0], module)
+ if route:
+ found.append((decorator.lineno, decorator.col_offset, route))
+ if isinstance(node, ast.Call) and self.resolve(node.func, module) is _WIDGET_OPTIONS:
+ route = self._literal(self.route_arg(node, _WIDGET_OPTIONS))
+ if route:
+ found.append((node.lineno, node.col_offset, route))
+ return [route for _, _, route in sorted(found)]
+
+ def _decorator_route(self, expr: ast.AST, module: _Module) -> Optional[str]:
+ literal = self._literal(expr)
+ if literal is not None:
+ return literal
+ if isinstance(expr, ast.Call):
+ return self._literal(self.route_arg(expr, self.resolve(expr.func, module)))
+ return None
+
+
+def collect_widget_routes(sources: Iterable[Tuple[str, str]]) -> List[Tuple[str, str]]:
+ """``(route, rel_path)`` for every route found in ``(rel_path, source_text)`` pairs."""
+ project = _Project(sources)
+ found: List[Tuple[str, str]] = []
+ seen = set()
+ for rel_path, module in project.order:
+ for route in project.routes_in(module):
+ if route not in seen:
+ seen.add(route)
+ found.append((route, rel_path))
+ return found
diff --git a/nitrostack/core/additional_decorators.py b/nitrostack/core/additional_decorators.py
index aa30a47..ae3ee4f 100644
--- a/nitrostack/core/additional_decorators.py
+++ b/nitrostack/core/additional_decorators.py
@@ -1,7 +1,14 @@
+import json
import time
+import inspect
+import asyncio
+import threading
+from collections import OrderedDict, deque
+from concurrent.futures import ThreadPoolExecutor
from functools import wraps
-from typing import Callable, Any, Dict, List, Tuple
+from typing import Any, Callable, Deque, Dict, List, Literal, Optional, Tuple, TypedDict
from nitrostack.core.context import ExecutionContext
+from nitrostack.core.errors import RateLimitExceededError
def copy_mcp_attributes(src: Any, dst: Any) -> None:
"""Helper to copy all _mcp_ attributes from src function to dst function."""
@@ -9,21 +16,78 @@ def copy_mcp_attributes(src: Any, dst: Any) -> None:
if attr.startswith("_mcp_"):
setattr(dst, attr, getattr(src, attr))
-def cache(ttl: int = 60):
+
+def _make_cache_key_part(value: Any, label: str) -> Any:
+ """Convert *value* into a hashable cache-key component.
+
+ Pydantic BaseModel instances are keyed from all declared fields (including
+ those marked exclude=True) via pydantic_core.to_jsonable_python, identified
+ by their fully-qualified class name (module + qualname) to prevent collisions
+ between identically-named models from different modules.
+ Natively hashable values are used as-is.
+ Anything else raises a descriptive TypeError.
+ """
+ try:
+ import pydantic_core
+ from pydantic import BaseModel as PydanticBaseModel # type: ignore
+ if isinstance(value, PydanticBaseModel):
+ cls = type(value)
+ # Use all declared fields (bypasses exclude=True) so that excluded
+ all_fields = {name: getattr(value, name) for name in cls.model_fields}
+ serialized = json.dumps(
+ pydantic_core.to_jsonable_python(all_fields), sort_keys=True
+ )
+ # Use module + qualname so two classes named "Query" in different
+ # modules never share a cache entry.
+ type_id = f"{cls.__module__}.{cls.__qualname__}"
+ return ("__pydantic__", type_id, serialized)
+ except ImportError:
+ pass
+
+ try:
+ hash(value)
+ return value
+ except TypeError:
+ pass
+
+ raise TypeError(
+ f"cache: argument {label!r} of type {type(value).__name__!r} is not hashable "
+ f"and has no built-in serialization strategy. "
+ f"Pass a key= callable to cache() to handle this type explicitly."
+ )
+
+
+def cache(ttl: int = 60, max_size: Optional[int] = 1024, key: Optional[Callable[..., Any]] = None):
"""
Caches method outputs for a specific TTL (in seconds).
Skips ExecutionContext parameters when generating the cache key.
+ Holds at most max_size entries, evicting expired entries first and then
+ the least recently used. max_size=None disables the cap.
+ The wrapped function exposes cache_clear() to empty the cache.
+
+ Args:
+ ttl: Time-to-live for cached entries in seconds (must be > 0).
+ max_size: Maximum number of cache entries. None means unlimited.
+ key: Optional callable that receives the same *args* and **kwargs
+ as the decorated function (after ExecutionContext arguments
+ are filtered out) and returns a hashable cache key.
+ When provided it overrides the default key-building logic,
+ which serializes Pydantic models automatically and raises a
+ descriptive TypeError for other unhashable arguments.
"""
+ if ttl <= 0:
+ raise ValueError(f"cache ttl must be > 0, got {ttl!r}.")
+ if max_size is not None and (not isinstance(max_size, int) or isinstance(max_size, bool) or max_size < 1):
+ raise ValueError(f"cache max_size must be a positive integer or None, got {max_size!r}.")
+
def decorator(func: Callable):
- cache_store: Dict[Tuple[Any, ...], Tuple[Any, float]] = {}
+ cache_store: "OrderedDict[Tuple[Any, ...], Tuple[Any, float]]" = OrderedDict()
setattr(func, "_mcp_cache_ttl", ttl)
@wraps(func)
async def wrapper(*args, **kwargs):
- # Construct a cache key by filtering out ExecutionContext and self
filtered_args = []
for arg in args:
- # Skip self if it has class attributes or is the instance, skip ExecutionContext
if isinstance(arg, ExecutionContext) or type(arg).__name__ == "ExecutionContext":
continue
filtered_args.append(arg)
@@ -34,41 +98,94 @@ async def wrapper(*args, **kwargs):
continue
filtered_kwargs[k] = v
- # Standardize key (args and kwargs)
- key = (tuple(filtered_args), frozenset(filtered_kwargs.items()))
+ if key is not None:
+ raw_key = key(*filtered_args, **filtered_kwargs)
+ try:
+ hash(raw_key)
+ except TypeError:
+ raise TypeError(
+ f"cache: the key= callable returned a value of type "
+ f"{type(raw_key).__name__!r} which is not hashable. "
+ f"Ensure key= returns a hashable object (e.g. a string, int, or tuple)."
+ )
+ cache_key = raw_key
+ else:
+ key_args = tuple(
+ _make_cache_key_part(v, f"args[{i}]") for i, v in enumerate(filtered_args)
+ )
+ key_kwargs = frozenset(
+ (k, _make_cache_key_part(v, k)) for k, v in filtered_kwargs.items()
+ )
+ cache_key = (key_args, key_kwargs)
now = time.time()
- if key in cache_store:
- val, expiry = cache_store[key]
+ entry = cache_store.get(cache_key)
+ if entry is not None:
+ val, expiry = entry
if now < expiry:
+ cache_store.move_to_end(cache_key)
return val
+ del cache_store[cache_key]
result = await func(*args, **kwargs)
- cache_store[key] = (result, now + ttl)
+ cache_store[cache_key] = (result, now + ttl)
+ cache_store.move_to_end(cache_key)
+
+ if max_size is not None and len(cache_store) > max_size:
+ for stale in [k for k, (_, exp) in cache_store.items() if exp <= now]:
+ del cache_store[stale]
+ while len(cache_store) > max_size:
+ cache_store.popitem(last=False)
return result
copy_mcp_attributes(func, wrapper)
setattr(wrapper, "_mcp_cache_ttl", ttl)
+ wrapper.cache_clear = cache_store.clear
return wrapper
return decorator
-def rate_limit(max: int, window: int):
+def rate_limit(max: int, window: int, key: Optional[Callable[..., Any]] = None):
"""
Rate limits method calls to max calls per window (in seconds).
+ By default one counter is shared by all callers of the decorated function.
+ Pass key=callable(*args, **kwargs) -> hashable to keep a separate counter
+ per key, for example per user. Raises RateLimitExceededError (a ValueError)
+ carrying retry_after_seconds. Counters are held in memory per process.
"""
+ if not isinstance(max, int) or isinstance(max, bool) or max < 1:
+ raise ValueError(f"rate_limit max must be an integer >= 1, got {max!r}.")
+ if window <= 0:
+ raise ValueError(f"rate_limit window must be > 0, got {window!r}.")
+
+
def decorator(func: Callable):
- calls: List[float] = []
+ buckets: Dict[Any, Deque[float]] = {}
+ last_sweep = time.time()
@wraps(func)
async def wrapper(*args, **kwargs):
- nonlocal calls
+ nonlocal last_sweep
now = time.time()
- # Filter timestamps in the window
- calls = [t for t in calls if now - t < window]
- if len(calls) >= max:
- raise ValueError(f"Rate limit exceeded. Maximum of {max} calls allowed every {window} seconds.")
-
- calls.append(now)
+
+ if now - last_sweep >= window:
+ for k in [k for k, b in buckets.items() if not b or now - b[-1] >= window]:
+ del buckets[k]
+ last_sweep = now
+
+ bucket_key = key(*args, **kwargs) if key is not None else None
+ bucket = buckets.setdefault(bucket_key, deque())
+ while bucket and now - bucket[0] >= window:
+ bucket.popleft()
+
+ if len(bucket) >= max:
+ retry_after = window - (now - bucket[0])
+ raise RateLimitExceededError(
+ f"Rate limit exceeded. Maximum of {max} calls allowed every {window} seconds. "
+ f"Retry after {retry_after:.1f} seconds.",
+ retry_after_seconds=retry_after,
+ )
+
+ bucket.append(now)
return await func(*args, **kwargs)
copy_mcp_attributes(func, wrapper)
@@ -76,60 +193,136 @@ async def wrapper(*args, **kwargs):
return decorator
+class TransformTelemetry(TypedDict):
+ name: str
+ type: str
+ order: int
+ details: Dict[str, Any]
+
+
+class HealthCheckResult(TypedDict):
+ name: str
+ status: Literal["healthy", "unhealthy", "error", "timeout"]
+ latencyMs: float
+ message: Optional[str]
+
+
+class ServerHealthPayload(TypedDict, total=False):
+ status: Literal["healthy", "degraded", "unhealthy"]
+ uptimeSeconds: int
+ checks: List[HealthCheckResult]
+ count: int
+ transforms: List[TransformTelemetry]
+ timestamp: str
+ sdkVersion: str
+
+
class HealthCheckRegistry:
# Maps name -> (unbound_func, class_type)
_checks: Dict[str, Tuple[Callable, Any]] = {}
# Maps name -> bound_callable
- _bound_checks: Dict[str, Callable[[], bool]] = {}
+ _bound_checks: Dict[str, Tuple[Callable[[], bool], float]] = {}
+ DEFAULT_TIMEOUT_SECONDS = 5.0
+ SYNC_EXECUTOR_WORKERS = 4
+ _sync_executor = ThreadPoolExecutor(
+ max_workers=SYNC_EXECUTOR_WORKERS,
+ thread_name_prefix="nitrostack-health",
+ )
+ # Bound submitted work as well as running threads. Timed-out functions retain
+ # their slot until they actually return, preventing an unbounded work queue.
+ _sync_slots = threading.BoundedSemaphore(SYNC_EXECUTOR_WORKERS)
@classmethod
def register(cls, name: str, func: Callable, class_type: Any = None) -> None:
cls._checks[name] = (func, class_type)
@classmethod
- def bind_instance(cls, name: str, func: Callable, instance: Any) -> None:
+ def bind_instance(cls, name: str, func: Callable, instance: Any, timeout: float = 5.0) -> None:
# Bind the method to the resolved instance
import inspect
if inspect.ismethod(func):
- cls._bound_checks[name] = func
+ cls._bound_checks[name] = (func, timeout)
else:
- cls._bound_checks[name] = lambda: func(instance)
+ cls._bound_checks[name] = (lambda: func(instance), timeout)
@classmethod
def get_checks(cls) -> Dict[str, Callable[[], bool]]:
- return cls._bound_checks
+ return {
+ name: value[0] if isinstance(value, tuple) else value
+ for name, value in cls._bound_checks.items()
+ }
@classmethod
- def run_all(cls) -> Dict[str, str]:
- results = {}
- for name, check_fn in cls._bound_checks.items():
+ async def run_all(cls) -> Dict[str, str]:
+ """Run every registered health check and return {name: status}.
+
+ Coroutine checks are awaited, sync checks are called directly, and a
+ check that raises reports its own error without affecting the others.
+ """
+ detailed = await cls.run_detailed()
+ return {
+ result["name"]: (
+ f'error: {result["message"]}' if result["status"] == "error"
+ else "unhealthy" if result["status"] == "timeout"
+ else result["status"]
+ )
+ for result in detailed
+ }
+
+ @classmethod
+ async def run_detailed(cls) -> List[HealthCheckResult]:
+ """Run all checks concurrently, bounding each by its own timeout."""
+ async def run_one(name: str, check: Callable, timeout: float) -> HealthCheckResult:
+ started = time.perf_counter()
try:
- # Handle both sync and async checks
- import inspect
- if inspect.iscoroutinefunction(check_fn):
- # In a real environment, we'd await it, but let's handle it or run via loop
- import asyncio
+ async def invoke():
+ if inspect.iscoroutinefunction(check):
+ return await check()
+ while not cls._sync_slots.acquire(blocking=False):
+ await asyncio.sleep(0.01)
try:
- loop = asyncio.get_event_loop()
- except RuntimeError:
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
- status = loop.run_until_complete(check_fn())
- else:
- status = check_fn()
- results[name] = "healthy" if status else "unhealthy"
- except Exception as e:
- results[name] = f"error: {str(e)}"
- return results
-
-def health_check(name: str):
+ future = cls._sync_executor.submit(check)
+ except BaseException:
+ cls._sync_slots.release()
+ raise
+ future.add_done_callback(lambda _future: cls._sync_slots.release())
+ result = await asyncio.wrap_future(future)
+ return await result if inspect.isawaitable(result) else result
+
+ outcome = await asyncio.wait_for(invoke(), timeout=timeout)
+ status = "healthy" if outcome else "unhealthy"
+ message = None if outcome else "Check returned false"
+ except asyncio.TimeoutError:
+ status, message = "timeout", f"Timed out after {timeout:g}s"
+ except Exception as exc: # noqa: BLE001 - one bad check must not hide the rest
+ status, message = "error", str(exc)
+ return {
+ "name": name,
+ "status": status,
+ "latencyMs": round((time.perf_counter() - started) * 1000, 3),
+ "message": message,
+ }
+
+ checks = [
+ (name, value if isinstance(value, tuple) else (value, cls.DEFAULT_TIMEOUT_SECONDS))
+ for name, value in cls._bound_checks.items()
+ ]
+ return list(await asyncio.gather(*(
+ run_one(name, check, timeout) for name, (check, timeout) in checks
+ )))
+
+def health_check(name: str, timeout: float = HealthCheckRegistry.DEFAULT_TIMEOUT_SECONDS):
"""
Decorator to mark a service or controller method as a health check.
"""
+ if timeout <= 0:
+ raise ValueError("health check timeout must be greater than zero")
+
def decorator(func: Callable):
func._mcp_health_check_name = name
# We don't have the class type here yet, but we will register it.
# It will be bound during discovery in the McpApplicationFactory.
HealthCheckRegistry.register(name, func)
+ func._mcp_health_check_timeout = timeout
return func
return decorator
diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py
index 9d9b069..e0a54fa 100644
--- a/nitrostack/core/app.py
+++ b/nitrostack/core/app.py
@@ -1,1951 +1,76 @@
-import os
-import sys
-import re
-import json
-import uuid
-import asyncio
-import inspect
-import datetime
-import logging
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Pattern, Set, Tuple, Type
-
-import mcp.types as types
-from mcp import MCPError
-from mcp.server.context import ServerRequestContext
-from mcp.server.lowlevel.helper_types import ReadResourceContents
-from mcp.types import (
- CallToolRequestParams,
- GetPromptRequestParams,
- PaginatedRequestParams,
- ReadResourceRequestParams,
- RequestParams,
- SubscribeRequestParams,
- UnsubscribeRequestParams,
-)
-from pydantic import BaseModel, create_model
-
-from nitrostack.core.context import ExecutionContext, TaskContext
-from nitrostack.core.decorators import ToolConfig, ResourceConfig, PromptConfig, widget_resource_uri
-from nitrostack.core.app_mode import get_app_mode, get_widget_mime_type, is_mcp_app_mode, is_openai_mode
-from nitrostack.core.di import DIContainer
-from nitrostack.core.errors import (
- DependencyResolutionError,
- PromptNotFoundError,
- ResourceNotFoundError,
- TaskAlreadyTerminalError,
- TaskExpiredError,
- TaskNotFoundError,
-)
-from nitrostack.core.mcp_server import NitroStackMcpServer
-from nitrostack.core.pipeline import run_pipeline
-from nitrostack.core.additional_decorators import HealthCheckRegistry
-from nitrostack.core.task import TaskManager, TaskStatus
-from nitrostack.events.event_emitter import EventEmitter
-from nitrostack.protocol.schema import (
- gate_registered_schema,
- normalize_input_schema,
- normalize_output_schema,
-)
-from nitrostack.protocol.resources import extract_template_param_names, uri_template_to_pattern
-from nitrostack.protocol.version import (
- MODERN_PROTOCOL_VERSION,
- EraSource,
- ProtocolEra,
- protocol_version_for_era,
- resolve_http_engine,
- resolve_protocol_era_resolution,
- wire_mode_for_era,
-)
-from nitrostack.protocol.mrtr import InputRequiredResult, split_mrtr_from_arguments
-from nitrostack.protocol.cache_hints import (
- build_list_endpoint_cache_hint_meta,
- resolve_resource_cache_hint_meta,
- resolve_tool_cache_hint_meta,
-)
-from nitrostack.auth.request import (
- auth_context_from_request,
- bearer_token_from_envelope_auth,
- envelope_auth_slot,
-)
-from nitrostack.protocol.meta import (
- bind_request_envelope,
- flatten_request_meta_object,
- strip_tool_arguments,
+"""Compatibility exports for the public application API.
+
+Implementation lives in focused app_* modules; those modules never import this facade.
+The delegated startup method preserves the ``return http_app`` contract.
+"""
+
+from nitrostack.core.app_config import (
+ DEFAULT_HTTP_PORT,
+ GetTaskResult,
+ ServerConfig,
+ _apply_project_identity,
+ _iso_timestamp,
+ _project_identity,
+ _read_dotenv_value,
+ mcp_app,
+ resolve_http_host,
+ resolve_http_port,
)
-from nitrostack.protocol.observability import TraceContext, extract_trace_context
-from nitrostack.runtime.correlation import InFlightRegistry, new_correlation_id
-from nitrostack.transports.headers import (
- extract_mcp_param_headers,
- extract_mcp_scope_headers,
- merge_mcp_param_headers,
+from nitrostack.core.app_context import (
+ _AUTH_META_KEYS,
+ _apply_request_envelope,
+ _auth_metadata_from_request_ctx,
+ _bind_correlation,
+ _http_headers_from_request_ctx,
+ _read_contents_to_result,
+ _request_meta_from_ctx,
+ _tool_arguments_with_mcp_params,
+ _trace_context_from_request_ctx,
)
-from nitrostack.protocol.deprecated import (
- deprecated_method_message,
- rejects_deprecated_method,
+from nitrostack.core.app_entries import _PromptEntry, _ResourceEntry, _ToolEntry
+from nitrostack.core.app_runtime import McpApplication, McpApplicationFactory
+from nitrostack.core.app_schema import (
+ _is_blank_inspector_value,
+ _is_null_schema,
+ _omit_blank_optional_fields,
+ _unwrap_nullable_schema,
+ get_pydantic_model,
+ inspector_friendly_schema,
+ parse_tool_input,
+ tool_json_schema,
)
-from nitrostack.protocol.tasks import (
- DEFAULT_TASK_TTL_MS,
- task_support_forbidden_message,
- task_support_required_message,
-)
-from nitrostack.runtime.request_ctx import ServerResult, request_ctx
-from nitrostack.tasks.authorization import extract_task_access_context
-from nitrostack.widgets.component import Component, find_project_root, load_widget_html, parse_widget_options
-from nitrostack.widgets.mcp_meta import build_call_tool_result_meta, build_tool_list_meta, resource_read_contents_meta
-from nitrostack.widgets.route_templates import build_missing_widget
-
-
-DEFAULT_HTTP_PORT = 3000
-logger = logging.getLogger(__name__)
-
-
-def _iso_timestamp(value: Any) -> str:
- """Official Task timestamps are ISO-8601 strings."""
- if hasattr(value, "isoformat"):
- text = value.isoformat()
- if text.endswith("+00:00"):
- return text[:-6] + "Z"
- return text
- return str(value)
-
-
-class GetTaskResult(types.GetTaskResult):
- """Official GetTaskResult plus NitroStack-owned ``result`` / ``error`` slots."""
-
- result: Any = None
- error: Any = None
-
-
-def resolve_http_port() -> int:
- """MCP HTTP/dual bind port. Defaults to 3000; 3001 is reserved for widgets."""
- return int(os.environ.get("PORT") or os.environ.get("MCP_SERVER_PORT") or DEFAULT_HTTP_PORT)
-
-
-def resolve_http_host() -> str:
- """Bind host. ``HOST`` matches the TypeScript templates; default is ``127.0.0.1``."""
- return (os.environ.get("HOST") or "127.0.0.1").strip() or "127.0.0.1"
-
-
-def _read_dotenv_value(root: str, key: str) -> Optional[str]:
- path = os.path.join(root, ".env")
- if not os.path.isfile(path):
- return None
- try:
- with open(path, encoding="utf-8") as handle:
- for raw in handle:
- line = raw.strip()
- if not line or line.startswith("#") or "=" not in line:
- continue
- name, value = line.split("=", 1)
- if name.strip() != key:
- continue
- return value.strip().strip('"').strip("'") or None
- except OSError:
- return None
- return None
-
-
-def _project_identity(root: Optional[str] = None) -> Dict[str, Optional[str]]:
- """Name / version / description for the `GET /` documentation page."""
- cwd = root or os.getcwd()
- name = os.environ.get("SERVER_NAME") or _read_dotenv_value(cwd, "SERVER_NAME")
- description = os.environ.get("SERVER_DESC") or _read_dotenv_value(cwd, "SERVER_DESC")
- version = None
- path = os.path.join(cwd, "pyproject.toml")
- if os.path.isfile(path):
- try:
- text = Path(path).read_text(encoding="utf-8")
- except OSError:
- text = ""
- if not name:
- match = re.search(r'(?m)^name\s*=\s*"([^"]+)"', text)
- name = match.group(1) if match else None
- if not description:
- match = re.search(r'(?m)^description\s*=\s*"([^"]+)"', text)
- description = match.group(1) if match else None
- match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', text)
- version = match.group(1) if match else None
- if not name:
- name = os.path.basename(os.path.abspath(cwd)) or None
- return {"name": name, "version": version, "description": description}
-
-
-def _apply_project_identity(config: "ServerConfig") -> None:
- ident = _project_identity()
- generic = (config.name or "").strip().lower() in {"", "app", "mcp-server"}
- if generic and ident.get("name"):
- config.name = ident["name"]
- if not config.description and ident.get("description"):
- config.description = ident["description"]
-
-
-@dataclass
-class ServerConfig:
- name: str
- version: str = "1.0.0"
- transport_type: Optional[Literal["stdio", "http", "dual"]] = None
- protocol_version: str = MODERN_PROTOCOL_VERSION
- # Era fallback when MCP_STATELESS and NITRO_MCP_PROTOCOL_VERSION are unset.
- # Same tokens as the env var (modern/latest/2026/2026-07-28, auto/both/dual/
- # dual-spec, legacy/2025/2025-06-18/2025-11-25). None means default era (`auto`).
- protocol_era: Optional[str] = None
- # Streamable HTTP options. Era resolution at `start()` / `get_combined_app()`:
- # `MCP_STATELESS`, then `NITRO_MCP_PROTOCOL_VERSION`, then `protocol_era`,
- # then `auto`. Also: `ENABLE_CORS`, `MCP_MAX_SESSIONS`,
- # `MCP_SESSION_TIMEOUT_MS`, `MCP_TRANSPORT_TYPE`.
- # `MCP_STATELESS` wins over the protocol-era mapping. Unset era is `auto`
- # and does not force this flag; only `modern` sets stateless HTTP.
- stateless: bool = False
- max_sessions: Optional[int] = None
- session_timeout_ms: Optional[int] = None
- json_response: bool = False
- extensions: Optional[Dict[str, str]] = None
- # Subtitle on the `GET /` documentation page.
- description: Optional[str] = None
-
-
-def mcp_app(module: Type, server: ServerConfig):
- """
- Decorator to declare the main application class.
- Specifies the root AppModule and ServerConfig.
- """
- def decorator(cls: Type):
- cls._mcp_app_module = module
- cls._mcp_app_server = server
- return cls
- return decorator
-
-
-def get_pydantic_model(schema: Any) -> Type[BaseModel]:
- """Helper to resolve or construct a Pydantic model for input validation."""
- if isinstance(schema, type) and issubclass(schema, BaseModel):
- return schema
- if isinstance(schema, dict):
- # Dynamically build a Pydantic model from JSON schema
- properties = schema.get("properties", {})
- required = schema.get("required", [])
- fields = {}
- for name, prop in properties.items():
- t = Any
- prop_type = prop.get("type")
- if prop_type == "string":
- t = str
- elif prop_type == "integer":
- t = int
- elif prop_type == "number":
- t = float
- elif prop_type == "boolean":
- t = bool
- elif prop_type == "array":
- t = list
- elif prop_type == "object":
- t = dict
-
- default = ... if name in required else None
- fields[name] = (t, default)
- return create_model("DynamicInputModel", **fields)
-
- # Return a default empty model if invalid or empty
- return create_model("EmptyInputModel")
-
-
-def _is_null_schema(node: Any) -> bool:
- return isinstance(node, dict) and node.get("type") == "null"
-
-
-def _unwrap_nullable_schema(schema: Dict[str, Any]) -> Dict[str, Any]:
- """Turn JSON Schema `T | null` into `T` so MCP Inspector can render widgets.
-
- Pydantic v2 emits Optional fields as `anyOf: [{type: T}, {type: null}]` (or
- `type: [T, "null"]`). Inspector/RJSF shows the property name but no input
- control for those unions.
- """
- for key in ("anyOf", "oneOf"):
- variants = schema.get(key)
- if not isinstance(variants, list) or len(variants) != 2:
- continue
- non_null = [item for item in variants if not _is_null_schema(item)]
- if len(non_null) != 1:
- continue
- merged = dict(non_null[0])
- for extra_key, extra_val in schema.items():
- if extra_key == key:
- continue
- if extra_key not in merged:
- merged[extra_key] = extra_val
- elif extra_key in ("description", "title", "default") and extra_val is not None:
- merged[extra_key] = extra_val
- if merged.get("default") is None:
- merged.pop("default", None)
- return merged
-
- types = schema.get("type")
- if isinstance(types, list):
- non_null = [item for item in types if item != "null"]
- if len(non_null) == 1:
- schema = {**schema, "type": non_null[0]}
- if schema.get("default") is None:
- schema.pop("default", None)
- return schema
-
-
-def inspector_friendly_schema(node: Any) -> Any:
- """Normalize a Pydantic JSON Schema so MCP Inspector can render form fields."""
- if isinstance(node, list):
- return [inspector_friendly_schema(item) for item in node]
- if not isinstance(node, dict):
- return node
- unwrapped = _unwrap_nullable_schema(node)
- return {key: inspector_friendly_schema(value) for key, value in unwrapped.items()}
-
-
-def tool_json_schema(schema_spec: Any) -> Optional[Dict[str, Any]]:
- """Convert a Pydantic model class or JSON-schema dict to MCP 2026-07-28 outputSchema."""
- if schema_spec is None:
- return None
- if isinstance(schema_spec, dict):
- return normalize_output_schema(inspector_friendly_schema(schema_spec))
- model = get_pydantic_model(schema_spec)
- if model is not None:
- return normalize_output_schema(inspector_friendly_schema(model.model_json_schema()))
- return None
-
-
-def _is_blank_inspector_value(value: Any) -> bool:
- """Inspector leaves unused form fields as ``""`` (or whitespace)."""
- return value is None or (isinstance(value, str) and not value.strip())
-
-
-def _omit_blank_optional_fields(payload: Dict[str, Any], input_model: Type[BaseModel]) -> Dict[str, Any]:
- """Drop blank optional/defaulted fields so Pydantic defaults apply.
-
- MCP Inspector sends ``filter: ""`` when the enum is left empty. Zod in the
- TS SDK marks that field ``.optional()`` and then uses ``args.filter || 'all'``.
- Pydantic ``default='all'`` only runs when the key is missing, not when it is
- an empty string — so we omit blanks for non-required fields.
- """
- fields = getattr(input_model, "model_fields", {}) or {}
- cleaned: Dict[str, Any] = {}
- for key, value in payload.items():
- field = fields.get(key)
- if field is not None and (not field.is_required()) and _is_blank_inspector_value(value):
- continue
- cleaned[key] = value
- return cleaned
-
-
-def parse_tool_input(input_model: Type[BaseModel], arguments: Optional[Dict[str, Any]]) -> BaseModel:
- """Validate tool arguments from Inspector or the older nested wrap.
-
- Inspector sends top-level fields (`{openNow: true}`).
- Older Python clients wrap them (`{input: {openNow: true}}`).
- Empty strings on optional fields are treated as omitted (Inspector dropdowns).
- """
- arguments = arguments or {}
- inner = arguments.get("input")
- looks_wrapped = (
- isinstance(inner, dict)
- and set(arguments.keys()) <= {"input"}
- and "input" not in input_model.model_fields
- )
- payload = inner if looks_wrapped else arguments
- if not isinstance(payload, dict):
- payload = {}
- return input_model.model_validate(_omit_blank_optional_fields(payload, input_model))
-
-
-@dataclass
-class _ToolEntry:
- config: ToolConfig
- input_model: Type[BaseModel]
- instance: Any
- method: Callable
- component: Optional[Component] = None
-
-
-@dataclass
-class _ResourceEntry:
- config: ResourceConfig
- instance: Any
- method: Callable
- param_names: List[str] = field(default_factory=list)
- pattern: Optional[Pattern] = None
- component: Optional[Component] = None
-
-
-@dataclass
-class _PromptEntry:
- config: PromptConfig
- instance: Any
- method: Callable
-
-
-_AUTH_META_KEYS = ("authorization", "x-api-key", "token", "_oauth", "headers")
-
-
-def _request_meta_from_ctx(rc: Any) -> Dict[str, Any]:
- """Flatten MCP request ``_meta`` from the low-level request context."""
- if rc is None:
- return {}
-
- raw_meta = getattr(rc, "meta", None)
- if raw_meta is None:
- return {}
- data = flatten_request_meta_object(raw_meta)
- if data:
- return data
- for key in _AUTH_META_KEYS:
- value = getattr(raw_meta, key, None)
- if value is not None:
- data[key] = value
- return data
-
-
-def _trace_context_from_request_ctx(rc: Any) -> TraceContext | None:
- return extract_trace_context(_request_meta_from_ctx(rc))
-
-
-def _read_contents_to_result(uri: str, items: List[ReadResourceContents]) -> types.ReadResourceResult:
- import base64
-
- contents: List[Any] = []
- for item in items:
- mime = item.mime_type or "text/plain"
- extra = {"_meta": item.meta} if getattr(item, "meta", None) else {}
- if isinstance(item.content, bytes):
- contents.append(
- types.BlobResourceContents(
- uri=uri,
- mimeType=mime,
- blob=base64.b64encode(item.content).decode("ascii"),
- **extra,
- )
- )
- else:
- contents.append(
- types.TextResourceContents(
- uri=uri, mimeType=mime, text=str(item.content), **extra
- )
- )
- return types.ReadResourceResult(contents=contents)
-
-
-def _http_headers_from_request_ctx(rc: Any) -> Dict[str, str]:
- if rc is None:
- return {}
- request = getattr(rc, "request", None)
- raw = getattr(request, "headers", None) if request is not None else None
- if raw is None:
- session = getattr(rc, "session", None)
- transport = getattr(session, "transport", None) if session is not None else None
- raw = getattr(transport, "headers", None) if transport is not None else None
- if raw is None:
- raw = getattr(rc, "headers", None)
- if raw is None:
- return {}
- try:
- return {str(key): str(value) for key, value in raw.items()}
- except Exception:
- return {}
-
-
-def _apply_request_envelope(ctx: ExecutionContext, rc: Any) -> None:
- http_headers = _http_headers_from_request_ctx(rc)
- envelope = bind_request_envelope(
- raw_meta=_request_meta_from_ctx(rc),
- mcp_headers=extract_mcp_scope_headers(http_headers),
- )
- ctx.rpc_meta = envelope.meta
- ctx.mcp_headers = dict(envelope.mcp_headers)
- ctx.mcp_param_headers = extract_mcp_param_headers(http_headers)
- ctx.protocol_version = envelope.protocol_version
- ctx.auth = auth_context_from_request(rc)
- if ctx.trace is None:
- ctx.trace = extract_trace_context(envelope.meta.raw)
- if ctx.jsonrpc_id is None and rc is not None:
- ctx.jsonrpc_id = getattr(rc, "request_id", None)
- if rc is not None and getattr(rc, "correlation_id", None) is None:
- try:
- rc.correlation_id = ctx.correlation_id
- except Exception:
- pass
-
-
-def _bind_correlation(rc: Any) -> tuple[str, Any]:
- """Allocate a correlation id. Never reuse the client JSON-RPC ``id`` as the key."""
- jsonrpc_id = getattr(rc, "request_id", None) if rc is not None else None
- existing = getattr(rc, "correlation_id", None) if rc is not None else None
- if existing:
- return str(existing), jsonrpc_id
- correlation_id = new_correlation_id()
- if rc is not None:
- try:
- rc.correlation_id = correlation_id
- except Exception:
- pass
- return correlation_id, jsonrpc_id
-
-
-def _tool_arguments_with_mcp_params(
- arguments: Dict[str, Any],
- param_headers: Mapping[str, str],
- input_model: Type[BaseModel],
-) -> Dict[str, Any]:
- """Fill missing tool fields from ``Mcp-Param-*``. Does not rewrite ``name``."""
- payload = dict(arguments or {})
- inner = payload.get("input")
- looks_wrapped = (
- isinstance(inner, dict)
- and set(payload.keys()) <= {"input"}
- and "input" not in input_model.model_fields
- )
- allowed = set(input_model.model_fields)
- if looks_wrapped:
- return {
- "input": merge_mcp_param_headers(
- inner, param_headers, allowed_fields=allowed
- )
- }
- return merge_mcp_param_headers(payload, param_headers, allowed_fields=allowed)
-
-
-def _auth_metadata_from_request_ctx(rc: Any) -> Dict[str, Any]:
- """Copy host-sent auth slots from MCP request ``_meta`` into ExecutionContext.
-
- Real transport headers (``rc.request.headers``) take precedence over
- client-supplied ``_meta`` values: ``_meta`` is part of the JSON-RPC payload
- and fully client-controlled, so it must not override credentials that were
- presented (or vetted) at the transport layer. ``_meta`` remains the only
- source on transports without HTTP headers (e.g. STDIO).
- """
- extra: Dict[str, Any] = {}
- if rc is None:
- return extra
-
- data = _request_meta_from_ctx(rc)
-
- auth = data.get("authorization") or data.get("Authorization")
- if isinstance(auth, str) and auth.strip():
- extra["authorization"] = auth
- api_key = data.get("x-api-key")
- if isinstance(api_key, str) and api_key.strip():
- extra["x-api-key"] = api_key
- token = data.get("token")
- if isinstance(token, str) and token.strip():
- extra["token"] = token
- oauth = data.get("_oauth")
- if isinstance(oauth, str) and oauth.strip():
- extra["_oauth"] = oauth
- headers = data.get("headers")
- if isinstance(headers, dict):
- extra["headers"] = headers
- if "authorization" not in extra:
- header_auth = headers.get("authorization") or headers.get("Authorization")
- if isinstance(header_auth, str) and header_auth.strip():
- extra["authorization"] = header_auth
- if "x-api-key" not in extra:
- header_key = headers.get("x-api-key") or headers.get("X-API-Key")
- if isinstance(header_key, str) and header_key.strip():
- extra["x-api-key"] = header_key
-
- envelope_token = bearer_token_from_envelope_auth(envelope_auth_slot(data))
- if envelope_token:
- extra["authorization"] = f"Bearer {envelope_token}"
-
- request = getattr(rc, "request", None)
- headers_obj = getattr(request, "headers", None) if request is not None else None
- if headers_obj is not None:
- try:
- http_auth = headers_obj.get("authorization") or headers_obj.get("Authorization")
- if isinstance(http_auth, str) and http_auth.strip():
- extra["authorization"] = http_auth
- http_key = headers_obj.get("x-api-key") or headers_obj.get("X-API-Key")
- if isinstance(http_key, str) and http_key.strip():
- extra["x-api-key"] = http_key
- except Exception:
- pass
- return extra
-
-class McpApplication:
- def __init__(self, app_class: Type):
- self.app_class = app_class
- if hasattr(app_class, "_mcp_app_module"):
- self.root_module = app_class._mcp_app_module
- self.server_config = app_class._mcp_app_server
- elif hasattr(app_class, "_mcp_module_config"):
- self.root_module = app_class
- self.server_config = ServerConfig(name=app_class._mcp_module_config.name or "mcp-server")
- else:
- raise ValueError("Invalid application class. Must be decorated with @mcp_app or @module.")
- _apply_project_identity(self.server_config)
-
- self.mcp_server: Optional[NitroStackMcpServer] = None
- era_resolution = resolve_protocol_era_resolution(
- config_value=self.server_config.protocol_era
- )
- self.protocol_era: ProtocolEra = era_resolution.era
- self.protocol_era_source: EraSource = era_resolution.source
-
- # nitrostack owns these registries so any number of low-level `Server`
- # instances can be wired against the same tools/resources/prompts (see
- # `create_configured_mcp_server`).
- self._tools: Dict[str, _ToolEntry] = {}
- self._resources: Dict[str, _ResourceEntry] = {}
- self._resource_templates: List[_ResourceEntry] = []
- self._prompts: Dict[str, _PromptEntry] = {}
- self._initial_tools: List[Tuple[Any, Callable, ToolConfig]] = []
- self.task_manager = TaskManager()
- self._in_flight = InFlightRegistry()
-
- self._bootstrap()
-
- def _bootstrap(self) -> None:
- # 1. Construct the low-level server directly.
- self.mcp_server = NitroStackMcpServer(
- name=self.server_config.name,
- version=self.server_config.version,
- )
-
- # 2. Resolve Module Tree recursively and register services
- resolved_modules: Set[Type] = set()
- self._resolve_modules(self.root_module, resolved_modules)
-
- container = DIContainer.get_instance()
- self._assert_declared_dependencies(resolved_modules, container)
-
- # Instantiate all providers and controllers to populate container.
- # Scan both: providers with @tool/@resource/@prompt must stay discoverable.
- module_instances: List[Any] = []
- seen_instance_ids: Set[int] = set()
- for mod in resolved_modules:
- mod_config = getattr(mod, "_mcp_module_config", None)
- if mod_config:
- for provider in mod_config.providers:
- instance = container.resolve(provider)
- if id(instance) not in seen_instance_ids:
- seen_instance_ids.add(id(instance))
- module_instances.append(instance)
- for controller in mod_config.controllers:
- instance = container.resolve(controller)
- if id(instance) not in seen_instance_ids:
- seen_instance_ids.add(id(instance))
- module_instances.append(instance)
-
- # 3. Discover decorated methods on resolved module providers and controllers
- for instance in module_instances:
- # Scan members of this instance
- for name, member in inspect.getmembers(instance):
- # Discover Tools
- if hasattr(member, "_mcp_tool_config"):
- tool_config: ToolConfig = getattr(member, "_mcp_tool_config")
- self._register_tool(instance, member, tool_config)
-
- # Discover Resources
- if hasattr(member, "_mcp_resource_config"):
- resource_config: ResourceConfig = getattr(member, "_mcp_resource_config")
- self._register_resource(instance, member, resource_config)
-
- # Discover Prompts
- if hasattr(member, "_mcp_prompt_config"):
- prompt_config: PromptConfig = getattr(member, "_mcp_prompt_config")
- self._register_prompt(instance, member, prompt_config)
-
- # Bind Health Checks
- if hasattr(member, "_mcp_health_check_name"):
- check_name = getattr(member, "_mcp_health_check_name")
- HealthCheckRegistry.bind_instance(check_name, member, instance)
-
- # Bind Event Listeners
- if hasattr(member, "_mcp_event_name"):
- event_name = getattr(member, "_mcp_event_name")
- EventEmitter.get_instance().bind_instance(event_name, member, instance)
-
- # 4. Register Built-in Health check Resource if any checks exist
- if HealthCheckRegistry.get_checks():
- self._register_health_resource()
-
- # 5. Wire every protocol handler (tools/resources/prompts/tasks/notifications)
- # onto the owned low-level server. This is factored out so additional server
- # instances (e.g. one per HTTP session) can be configured identically.
- self._setup_handlers(self.mcp_server)
-
- def _assert_declared_dependencies(
- self, resolved_modules: Set[Type], container: DIContainer
- ) -> None:
- """Fail at bootstrap when a string ``deps=[...]`` token was never registered."""
- missing: List[str] = []
- seen: Set[Type] = set()
-
- def walk(cls: Any) -> None:
- if not isinstance(cls, type) or cls in seen:
- return
- seen.add(cls)
- for dep in getattr(cls, "_mcp_deps", []) or []:
- if isinstance(dep, str):
- if not container.has_value(dep) and dep not in container._registry:
- missing.append(f"{cls.__name__} -> '{dep}'")
- elif isinstance(dep, type):
- walk(dep)
-
- for mod in resolved_modules:
- mod_config = getattr(mod, "_mcp_module_config", None)
- if not mod_config:
- continue
- for cls in [*mod_config.providers, *mod_config.controllers]:
- walk(cls)
-
- if missing:
- raise DependencyResolutionError(
- "Missing dependency at app bootstrap (referenced in deps=[...] "
- "but never registered): " + "; ".join(missing)
- )
-
- def _resolve_modules(self, module_class: Type, resolved_modules: Set[Type]) -> None:
- if module_class in resolved_modules:
- return
- resolved_modules.add(module_class)
-
- mod_config = getattr(module_class, "_mcp_module_config", None)
- if mod_config:
- for imp in mod_config.imports:
- self._resolve_modules(imp, resolved_modules)
-
- # ------------------------------------------------------------------
- # Registration (pure bookkeeping — no protocol/server calls here)
- # ------------------------------------------------------------------
-
- def _register_tool(self, instance: Any, method: Callable, tool_config: ToolConfig) -> None:
- gate_registered_schema(
- tool_config.input_schema, name=f"tool {tool_config.name!r} input"
- )
- gate_registered_schema(
- tool_config.output_schema, name=f"tool {tool_config.name!r} output"
- )
- input_model = get_pydantic_model(tool_config.input_schema)
- entry = _ToolEntry(config=tool_config, input_model=input_model, instance=instance, method=method)
-
- widget_spec = getattr(method, "_mcp_widget", None)
- if widget_spec is not None:
- options = parse_widget_options(widget_spec)
- resource_uri = widget_resource_uri(options.route)
- route_id = resource_uri.removeprefix("ui://widget/").removesuffix(".html")
- from_file = None
- method_module = inspect.getmodule(method)
- if method_module and getattr(method_module, "__file__", None):
- from_file = Path(method_module.__file__).resolve()
- project_root = find_project_root(from_file)
- html = load_widget_html(
- route_id,
- html=options.html,
- from_file=from_file,
- project_root=project_root,
- )
- if not html:
- html = build_missing_widget(route_id)
- component = Component(
- id=route_id,
- name=tool_config.title or tool_config.name,
- html=html,
- description=options.description or tool_config.description,
- css=options.css,
- js=options.js,
- csp=options.csp,
- domain=options.domain,
- prefers_border=options.prefers_border,
- can_invoke_tools=options.can_invoke_tools,
- )
- entry.component = component
- self._register_widget_resource(component)
-
- self._tools[tool_config.name] = entry
- if tool_config.is_initial:
- self._initial_tools.append((instance, method, tool_config))
-
- def _register_widget_resource(self, component: Component) -> None:
- config = ResourceConfig(
- uri=component.resource_uri,
- name=component.name,
- description=component.description or f"UI widget for {component.name}",
- mime_type=get_widget_mime_type(),
- )
-
- async def widget_resource_handler(context: ExecutionContext) -> str:
- return component.get_bundle()
-
- self._resources[config.uri] = _ResourceEntry(
- config=config,
- instance=None,
- method=widget_resource_handler,
- component=component,
- )
-
- def _register_resource(self, instance: Any, method: Callable, resource_config: ResourceConfig) -> None:
- gate_registered_schema(
- getattr(resource_config, "schema", None)
- or (resource_config.metadata or {}).get("schema"),
- name=f"resource {resource_config.uri!r}",
- )
- param_names = extract_template_param_names(resource_config.uri)
- entry = _ResourceEntry(config=resource_config, instance=instance, method=method, param_names=param_names)
-
- if param_names:
- entry.pattern = uri_template_to_pattern(resource_config.uri)
- self._resource_templates.append(entry)
- else:
- self._resources[resource_config.uri] = entry
-
- def _register_prompt(self, instance: Any, method: Callable, prompt_config: PromptConfig) -> None:
- for argument in prompt_config.arguments or []:
- gate_registered_schema(
- getattr(argument, "schema", None),
- name=f"prompt {prompt_config.name!r} argument {argument.name!r}",
- )
- self._prompts[prompt_config.name] = _PromptEntry(config=prompt_config, instance=instance, method=method)
-
- def _register_health_resource(self) -> None:
- config = ResourceConfig(
- uri="health://status",
- name="Health Status",
- description="System health status check",
- )
-
- async def health_status_resource(context: ExecutionContext) -> str:
- results = HealthCheckRegistry.run_all()
- return json.dumps(results)
-
- self._resources[config.uri] = _ResourceEntry(config=config, instance=None, method=health_status_resource)
-
- # ------------------------------------------------------------------
- # Protocol handler wiring (owned low-level `mcp.server.lowlevel.Server`)
- # ------------------------------------------------------------------
-
- def _advertise_tasks_extension(self) -> bool:
- return any(
- entry.config.task_support in ("optional", "required")
- for entry in self._tools.values()
- )
-
- def _custom_extensions(self) -> Optional[Dict[str, str]]:
- extensions = getattr(self.server_config, "extensions", None)
- if not extensions:
- return None
- return dict(extensions)
-
- def handle_server_discover(self, protocol_version: Optional[str] = None) -> Dict[str, Any]:
- """Single ``server/discover`` result for the mounted HTTP engine."""
- from nitrostack.protocol.discovery import build_discover_result
-
- has_widgets = any(
- getattr(entry, "component", None) is not None
- for entry in getattr(self, "_tools", {}).values()
- )
- version = protocol_version or protocol_version_for_era(
- getattr(self, "protocol_era", None),
- self.server_config.protocol_version,
- )
- return build_discover_result(
- server_name=self.server_config.name,
- server_version=self.server_config.version,
- protocol_version=version,
- advertise_tasks=self._advertise_tasks_extension(),
- advertise_app=has_widgets,
- custom_extensions=self._custom_extensions(),
- )
-
- def handle_sessionless_initialize(self, requested_version: Optional[str] = None) -> Dict[str, Any]:
- """Answer 2025 ``initialize`` on the sessionless ``auto`` path. No session."""
- from nitrostack.protocol.discovery import build_sessionless_initialize_result
-
- has_widgets = any(
- getattr(entry, "component", None) is not None
- for entry in getattr(self, "_tools", {}).values()
- )
- version = protocol_version_for_era(
- getattr(self, "protocol_era", None),
- self.server_config.protocol_version,
- )
- return build_sessionless_initialize_result(
- server_name=self.server_config.name,
- server_version=self.server_config.version,
- requested_version=requested_version,
- protocol_version=version,
- advertise_tasks=self._advertise_tasks_extension(),
- advertise_app=has_widgets,
- custom_extensions=self._custom_extensions(),
- )
-
- def _list_endpoint_cache_meta(self) -> Dict[str, Any]:
- return build_list_endpoint_cache_hint_meta()
-
- def _setup_handlers(self, server: NitroStackMcpServer) -> None:
- async def _list_tools(_ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]):
- return types.ListToolsResult(
- tools=[self._build_tool_definition(entry) for entry in self._tools.values()],
- _meta=self._list_endpoint_cache_meta(),
- )
-
- async def _call_tool(ctx: ServerRequestContext, params: CallToolRequestParams):
- token = request_ctx.set(ctx)
- try:
- result = await self._call_tool(
- params.name, params.arguments or {}, task=params.task
- )
- if isinstance(result, types.CreateTaskResult):
- task = result.task
- return types.CallToolResult(
- content=[types.TextContent(type="text", text=task.task_id)],
- structuredContent={
- "resultType": "task",
- "task": task.model_dump(by_alias=True),
- },
- isError=False,
- )
- return result
- finally:
- request_ctx.reset(token)
-
- async def _list_resources(_ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]):
- return types.ListResourcesResult(
- resources=[self._build_resource_definition(entry) for entry in self._resources.values()],
- _meta=self._list_endpoint_cache_meta(),
- )
-
- async def _list_resource_templates(_ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]):
- return types.ListResourceTemplatesResult(
- resource_templates=[
- self._build_resource_template_definition(entry) for entry in self._resource_templates
- ],
- )
-
- async def _read_resource(ctx: ServerRequestContext, params: ReadResourceRequestParams):
- token = request_ctx.set(ctx)
- try:
- uri = str(params.uri)
- return _read_contents_to_result(uri, await self._read_resource(uri))
- finally:
- request_ctx.reset(token)
-
- async def _subscribe_resource(_ctx: ServerRequestContext, params: SubscribeRequestParams):
- if rejects_deprecated_method("resources/subscribe", self.protocol_era):
- message = deprecated_method_message("resources/subscribe")
- raise MCPError(types.METHOD_NOT_FOUND, message or "Not supported")
- if str(params.uri) not in self._resources:
- raise ResourceNotFoundError(str(params.uri))
- return types.EmptyResult()
-
- async def _unsubscribe_resource(_ctx: ServerRequestContext, _params: UnsubscribeRequestParams):
- return types.EmptyResult()
-
- async def _list_prompts(_ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]):
- return types.ListPromptsResult(
- prompts=[self._build_prompt_definition(entry) for entry in self._prompts.values()],
- _meta=self._list_endpoint_cache_meta(),
- )
-
- async def _get_prompt(ctx: ServerRequestContext, params: GetPromptRequestParams):
- token = request_ctx.set(ctx)
- try:
- arguments = params.arguments or {}
- return await self._get_prompt(
- params.name,
- {str(key): str(value) for key, value in arguments.items()},
- )
- finally:
- request_ctx.reset(token)
-
- async def _discover(ctx: ServerRequestContext, _params: Optional[RequestParams]):
- return self.handle_server_discover(getattr(ctx, "protocol_version", None))
-
- server.add_request_handler("server/discover", RequestParams, _discover)
- server.add_request_handler("tools/list", PaginatedRequestParams, _list_tools)
- server.add_request_handler("tools/call", CallToolRequestParams, _call_tool)
- server.add_request_handler("resources/list", PaginatedRequestParams, _list_resources)
- server.add_request_handler(
- "resources/templates/list", PaginatedRequestParams, _list_resource_templates
- )
- server.add_request_handler("resources/read", ReadResourceRequestParams, _read_resource)
- server.add_request_handler("resources/subscribe", SubscribeRequestParams, _subscribe_resource)
- server.add_request_handler("resources/unsubscribe", UnsubscribeRequestParams, _unsubscribe_resource)
- server.add_request_handler("prompts/list", PaginatedRequestParams, _list_prompts)
- server.add_request_handler("prompts/get", GetPromptRequestParams, _get_prompt)
-
- async def handle_list_tools(req=None):
- return ServerResult(await _list_tools(None, None))
-
- async def handle_call_tool(req=None):
- params = getattr(req, "params", None) if req is not None else None
- name = getattr(params, "name", "") if params is not None else ""
- arguments = (getattr(params, "arguments", None) or {}) if params is not None else {}
- task = getattr(params, "task", None) if params is not None else None
- return ServerResult(await self._call_tool(name, arguments, task=task))
-
- async def handle_list_resources(req=None):
- return ServerResult(await _list_resources(None, None))
-
- async def handle_list_resource_templates(req=None):
- return ServerResult(await _list_resource_templates(None, None))
-
- async def handle_read_resource(req):
- params = getattr(req, "params", req)
- uri = str(params.uri)
- return ServerResult(_read_contents_to_result(uri, await self._read_resource(uri)))
-
- async def handle_list_prompts(req=None):
- return ServerResult(await _list_prompts(None, None))
-
- async def handle_get_prompt(req):
- params = getattr(req, "params", req)
- arguments = getattr(params, "arguments", None) or {}
- return ServerResult(
- await self._get_prompt(
- params.name,
- {str(key): str(value) for key, value in arguments.items()},
- )
- )
-
- server.request_handlers[types.ListToolsRequest] = handle_list_tools
- server.request_handlers[types.CallToolRequest] = handle_call_tool
- server.request_handlers[types.ListResourcesRequest] = handle_list_resources
- server.request_handlers[types.ListResourceTemplatesRequest] = handle_list_resource_templates
- server.request_handlers[types.ReadResourceRequest] = handle_read_resource
- server.request_handlers[types.ListPromptsRequest] = handle_list_prompts
- server.request_handlers[types.GetPromptRequest] = handle_get_prompt
-
- self._register_task_handlers(server)
- self._register_initialized_handler(server)
- server.discover_handler = self.handle_server_discover
- server.initialize_handler = self.handle_sessionless_initialize
-
- def create_configured_mcp_server(self) -> NitroStackMcpServer:
- """
- Build a fresh, fully-wired low-level server instance sharing this
- application's tool/resource/prompt registries. A single shared server is
- sufficient for the Python `mcp` SDK's HTTP session managers (unlike the TS
- SDK's `Server`, `.run()` here does not bind a transport for the instance's
- lifetime), but this factory is kept available for isolated/stateless use
- cases (e.g. Phase 3 extensions) that want their own server instance.
- """
- server = NitroStackMcpServer(name=self.server_config.name, version=self.server_config.version)
- self._setup_handlers(server)
- return server
-
- # ------------------------------------------------------------------
- # Definition builders (registry entry -> wire-level `mcp.types` objects)
- # ------------------------------------------------------------------
-
- def _tool_input_schema(self, input_model: Type[BaseModel]) -> Dict[str, Any]:
- """JSON Schema for `tools/list` with fields at the top level.
-
- MCP Inspector renders `inputSchema.properties` as form fields. Nesting
- the model under `properties.input.$ref` only showed labels.
- """
- schema = inspector_friendly_schema(input_model.model_json_schema())
- if not isinstance(schema, dict):
- schema = {}
- schema.setdefault("type", "object")
- schema.setdefault("properties", {})
- return normalize_input_schema(schema)
-
- def _build_tool_definition(self, entry: _ToolEntry) -> types.Tool:
- cfg = entry.config
- input_schema = self._tool_input_schema(entry.input_model)
-
- meta: Dict[str, Any] = {
- "is_initial": cfg.is_initial,
- "visibility": cfg.visibility,
- "task_support": cfg.task_support,
- **(cfg.metadata or {}),
- }
-
- if entry.component is not None:
- widget_meta = build_tool_list_meta(
- entry.component,
- cfg.visibility,
- cfg.invocation,
- )
- meta.update(widget_meta)
- elif cfg.invocation and is_openai_mode():
- meta["openai/toolInvocation/invoking"] = cfg.invocation.invoking
- meta["openai/toolInvocation/invoked"] = cfg.invocation.invoked
-
- if cfg.examples:
- meta["examples"] = {
- "input": cfg.examples.input,
- "output": cfg.examples.output,
- "description": cfg.examples.description,
- }
-
- cache_meta = resolve_tool_cache_hint_meta(cfg, entry.method)
- if cache_meta:
- meta.update(cache_meta)
-
- if is_openai_mode():
- meta["openai/type"] = "function"
- meta["openai/function"] = {
- "name": cfg.name,
- "description": cfg.description,
- "parameters": input_schema,
- }
-
- annotations = types.ToolAnnotations(
- readOnlyHint=cfg.annotations.read_only_hint,
- destructiveHint=cfg.annotations.destructive_hint,
- idempotentHint=cfg.annotations.idempotent_hint,
- openWorldHint=cfg.annotations.open_world_hint,
- )
-
- execution = None
- if cfg.task_support and cfg.task_support != "forbidden":
- execution = types.ToolExecution(taskSupport=cfg.task_support)
-
- tool_kwargs: Dict[str, Any] = {
- "name": cfg.name,
- "title": cfg.title,
- "description": cfg.description,
- "inputSchema": input_schema,
- "annotations": annotations,
- "execution": execution,
- "_meta": meta,
- }
- if entry.component is not None and is_openai_mode():
- tool_kwargs["outputTemplate"] = entry.component.resource_uri
-
- output_schema = tool_json_schema(cfg.output_schema)
- if output_schema is not None:
- tool_kwargs["outputSchema"] = output_schema
-
- return types.Tool(**tool_kwargs)
-
- def _build_resource_definition(self, entry: _ResourceEntry) -> types.Resource:
- cfg = entry.config
- meta = dict(cfg.metadata or {})
- cache_meta = resolve_resource_cache_hint_meta(cfg)
- if cache_meta:
- meta.update(cache_meta)
- resource_kwargs: Dict[str, Any] = {
- "uri": cfg.uri,
- "name": cfg.name,
- "title": cfg.title,
- "description": cfg.description,
- "mimeType": cfg.mime_type,
- "size": cfg.size,
- }
- if meta:
- resource_kwargs["_meta"] = meta
- return types.Resource(**resource_kwargs)
-
- def _build_resource_template_definition(self, entry: _ResourceEntry) -> types.ResourceTemplate:
- cfg = entry.config
- return types.ResourceTemplate(
- uriTemplate=cfg.uri,
- name=cfg.name,
- title=cfg.title,
- description=cfg.description,
- mimeType=cfg.mime_type,
- )
-
- def _build_prompt_definition(self, entry: _PromptEntry) -> types.Prompt:
- cfg = entry.config
- arguments = [
- types.PromptArgument(name=arg.name, description=arg.description, required=arg.required)
- for arg in cfg.arguments
- ]
- return types.Prompt(name=cfg.name, description=cfg.description, arguments=arguments or None)
-
- # ------------------------------------------------------------------
- # Request dispatch
- # ------------------------------------------------------------------
-
- def _pipeline_stages(self, method: Callable) -> Tuple[List[Type], List[Type], List[Type], List[Type], List[Type]]:
- return (
- getattr(method, "_mcp_guards", []),
- getattr(method, "_mcp_middleware", []),
- getattr(method, "_mcp_interceptors", []),
- getattr(method, "_mcp_pipes", []),
- getattr(method, "_mcp_filters", []),
- )
-
- def _to_call_tool_result(
- self,
- result: Any,
- component: Optional[Component] = None,
- context: Optional[ExecutionContext] = None,
- ) -> types.CallToolResult:
- if isinstance(result, InputRequiredResult):
- wire = result.to_wire_dict()
- return types.CallToolResult(
- content=[types.TextContent(type="text", text=wire.get("message", "Input required"))],
- structuredContent=wire,
- isError=False,
- )
- mrtr_result = None
- if isinstance(result, dict) and result.get("resultType") == "input_required":
- from nitrostack.protocol.mrtr import coerce_input_required_result
-
- mrtr_result = coerce_input_required_result(result)
- if mrtr_result is not None:
- wire = mrtr_result.to_wire_dict()
- return types.CallToolResult(
- content=[types.TextContent(type="text", text=wire.get("message", "Input required"))],
- structuredContent=wire,
- isError=False,
- )
- if isinstance(result, types.CallToolResult):
- if component is not None:
- result = result.model_copy(
- update={"meta": build_call_tool_result_meta(component, self._call_tool_result_meta(result))}
- )
- return result
- if isinstance(result, BaseModel):
- result = result.model_dump()
-
- structured: Any = result
- result_meta: Optional[Dict[str, Any]] = None
-
- if component is not None:
- if component.transformer is not None:
- structured = component.transformer(result, context)
- if component.meta_transformer is not None:
- result_meta = component.meta_transformer(result, context) or {}
- if isinstance(structured, BaseModel):
- structured = structured.model_dump()
-
- if isinstance(result, dict) and "content" in result and "isError" in result:
- call_result = types.CallToolResult(**result)
- if component is not None:
- call_result = call_result.model_copy(
- update={"meta": build_call_tool_result_meta(component, self._call_tool_result_meta(call_result))}
- )
- return call_result
-
- if isinstance(structured, dict):
- widget_meta = build_call_tool_result_meta(component, result_meta) if component else result_meta
- return types.CallToolResult(
- content=self._widget_result_content(structured, component),
- structuredContent=structured,
- **({"_meta": widget_meta} if widget_meta else {}),
- isError=False,
- )
-
- return types.CallToolResult(
- content=[types.TextContent(type="text", text=str(structured))],
- isError=False,
- )
-
- @staticmethod
- def _call_tool_result_meta(result: types.CallToolResult) -> Optional[Dict[str, Any]]:
- """Read caller ``_meta`` from the field or pydantic extra (alias vs extra)."""
- if result.meta:
- return dict(result.meta)
- extra = getattr(result, "model_extra", None) or {}
- raw = extra.get("_meta") or extra.get("meta")
- return dict(raw) if isinstance(raw, dict) else None
-
- def _widget_result_content(self, structured: Dict[str, Any], component: Optional[Component]) -> List[Any]:
- """Text fallback plus data-filled HTML so Inspector/Studio can paint the live result."""
- content: List[Any] = [
- types.TextContent(type="text", text=json.dumps(structured, indent=2, default=str)),
- ]
- if component is None:
- return content
- mime = get_widget_mime_type()
- try:
- filled = component.html_with_data(structured)
- except Exception:
- logger.exception(
- "Widget HTML render failed for %s; returning JSON without embedded HTML",
- component.id,
- )
- filled = None
- if filled is not None:
- content.append(
- types.EmbeddedResource(
- type="resource",
- resource=types.TextResourceContents(
- uri=component.resource_uri,
- mimeType=mime,
- text=filled,
- ),
- )
- )
- content.append(
- types.ResourceLink(
- type="resource_link",
- uri=component.resource_uri,
- name=component.name,
- description=component.description,
- mimeType=mime,
- )
- )
- return content
-
- async def _call_tool(self, name: str, arguments: Dict[str, Any], task: Any = None):
- entry = self._tools.get(name)
- if entry is None:
- return types.CallToolResult(
- content=[types.TextContent(type="text", text=f"Tool '{name}' not found")],
- isError=True,
- )
-
- cfg = entry.config
- tool_arguments, input_responses, request_state = split_mrtr_from_arguments(
- strip_tool_arguments(arguments)
- )
- rc = request_ctx.get(None)
- tool_arguments = _tool_arguments_with_mcp_params(
- tool_arguments,
- extract_mcp_param_headers(_http_headers_from_request_ctx(rc)),
- entry.input_model,
- )
- # Pydantic validates after accepting either Inspector top-level fields
- # or the older `{input: {...}}` wrap. Low-level jsonschema is off
- # (`validate_input=False`) so the wrap is not rejected against the
- # published top-level inputSchema.
- input_instance = parse_tool_input(entry.input_model, tool_arguments)
- guards, middleware, interceptors, pipes, filters = self._pipeline_stages(entry.method)
-
- # Task metadata: explicit ``params.task``, then the 1.x experimental
- # slot, then the official request context ``params`` mapping.
- task_metadata = task
- session = None
- progress_token = None
- if rc is not None:
- if task_metadata is None and getattr(rc, "experimental", None) is not None:
- task_metadata = rc.experimental.task_metadata
- params = getattr(rc, "params", None)
- if task_metadata is None:
- task_metadata = getattr(params, "task", None)
- if task_metadata is None and isinstance(params, Mapping):
- task_metadata = params.get("task")
- meta = getattr(rc, "meta", None)
- if isinstance(meta, Mapping):
- progress_token = meta.get("progress_token") or meta.get("progressToken")
- elif meta is not None:
- progress_token = getattr(meta, "progress_token", None) or getattr(
- meta, "progressToken", None
- )
- session = getattr(rc, "session", None)
- auth_meta = _auth_metadata_from_request_ctx(rc)
- trace = _trace_context_from_request_ctx(rc)
-
- is_task = task_metadata is not None
- if cfg.task_support == "forbidden" and task_metadata is not None:
- raise MCPError(
- types.METHOD_NOT_FOUND,
- task_support_forbidden_message(cfg.name),
- )
- if cfg.task_support == "required" and task_metadata is None:
- raise MCPError(
- types.INVALID_REQUEST,
- task_support_required_message(cfg.name),
- )
-
- if is_task:
- ttl_ms = (
- task_metadata.ttl
- if task_metadata and task_metadata.ttl is not None
- else DEFAULT_TASK_TTL_MS
- )
- task_access = extract_task_access_context(rc)
- task = await self.task_manager.create_task(
- ttl_ms=ttl_ms,
- tool_name=cfg.name,
- owner_id=task_access.user_id if task_access else None,
- tenant_id=task_access.tenant_id if task_access else None,
- session_id=task_access.session_id if task_access else None,
- )
- task_id = task.id
- correlation_id, jsonrpc_id = _bind_correlation(rc)
-
- async def background_execution():
- task_ctx = ExecutionContext(
- request_id=correlation_id,
- correlation_id=correlation_id,
- jsonrpc_id=jsonrpc_id,
- tool_name=cfg.name,
- metadata={"input": input_instance, **auth_meta},
- input_responses=input_responses,
- request_state=request_state,
- trace=trace,
- )
- _apply_request_envelope(task_ctx, rc)
- task_ctx.task = TaskContext(
- task_id,
- self.task_manager,
- session=session,
- progress_token=progress_token,
- correlation_id=correlation_id,
- )
- try:
- result = await run_pipeline(
- handler=entry.method,
- handler_instance=entry.instance,
- args=(input_instance, task_ctx),
- kwargs={},
- context=task_ctx,
- guards=guards,
- middleware=middleware,
- interceptors=interceptors,
- pipes=pipes,
- filters=filters,
- param_name="input",
- param_type=entry.input_model,
- )
- if isinstance(result, InputRequiredResult):
- await self.task_manager.require_input(
- task_id,
- result.to_wire_dict(),
- progress=result.message or "Additional input required",
- )
- else:
- await self.task_manager.complete_task(
- task_id, self._to_call_tool_result(result, entry.component, task_ctx)
- )
- except Exception as e:
- try:
- await self.task_manager.fail_task(task_id, e)
- except (TaskAlreadyTerminalError, TaskExpiredError):
- # Cancelled/expired while running — leave terminal state as-is.
- pass
-
- asyncio.create_task(background_execution())
- return types.CreateTaskResult(task=self._task_data_to_mcp_task(task))
-
- correlation_id, jsonrpc_id = _bind_correlation(rc)
- ctx = ExecutionContext(
- request_id=correlation_id,
- correlation_id=correlation_id,
- jsonrpc_id=jsonrpc_id,
- tool_name=cfg.name,
- metadata={"input": input_instance, **auth_meta},
- input_responses=input_responses,
- request_state=request_state,
- trace=trace,
- )
- _apply_request_envelope(ctx, rc)
- ticket = self._in_flight.register(correlation_id, jsonrpc_id=jsonrpc_id)
- try:
- result = await run_pipeline(
- handler=entry.method,
- handler_instance=entry.instance,
- args=(input_instance, ctx),
- kwargs={},
- context=ctx,
- guards=guards,
- middleware=middleware,
- interceptors=interceptors,
- pipes=pipes,
- filters=filters,
- param_name="input",
- param_type=entry.input_model,
- )
- except Exception as exc:
- logger.exception("Tool %s failed", cfg.name)
- return types.CallToolResult(
- content=[types.TextContent(type="text", text=str(exc))],
- isError=True,
- )
- finally:
- self._in_flight.discard(correlation_id)
- if ticket.cancel_requested.is_set():
- return types.CallToolResult(
- content=[types.TextContent(type="text", text="Request was cancelled.")],
- isError=True,
- )
- return self._to_call_tool_result(result, entry.component, ctx)
-
- async def _read_resource(self, uri: str) -> List[ReadResourceContents]:
- entry = self._resources.get(uri)
- path_kwargs: Dict[str, str] = {}
-
- if entry is None:
- for template_entry in self._resource_templates:
- match = template_entry.pattern.match(uri) if template_entry.pattern else None
- if match:
- entry = template_entry
- path_kwargs = match.groupdict()
- break
-
- if entry is None:
- raise ResourceNotFoundError(uri)
-
- if entry.component is not None:
- return [
- ReadResourceContents(
- content=entry.component.get_bundle(),
- mime_type=get_widget_mime_type(),
- meta=resource_read_contents_meta(entry.component),
- )
- ]
-
- cfg = entry.config
- ctx = ExecutionContext(request_id=str(uuid.uuid4()), metadata=dict(path_kwargs))
- _apply_request_envelope(ctx, request_ctx.get(None))
- guards, middleware, interceptors, pipes, filters = self._pipeline_stages(entry.method)
-
- result = await run_pipeline(
- handler=entry.method,
- handler_instance=entry.instance,
- args=(),
- kwargs={**path_kwargs, "context": ctx},
- context=ctx,
- guards=guards,
- middleware=middleware,
- interceptors=interceptors,
- pipes=pipes,
- filters=filters,
- )
-
- # Support Discriminated Union formats for return (Section 1.2)
- if isinstance(result, dict) and "type" in result and "data" in result:
- result = result["data"]
-
- if isinstance(result, BaseModel):
- result = result.model_dump()
-
- if isinstance(result, bytes):
- return [ReadResourceContents(content=result, mime_type=cfg.mime_type or "application/octet-stream")]
-
- if isinstance(result, str):
- return [ReadResourceContents(content=result, mime_type=cfg.mime_type or "text/plain")]
-
- text = json.dumps(result, indent=2, default=str)
- return [ReadResourceContents(content=text, mime_type=cfg.mime_type or "application/json")]
-
- async def _get_prompt(self, name: str, arguments: Dict[str, str]) -> types.GetPromptResult:
- entry = self._prompts.get(name)
- if entry is None:
- raise PromptNotFoundError(name)
-
- cfg = entry.config
- args_dict = dict(arguments or {})
- rc = request_ctx.get(None)
- allowed = {arg.name for arg in cfg.arguments} if cfg.arguments else None
- args_dict = merge_mcp_param_headers(
- args_dict,
- extract_mcp_param_headers(_http_headers_from_request_ctx(rc)),
- allowed_fields=allowed,
- )
- ctx = ExecutionContext(request_id=str(uuid.uuid4()), metadata=args_dict)
- _apply_request_envelope(ctx, rc)
- guards, middleware, interceptors, pipes, filters = self._pipeline_stages(entry.method)
-
- raw_messages = await run_pipeline(
- handler=entry.method,
- handler_instance=entry.instance,
- args=(args_dict, ctx),
- kwargs={},
- context=ctx,
- guards=guards,
- middleware=middleware,
- interceptors=interceptors,
- pipes=pipes,
- filters=filters,
- )
-
- if not isinstance(raw_messages, (list, tuple)):
- raw_messages = [raw_messages]
-
- messages: List[types.PromptMessage] = []
- for msg in raw_messages:
- role = msg.role if hasattr(msg, "role") else msg.get("role")
- content = msg.content if hasattr(msg, "content") else msg.get("content")
- messages.append(types.PromptMessage(role=role, content=types.TextContent(type="text", text=content)))
-
- return types.GetPromptResult(description=cfg.description, messages=messages)
-
- # ------------------------------------------------------------------
- # Task subsystem — registered on the low-level server's public
- # `request_handlers`/`notification_handlers` dicts.
- # ------------------------------------------------------------------
-
- def _task_data_to_mcp_task(self, task) -> types.Task:
- """Map TaskData to MCP Task. EXPIRED is not an MCP wire status — surface as error."""
- if task.status == TaskStatus.EXPIRED:
- raise MCPError(types.INVALID_PARAMS, f"Task {task.id} has expired")
- return types.Task(
- taskId=task.id,
- status=task.status.value,
- statusMessage=task.progress or "",
- createdAt=_iso_timestamp(task.created_at),
- lastUpdatedAt=_iso_timestamp(task.last_updated_at or task.created_at),
- ttl=task.ttl if task.ttl is not None else 0,
- pollInterval=task.poll_interval,
- )
-
- def _serialize_task_result_payload(self, result: Any) -> Any:
- if isinstance(result, types.CallToolResult):
- return result.model_dump(by_alias=True, exclude_none=True)
- if isinstance(result, BaseModel):
- return result.model_dump()
- return result
-
- def _build_get_task_result(self, task) -> types.GetTaskResult:
- mcp_task = self._task_data_to_mcp_task(task)
- payload: Dict[str, Any] = {
- "taskId": mcp_task.task_id,
- "status": mcp_task.status,
- "statusMessage": mcp_task.status_message,
- "createdAt": mcp_task.created_at,
- "lastUpdatedAt": mcp_task.last_updated_at,
- "ttl": mcp_task.ttl,
- "pollInterval": mcp_task.poll_interval,
- }
- if task.status == TaskStatus.COMPLETED and task.result is not None:
- payload["result"] = self._serialize_task_result_payload(task.result)
- elif task.status == TaskStatus.FAILED and task.error is not None:
- payload["error"] = {"message": str(task.error)}
- elif task.status == TaskStatus.INPUT_REQUIRED and task.result is not None:
- payload["result"] = task.result
- return GetTaskResult(**payload)
-
- def _register_task_handlers(self, server: NitroStackMcpServer) -> None:
- async def handle_list_tasks(req):
- if rejects_deprecated_method("tasks/list", self.protocol_era):
- message = deprecated_method_message("tasks/list")
- raise MCPError(types.METHOD_NOT_FOUND, message or "Not supported")
- tasks_list = []
- access = extract_task_access_context(request_ctx.get(None))
- params = getattr(req, "params", req)
- cursor = getattr(params, "cursor", None) if params is not None else None
- tasks_page, next_cursor = await self.task_manager.list_tasks_page(
- access_context=access,
- cursor=cursor,
- )
- for t in tasks_page:
- if t.status == TaskStatus.EXPIRED:
- continue
- tasks_list.append(self._task_data_to_mcp_task(t))
- return types.ListTasksResult(tasks=tasks_list, nextCursor=next_cursor)
-
- async def handle_get_task(req):
- params = getattr(req, "params", req)
- task_id = getattr(params, "task_id", None) or getattr(params, "taskId", None)
- access = extract_task_access_context(request_ctx.get(None))
- try:
- t = await self.task_manager.get_task(task_id, access_context=access)
- except TaskNotFoundError:
- raise MCPError(types.INVALID_PARAMS, f"Task {task_id} not found")
- return self._build_get_task_result(t)
-
- async def handle_cancel_task(req):
- params = getattr(req, "params", req)
- task_id = getattr(params, "task_id", None) or getattr(params, "taskId", None)
- access = extract_task_access_context(request_ctx.get(None))
- try:
- await self.task_manager.cancel_task(task_id, access_context=access)
- t = await self.task_manager.get_task(task_id, access_context=access)
- except TaskNotFoundError:
- raise MCPError(types.INVALID_PARAMS, f"Task {task_id} not found")
- except TaskExpiredError:
- raise MCPError(types.INVALID_PARAMS, f"Task {task_id} has expired")
- except TaskAlreadyTerminalError as e:
- raise MCPError(types.INVALID_PARAMS, str(e))
- mcp_task = self._task_data_to_mcp_task(t)
- return types.CancelTaskResult(
- taskId=mcp_task.task_id,
- status=mcp_task.status,
- statusMessage=mcp_task.status_message,
- createdAt=mcp_task.created_at,
- lastUpdatedAt=mcp_task.last_updated_at,
- ttl=mcp_task.ttl,
- pollInterval=mcp_task.poll_interval,
- )
-
- async def handle_get_task_payload(req):
- if rejects_deprecated_method("tasks/result", self.protocol_era):
- message = deprecated_method_message("tasks/result")
- raise MCPError(types.METHOD_NOT_FOUND, message or "Not supported")
- params = getattr(req, "params", req)
- task_id = getattr(params, "task_id", None) or getattr(params, "taskId", None)
- access = extract_task_access_context(request_ctx.get(None))
- try:
- t = await self.task_manager.wait_until_done(task_id, access_context=access)
- except TaskNotFoundError:
- raise MCPError(types.INVALID_PARAMS, f"Task {task_id} not found")
- if t.status == TaskStatus.COMPLETED:
- return t.result
- if t.status == TaskStatus.CANCELLED:
- return types.CallToolResult(
- content=[types.TextContent(type="text", text="Task was cancelled.")],
- isError=True,
- )
- if t.status == TaskStatus.EXPIRED:
- return types.CallToolResult(
- content=[types.TextContent(type="text", text="Task has expired.")],
- isError=True,
- )
- return types.CallToolResult(
- content=[types.TextContent(type="text", text=str(t.error or t.progress))],
- isError=True,
- )
-
- async def on_list_tasks(ctx: ServerRequestContext, params: Optional[PaginatedRequestParams]):
- token = request_ctx.set(ctx)
- try:
- return await handle_list_tasks(types.ListTasksRequest(params=params))
- finally:
- request_ctx.reset(token)
-
- async def on_get_task(ctx: ServerRequestContext, params: types.GetTaskRequestParams):
- token = request_ctx.set(ctx)
- try:
- return await handle_get_task(types.GetTaskRequest(params=params))
- finally:
- request_ctx.reset(token)
-
- async def on_cancel_task(ctx: ServerRequestContext, params: types.CancelTaskRequestParams):
- token = request_ctx.set(ctx)
- try:
- return await handle_cancel_task(types.CancelTaskRequest(params=params))
- finally:
- request_ctx.reset(token)
-
- async def on_get_task_payload(ctx: ServerRequestContext, params: types.GetTaskPayloadRequestParams):
- token = request_ctx.set(ctx)
- try:
- return await handle_get_task_payload(types.GetTaskPayloadRequest(params=params))
- finally:
- request_ctx.reset(token)
-
- server.add_request_handler("tasks/list", PaginatedRequestParams, on_list_tasks)
- server.add_request_handler("tasks/get", types.GetTaskRequestParams, on_get_task)
- server.add_request_handler("tasks/cancel", types.CancelTaskRequestParams, on_cancel_task)
- server.add_request_handler("tasks/result", types.GetTaskPayloadRequestParams, on_get_task_payload)
- server.request_handlers[types.ListTasksRequest] = handle_list_tasks
- server.request_handlers[types.GetTaskRequest] = handle_get_task
- server.request_handlers[types.CancelTaskRequest] = handle_cancel_task
- server.request_handlers[types.GetTaskPayloadRequest] = handle_get_task_payload
- server.has_task_support = True
-
- def _register_initialized_handler(self, server: NitroStackMcpServer) -> None:
- async def handle_initialized(notification: types.InitializedNotification):
- for instance, method, config in self._initial_tools:
- try:
- entry = self._tools[config.name]
- try:
- input_inst = entry.input_model()
- except Exception:
- input_inst = None
-
- ctx = ExecutionContext(
- request_id=f"initial-tool-{uuid.uuid4().hex[:8]}",
- tool_name=config.name,
- metadata={},
- )
- _apply_request_envelope(ctx, request_ctx.get(None))
- guards, middleware, interceptors, pipes, filters = self._pipeline_stages(method)
-
- await run_pipeline(
- handler=method,
- handler_instance=instance,
- args=(input_inst, ctx),
- kwargs={},
- context=ctx,
- guards=guards,
- middleware=middleware,
- interceptors=interceptors,
- pipes=pipes,
- filters=filters,
- param_name="input",
- param_type=entry.input_model,
- )
- except Exception as e:
- sys.stderr.write(f"Error executing initial tool '{config.name}': {e}\n")
- sys.stderr.flush()
-
- async def on_initialized(ctx: ServerRequestContext, _params: Optional[types.NotificationParams]):
- token = request_ctx.set(ctx)
- try:
- await handle_initialized(types.InitializedNotification())
- finally:
- request_ctx.reset(token)
-
- server.add_notification_handler(
- "notifications/initialized", types.NotificationParams, on_initialized
- )
- server.notification_handlers[types.InitializedNotification] = handle_initialized
-
- # ------------------------------------------------------------------
- # Transports
- # ------------------------------------------------------------------
-
- def _apply_protocol_era(self) -> ProtocolEra:
- """Re-read env/config, store the era, and log how it was chosen."""
- resolution = resolve_protocol_era_resolution(
- config_value=self.server_config.protocol_era
- )
- self.protocol_era = resolution.era
- self.protocol_era_source = resolution.source
- logger.info(resolution.log_line())
- return resolution.era
-
- def get_combined_app(
- self,
- *,
- max_sessions: Optional[int] = None,
- session_idle_timeout: Optional[float] = None,
- enable_cors: Optional[bool] = None,
- stateless: Optional[bool] = None,
- json_response: Optional[bool] = None,
- ) -> Any:
- """
- Build the Starlette app wiring the owned low-level server to the Streamable
- HTTP (`/mcp`), legacy SSE (`/sse` + `/mcp/messages/`), and health-check
- (`/mcp/health`) endpoints. See `nitrostack.transports.http.build_http_app`
- for the full behavior (session cap, CORS, DNS-rebinding protection).
-
- Any argument left as ``None`` falls back to env
- (``MCP_STATELESS``, ``NITRO_MCP_PROTOCOL_VERSION``, ``ENABLE_CORS``)
- then this app's ``ServerConfig.protocol_era``. Unset protocol era is ``auto``.
- """
- from nitrostack.transports.http import build_http_app
-
- era = self._apply_protocol_era()
- wire_mode = wire_mode_for_era(era)
- # Sessionful 1.x only when era is legacy. auto/modern stay sessionless.
- http_engine = resolve_http_engine(era, stateless=stateless)
- effective_stateless = http_engine == "sessionless"
-
- if enable_cors is None:
- env_cors = self._env_bool("ENABLE_CORS")
- enable_cors = True if env_cors is None else env_cors
-
- http_app = build_http_app(
- self,
- max_sessions=max_sessions if max_sessions is not None else self.server_config.max_sessions,
- session_idle_timeout=session_idle_timeout,
- enable_cors=enable_cors,
- stateless=effective_stateless,
- json_response=self.server_config.json_response if json_response is None else json_response,
- protocol_era=era,
- wire_mode=wire_mode,
- http_engine=http_engine,
- )
-
- if http_engine == "sessionless":
- from nitrostack.transports.middleware import wrap_stateless_transport
-
- def _discover_handler(_request):
- return self.handle_server_discover()
-
- def _initialize_handler(request):
- params = getattr(request, "params", None) or {}
- requested = params.get("protocolVersion") if isinstance(params, dict) else None
- return self.handle_sessionless_initialize(
- requested if isinstance(requested, str) else None
- )
-
- http_app = wrap_stateless_transport(
- http_app,
- server_name=self.server_config.name,
- server_version=self.server_config.version,
- protocol_version=protocol_version_for_era(era, self.server_config.protocol_version),
- advertise_tasks=self._advertise_tasks_extension(),
- advertise_app=any(
- getattr(entry, "component", None) is not None
- for entry in getattr(self, "_tools", {}).values()
- ),
- custom_extensions=self._custom_extensions(),
- wire_mode=wire_mode,
- protocol_era=era,
- enable_cors=enable_cors,
- discover_handler=_discover_handler,
- initialize_handler=_initialize_handler,
- )
-
- return http_app
-
- async def _run_stdio(self) -> None:
- from nitrostack.transports.stdio import run_stdio
-
- await run_stdio(self.mcp_server, self.protocol_era)
-
- @staticmethod
- def _env_int(name: str) -> Optional[int]:
- raw = os.environ.get(name)
- if raw is None or raw == "":
- return None
- try:
- return int(raw)
- except ValueError:
- return None
-
- @staticmethod
- def _env_bool(name: str) -> Optional[bool]:
- raw = os.environ.get(name)
- if raw is None or raw == "":
- return None
- return raw.strip().lower() in ("1", "true", "yes", "on")
-
- async def start(self) -> None:
- """Starts the MCP application based on transport configurations."""
- # Start background OAuth discovery only when OAuthModule registered a service.
- # resolve(OAuthService) would otherwise auto-instantiate and fail closed.
- from nitrostack.auth.oauth import OAuthService, warn_if_oauth_fail_open
-
- container = DIContainer.get_instance()
- if container.has_value(OAuthService):
- oauth_service = container.resolve(OAuthService)
- oauth_service.start_discovery_server()
- warn_if_oauth_fail_open()
-
- transport = os.environ.get("MCP_TRANSPORT_TYPE") or self.server_config.transport_type
- node_env = os.environ.get("NODE_ENV", "development")
- port = resolve_http_port()
- host = resolve_http_host()
-
- json_response = self._env_bool("MCP_JSON_RESPONSE")
- if json_response is None:
- json_response = self.server_config.json_response
- max_sessions = self._env_int("MCP_MAX_SESSIONS") or self.server_config.max_sessions
- session_timeout_ms = self._env_int("MCP_SESSION_TIMEOUT_MS") or self.server_config.session_timeout_ms
- session_idle_timeout = (session_timeout_ms / 1000) if session_timeout_ms else None
- graceful_timeout_ms = self._env_int("MCP_GRACEFUL_SHUTDOWN_TIMEOUT_MS") or 10000
-
- if transport == "http":
- import uvicorn
- app = self.get_combined_app(
- max_sessions=max_sessions,
- session_idle_timeout=session_idle_timeout,
- json_response=json_response,
- )
- config = uvicorn.Config(
- app,
- host=host,
- port=port,
- log_level="info",
- timeout_graceful_shutdown=graceful_timeout_ms / 1000,
- )
- server = uvicorn.Server(config)
- await server.serve()
- elif transport == "dual" or (node_env == "production" and not transport):
- from nitrostack.transports.dual import run_dual
-
- app = self.get_combined_app(
- max_sessions=max_sessions,
- session_idle_timeout=session_idle_timeout,
- json_response=json_response,
- )
- await run_dual(
- self,
- app,
- host=host,
- port=port,
- graceful_timeout=graceful_timeout_ms / 1000,
- )
- else:
- # Default Stdio
- self._apply_protocol_era()
- from nitrostack.transports.stdio import safe_stdio_transport
- with safe_stdio_transport():
- await self._run_stdio()
-
-class McpApplicationFactory:
- @classmethod
- async def create(cls, app_class: Type) -> McpApplication:
- """Bootstraps and instantiates the McpApplication class."""
- return McpApplication(app_class)
+__all__ = [
+ "DEFAULT_HTTP_PORT",
+ "GetTaskResult",
+ "McpApplication",
+ "McpApplicationFactory",
+ "ServerConfig",
+ "_AUTH_META_KEYS",
+ "_PromptEntry",
+ "_ResourceEntry",
+ "_ToolEntry",
+ "_apply_project_identity",
+ "_apply_request_envelope",
+ "_auth_metadata_from_request_ctx",
+ "_bind_correlation",
+ "_http_headers_from_request_ctx",
+ "_is_blank_inspector_value",
+ "_is_null_schema",
+ "_iso_timestamp",
+ "_omit_blank_optional_fields",
+ "_project_identity",
+ "_read_contents_to_result",
+ "_read_dotenv_value",
+ "_request_meta_from_ctx",
+ "_tool_arguments_with_mcp_params",
+ "_trace_context_from_request_ctx",
+ "_unwrap_nullable_schema",
+ "get_pydantic_model",
+ "inspector_friendly_schema",
+ "mcp_app",
+ "parse_tool_input",
+ "resolve_http_host",
+ "resolve_http_port",
+ "tool_json_schema",
+]
diff --git a/nitrostack/core/app_config.py b/nitrostack/core/app_config.py
new file mode 100644
index 0000000..9e62fab
--- /dev/null
+++ b/nitrostack/core/app_config.py
@@ -0,0 +1,140 @@
+"""Application configuration, decorator, and startup metadata helpers."""
+
+import logging
+import os
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, List, Literal, Optional, Type
+
+import mcp.types as types
+
+from nitrostack.protocol.version import (
+ MODERN_PROTOCOL_VERSION,
+)
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_HTTP_PORT = 3000
+
+
+def _iso_timestamp(value: Any) -> str:
+ """Official Task timestamps are ISO-8601 strings."""
+ if hasattr(value, "isoformat"):
+ text = value.isoformat()
+ if text.endswith("+00:00"):
+ return text[:-6] + "Z"
+ return text
+ return str(value)
+
+
+class GetTaskResult(types.GetTaskResult):
+ """Official GetTaskResult plus NitroStack-owned ``result`` / ``error`` slots."""
+
+ result: Any = None
+ error: Any = None
+
+
+def resolve_http_port() -> int:
+ """MCP HTTP/dual bind port. Defaults to 3000; 3001 is reserved for widgets."""
+ return int(os.environ.get("PORT") or os.environ.get("MCP_SERVER_PORT") or DEFAULT_HTTP_PORT)
+
+
+def resolve_http_host() -> str:
+ """Bind host. ``HOST`` matches the TypeScript templates; default is ``127.0.0.1``."""
+ return (os.environ.get("HOST") or "127.0.0.1").strip() or "127.0.0.1"
+
+
+def _read_dotenv_value(root: str, key: str) -> Optional[str]:
+ path = os.path.join(root, ".env")
+ if not os.path.isfile(path):
+ return None
+ try:
+ with open(path, encoding="utf-8") as handle:
+ for raw in handle:
+ line = raw.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ name, value = line.split("=", 1)
+ if name.strip() != key:
+ continue
+ return value.strip().strip('"').strip("'") or None
+ except OSError:
+ return None
+ return None
+
+
+def _project_identity(root: Optional[str] = None) -> Dict[str, Optional[str]]:
+ """Name / version / description for the `GET /` documentation page."""
+ cwd = root or os.getcwd()
+ name = os.environ.get("SERVER_NAME") or _read_dotenv_value(cwd, "SERVER_NAME")
+ description = os.environ.get("SERVER_DESC") or _read_dotenv_value(cwd, "SERVER_DESC")
+ version = None
+ path = os.path.join(cwd, "pyproject.toml")
+ if os.path.isfile(path):
+ try:
+ text = Path(path).read_text(encoding="utf-8")
+ except OSError:
+ text = ""
+ if not name:
+ match = re.search(r'(?m)^name\s*=\s*"([^"]+)"', text)
+ name = match.group(1) if match else None
+ if not description:
+ match = re.search(r'(?m)^description\s*=\s*"([^"]+)"', text)
+ description = match.group(1) if match else None
+ match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', text)
+ version = match.group(1) if match else None
+ if not name:
+ name = os.path.basename(os.path.abspath(cwd)) or None
+ return {"name": name, "version": version, "description": description}
+
+
+def _apply_project_identity(config: "ServerConfig") -> None:
+ ident = _project_identity()
+ generic = (config.name or "").strip().lower() in {"", "app", "mcp-server"}
+ if generic and ident.get("name"):
+ config.name = ident["name"]
+ if not config.description and ident.get("description"):
+ config.description = ident["description"]
+
+
+@dataclass
+class ServerConfig:
+ name: str
+ version: str = "1.0.0"
+ transport_type: Optional[Literal["stdio", "http", "dual"]] = None
+ protocol_version: str = MODERN_PROTOCOL_VERSION
+ # Era fallback when MCP_STATELESS and NITRO_MCP_PROTOCOL_VERSION are unset.
+ # Same tokens as the env var (modern/latest/2026/2026-07-28, auto/both/dual/
+ # dual-spec, legacy/2025/2025-06-18/2025-11-25). None means default era (`auto`).
+ protocol_era: Optional[str] = None
+ # Streamable HTTP options. Era resolution at `start()` / `get_combined_app()`:
+ # `MCP_STATELESS`, then `NITRO_MCP_PROTOCOL_VERSION`, then `protocol_era`,
+ # then `auto`. Also: `ENABLE_CORS`, `MCP_MAX_SESSIONS`,
+ # `MCP_SESSION_TIMEOUT_MS`, `MCP_TRANSPORT_TYPE`.
+ # `MCP_STATELESS` wins over the protocol-era mapping. Unset era is `auto`
+ # and does not force this flag; only `modern` sets stateless HTTP.
+ stateless: bool = False
+ max_sessions: Optional[int] = None
+ session_timeout_ms: Optional[int] = None
+ json_response: bool = False
+ json_body_limit: Optional[str | int] = None
+ extensions: Optional[Dict[str, str]] = None
+ # Subtitle on the `GET /` documentation page.
+ description: Optional[str] = None
+
+
+def mcp_app(
+ module: Type,
+ server: ServerConfig,
+ transforms: Optional[List[Any]] = None,
+):
+ """Declare an MCP application and its optional tool-list transforms."""
+
+ def decorator(cls: Type):
+ cls._mcp_app_module = module
+ cls._mcp_app_server = server
+ cls._mcp_transforms = list(transforms or [])
+ return cls
+
+ return decorator
diff --git a/nitrostack/core/app_context.py b/nitrostack/core/app_context.py
new file mode 100644
index 0000000..7728b50
--- /dev/null
+++ b/nitrostack/core/app_context.py
@@ -0,0 +1,211 @@
+"""Request context extraction and protocol envelope helpers."""
+
+import logging
+from typing import Any, Dict, List, Mapping, Type
+
+import mcp.types as types
+from mcp.server.lowlevel.helper_types import ReadResourceContents
+from pydantic import BaseModel
+
+from nitrostack.auth.request import (
+ auth_context_from_request,
+ bearer_token_from_envelope_auth,
+ envelope_auth_slot,
+)
+from nitrostack.core.context import ExecutionContext
+from nitrostack.protocol.meta import (
+ bind_request_envelope,
+ flatten_request_meta_object,
+)
+from nitrostack.protocol.observability import TraceContext, extract_trace_context
+from nitrostack.runtime.correlation import new_correlation_id
+from nitrostack.transports.headers import (
+ extract_mcp_param_headers,
+ extract_mcp_scope_headers,
+ merge_mcp_param_headers,
+)
+
+logger = logging.getLogger(__name__)
+
+
+_AUTH_META_KEYS = ("authorization", "x-api-key", "token", "_oauth", "headers")
+
+
+def _request_meta_from_ctx(rc: Any) -> Dict[str, Any]:
+ """Flatten MCP request ``_meta`` from the low-level request context."""
+ if rc is None:
+ return {}
+
+ raw_meta = getattr(rc, "meta", None)
+ if raw_meta is None:
+ return {}
+ data = flatten_request_meta_object(raw_meta)
+ if data:
+ return data
+ for key in _AUTH_META_KEYS:
+ value = getattr(raw_meta, key, None)
+ if value is not None:
+ data[key] = value
+ return data
+
+
+def _trace_context_from_request_ctx(rc: Any) -> TraceContext | None:
+ return extract_trace_context(_request_meta_from_ctx(rc))
+
+
+def _read_contents_to_result(
+ uri: str, items: List[ReadResourceContents]
+) -> types.ReadResourceResult:
+ import base64
+
+ contents: List[Any] = []
+ for item in items:
+ mime = item.mime_type or "text/plain"
+ extra = {"_meta": item.meta} if getattr(item, "meta", None) else {}
+ if isinstance(item.content, bytes):
+ contents.append(
+ types.BlobResourceContents(
+ uri=uri,
+ mimeType=mime,
+ blob=base64.b64encode(item.content).decode("ascii"),
+ **extra,
+ )
+ )
+ else:
+ contents.append(
+ types.TextResourceContents(uri=uri, mimeType=mime, text=str(item.content), **extra)
+ )
+ return types.ReadResourceResult(contents=contents, resultType="complete")
+
+
+def _http_headers_from_request_ctx(rc: Any) -> Dict[str, str]:
+ if rc is None:
+ return {}
+ request = getattr(rc, "request", None)
+ raw = getattr(request, "headers", None) if request is not None else None
+ if raw is None:
+ session = getattr(rc, "session", None)
+ transport = getattr(session, "transport", None) if session is not None else None
+ raw = getattr(transport, "headers", None) if transport is not None else None
+ if raw is None:
+ raw = getattr(rc, "headers", None)
+ if raw is None:
+ return {}
+ try:
+ return {str(key): str(value) for key, value in raw.items()}
+ except Exception:
+ return {}
+
+
+def _apply_request_envelope(ctx: ExecutionContext, rc: Any) -> None:
+ http_headers = _http_headers_from_request_ctx(rc)
+ envelope = bind_request_envelope(
+ raw_meta=_request_meta_from_ctx(rc),
+ mcp_headers=extract_mcp_scope_headers(http_headers),
+ )
+ ctx.rpc_meta = envelope.meta
+ ctx.mcp_headers = dict(envelope.mcp_headers)
+ ctx.mcp_param_headers = extract_mcp_param_headers(http_headers)
+ ctx.protocol_version = envelope.protocol_version
+ ctx.auth = auth_context_from_request(rc)
+ if ctx.trace is None:
+ ctx.trace = extract_trace_context(envelope.meta.raw)
+ if ctx.jsonrpc_id is None and rc is not None:
+ ctx.jsonrpc_id = getattr(rc, "request_id", None)
+ if rc is not None and getattr(rc, "correlation_id", None) is None:
+ try:
+ rc.correlation_id = ctx.correlation_id
+ except Exception:
+ pass
+
+
+def _bind_correlation(rc: Any) -> tuple[str, Any]:
+ """Allocate a correlation id. Never reuse the client JSON-RPC ``id`` as the key."""
+ jsonrpc_id = getattr(rc, "request_id", None) if rc is not None else None
+ existing = getattr(rc, "correlation_id", None) if rc is not None else None
+ if existing:
+ return str(existing), jsonrpc_id
+ correlation_id = new_correlation_id()
+ if rc is not None:
+ try:
+ rc.correlation_id = correlation_id
+ except Exception:
+ pass
+ return correlation_id, jsonrpc_id
+
+
+def _tool_arguments_with_mcp_params(
+ arguments: Dict[str, Any],
+ param_headers: Mapping[str, str],
+ input_model: Type[BaseModel],
+) -> Dict[str, Any]:
+ """Fill missing tool fields from ``Mcp-Param-*``. Does not rewrite ``name``."""
+ payload = dict(arguments or {})
+ inner = payload.get("input")
+ looks_wrapped = (
+ isinstance(inner, dict)
+ and set(payload.keys()) <= {"input"}
+ and "input" not in input_model.model_fields
+ )
+ allowed = set(input_model.model_fields)
+ if looks_wrapped:
+ return {"input": merge_mcp_param_headers(inner, param_headers, allowed_fields=allowed)}
+ return merge_mcp_param_headers(payload, param_headers, allowed_fields=allowed)
+
+
+def _auth_metadata_from_request_ctx(rc: Any) -> Dict[str, Any]:
+ """Copy host-sent auth slots from MCP request ``_meta`` into ExecutionContext.
+
+ Real transport headers (``rc.request.headers``) take precedence over
+ client-supplied ``_meta`` values: ``_meta`` is part of the JSON-RPC payload
+ and fully client-controlled, so it must not override credentials that were
+ presented (or vetted) at the transport layer. ``_meta`` remains the only
+ source on transports without HTTP headers (e.g. STDIO).
+ """
+ extra: Dict[str, Any] = {}
+ if rc is None:
+ return extra
+
+ data = _request_meta_from_ctx(rc)
+
+ auth = data.get("authorization") or data.get("Authorization")
+ if isinstance(auth, str) and auth.strip():
+ extra["authorization"] = auth
+ api_key = data.get("x-api-key")
+ if isinstance(api_key, str) and api_key.strip():
+ extra["x-api-key"] = api_key
+ token = data.get("token")
+ if isinstance(token, str) and token.strip():
+ extra["token"] = token
+ oauth = data.get("_oauth")
+ if isinstance(oauth, str) and oauth.strip():
+ extra["_oauth"] = oauth
+ headers = data.get("headers")
+ if isinstance(headers, dict):
+ extra["headers"] = headers
+ if "authorization" not in extra:
+ header_auth = headers.get("authorization") or headers.get("Authorization")
+ if isinstance(header_auth, str) and header_auth.strip():
+ extra["authorization"] = header_auth
+ if "x-api-key" not in extra:
+ header_key = headers.get("x-api-key") or headers.get("X-API-Key")
+ if isinstance(header_key, str) and header_key.strip():
+ extra["x-api-key"] = header_key
+
+ envelope_token = bearer_token_from_envelope_auth(envelope_auth_slot(data))
+ if envelope_token:
+ extra["authorization"] = f"Bearer {envelope_token}"
+
+ request = getattr(rc, "request", None)
+ headers_obj = getattr(request, "headers", None) if request is not None else None
+ if headers_obj is not None:
+ try:
+ http_auth = headers_obj.get("authorization") or headers_obj.get("Authorization")
+ if isinstance(http_auth, str) and http_auth.strip():
+ extra["authorization"] = http_auth
+ http_key = headers_obj.get("x-api-key") or headers_obj.get("X-API-Key")
+ if isinstance(http_key, str) and http_key.strip():
+ extra["x-api-key"] = http_key
+ except Exception:
+ pass
+ return extra
diff --git a/nitrostack/core/app_definitions.py b/nitrostack/core/app_definitions.py
new file mode 100644
index 0000000..c4b3a44
--- /dev/null
+++ b/nitrostack/core/app_definitions.py
@@ -0,0 +1,161 @@
+"""Definitions implementation mixin."""
+
+import copy
+import logging
+from typing import Any, Dict, Type
+
+import mcp.types as types
+from pydantic import BaseModel
+
+from nitrostack.core.app_entries import _PromptEntry, _ResourceEntry, _ToolEntry
+from nitrostack.core.app_mode import is_openai_mode
+from nitrostack.core.app_schema import inspector_friendly_schema, tool_json_schema
+from nitrostack.core.interceptors.data_spillover import (
+ SPILLOVER_SCHEMA,
+)
+from nitrostack.protocol.cache_hints import (
+ resolve_resource_cache_hint_meta,
+ resolve_tool_cache_hint_meta,
+)
+from nitrostack.protocol.schema import (
+ normalize_input_schema,
+)
+from nitrostack.widgets.mcp_meta import build_tool_list_meta
+
+logger = logging.getLogger(__name__)
+
+
+class DefinitionsMixin:
+ def _ensure_tool_entry_wire_cache(self, entry: _ToolEntry) -> None:
+ """Lazily cache list-wire fields so tools registered after bootstrap stay correct."""
+ if entry.input_json_schema is None:
+ entry.input_json_schema = self._tool_input_schema(entry.input_model)
+ if entry.has_spillover is None:
+ entry.has_spillover = self._has_spillover(entry.method)
+
+ def _tool_input_schema(self, input_model: Type[BaseModel]) -> Dict[str, Any]:
+ """JSON Schema for `tools/list` with fields at the top level.
+
+ MCP Inspector renders `inputSchema.properties` as form fields. Nesting
+ the model under `properties.input.$ref` only showed labels.
+ """
+ schema = inspector_friendly_schema(input_model.model_json_schema())
+ if not isinstance(schema, dict):
+ schema = {}
+ schema.setdefault("type", "object")
+ schema.setdefault("properties", {})
+ return normalize_input_schema(schema)
+
+ def _build_tool_definition(self, entry: _ToolEntry) -> types.Tool:
+ cfg = entry.config
+ self._ensure_tool_entry_wire_cache(entry)
+ input_schema = copy.deepcopy(entry.input_json_schema)
+
+ tasks_visible = self._tasks_visible_on_wire()
+ meta: Dict[str, Any] = {
+ "is_initial": cfg.is_initial,
+ "visibility": cfg.visibility,
+ **({"task_support": cfg.task_support} if tasks_visible else {}),
+ **(cfg.metadata or {}),
+ }
+
+ if entry.component is not None:
+ widget_meta = build_tool_list_meta(
+ entry.component,
+ cfg.visibility,
+ cfg.invocation,
+ )
+ meta.update(widget_meta)
+ elif cfg.invocation and is_openai_mode():
+ meta["openai/toolInvocation/invoking"] = cfg.invocation.invoking
+ meta["openai/toolInvocation/invoked"] = cfg.invocation.invoked
+
+ if cfg.examples:
+ meta["examples"] = {
+ "input": cfg.examples.input,
+ "output": cfg.examples.output,
+ "description": cfg.examples.description,
+ }
+
+ cache_meta = resolve_tool_cache_hint_meta(cfg, entry.method)
+ if cache_meta:
+ meta.update(cache_meta)
+
+ if is_openai_mode():
+ meta["openai/type"] = "function"
+ meta["openai/function"] = {
+ "name": cfg.name,
+ "description": cfg.description,
+ "parameters": input_schema,
+ }
+
+ annotations = types.ToolAnnotations(
+ readOnlyHint=cfg.annotations.read_only_hint,
+ destructiveHint=cfg.annotations.destructive_hint,
+ idempotentHint=cfg.annotations.idempotent_hint,
+ openWorldHint=cfg.annotations.open_world_hint,
+ )
+
+ execution = None
+ if tasks_visible and cfg.task_support and cfg.task_support != "forbidden":
+ execution = types.ToolExecution(taskSupport=cfg.task_support)
+
+ tool_kwargs: Dict[str, Any] = {
+ "name": cfg.name,
+ "title": cfg.title,
+ "description": cfg.description,
+ "inputSchema": input_schema,
+ "annotations": annotations,
+ "execution": execution,
+ "_meta": meta,
+ }
+ if entry.component is not None and is_openai_mode():
+ tool_kwargs["outputTemplate"] = entry.component.resource_uri
+
+ output_schema = tool_json_schema(cfg.output_schema)
+ if output_schema is not None:
+ if entry.has_spillover:
+ output_schema = {
+ "type": "object",
+ "anyOf": [output_schema, SPILLOVER_SCHEMA],
+ **({"$defs": output_schema["$defs"]} if "$defs" in output_schema else {}),
+ }
+ tool_kwargs["outputSchema"] = output_schema
+
+ return types.Tool(**tool_kwargs)
+
+ def _build_resource_definition(self, entry: _ResourceEntry) -> types.Resource:
+ cfg = entry.config
+ meta = dict(cfg.metadata or {})
+ cache_meta = resolve_resource_cache_hint_meta(cfg)
+ if cache_meta:
+ meta.update(cache_meta)
+ resource_kwargs: Dict[str, Any] = {
+ "uri": cfg.uri,
+ "name": cfg.name,
+ "title": cfg.title,
+ "description": cfg.description,
+ "mimeType": cfg.mime_type,
+ "size": cfg.size,
+ }
+ if meta:
+ resource_kwargs["_meta"] = meta
+ return types.Resource(**resource_kwargs)
+
+ def _build_resource_template_definition(self, entry: _ResourceEntry) -> types.ResourceTemplate:
+ cfg = entry.config
+ return types.ResourceTemplate(
+ uriTemplate=cfg.uri,
+ name=cfg.name,
+ title=cfg.title,
+ description=cfg.description,
+ mimeType=cfg.mime_type,
+ )
+
+ def _build_prompt_definition(self, entry: _PromptEntry) -> types.Prompt:
+ cfg = entry.config
+ arguments = [
+ types.PromptArgument(name=arg.name, description=arg.description, required=arg.required)
+ for arg in cfg.arguments
+ ]
+ return types.Prompt(name=cfg.name, description=cfg.description, arguments=arguments or None)
diff --git a/nitrostack/core/app_entries.py b/nitrostack/core/app_entries.py
new file mode 100644
index 0000000..9177e15
--- /dev/null
+++ b/nitrostack/core/app_entries.py
@@ -0,0 +1,40 @@
+"""Application registration entries shared by implementation modules."""
+
+import logging
+from dataclasses import dataclass, field
+from typing import Any, Callable, Dict, List, Optional, Pattern, Type
+
+from pydantic import BaseModel
+
+from nitrostack.core.decorators import PromptConfig, ResourceConfig, ToolConfig
+from nitrostack.widgets.component import Component
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class _ToolEntry:
+ config: ToolConfig
+ input_model: Type[BaseModel]
+ instance: Any
+ method: Callable
+ component: Optional[Component] = None
+ input_json_schema: Optional[Dict[str, Any]] = None
+ has_spillover: Optional[bool] = None
+
+
+@dataclass
+class _ResourceEntry:
+ config: ResourceConfig
+ instance: Any
+ method: Callable
+ param_names: List[str] = field(default_factory=list)
+ pattern: Optional[Pattern] = None
+ component: Optional[Component] = None
+
+
+@dataclass
+class _PromptEntry:
+ config: PromptConfig
+ instance: Any
+ method: Callable
diff --git a/nitrostack/core/app_invocation.py b/nitrostack/core/app_invocation.py
new file mode 100644
index 0000000..7585c31
--- /dev/null
+++ b/nitrostack/core/app_invocation.py
@@ -0,0 +1,386 @@
+"""Invocation implementation mixin."""
+
+import asyncio
+import logging
+from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
+
+import mcp.types as types
+from mcp import MCPError
+
+from nitrostack.core.app_context import (
+ _apply_request_envelope,
+ _auth_metadata_from_request_ctx,
+ _bind_correlation,
+ _http_headers_from_request_ctx,
+ _tool_arguments_with_mcp_params,
+ _trace_context_from_request_ctx,
+)
+from nitrostack.core.app_schema import parse_tool_input
+from nitrostack.core.context import ExecutionContext, TaskContext
+from nitrostack.core.di import DIContainer
+from nitrostack.core.errors import (
+ TaskAlreadyTerminalError,
+ TaskExpiredError,
+)
+from nitrostack.core.interceptors.data_spillover import (
+ DataSpilloverInterceptor,
+ bind_spillover_context,
+)
+from nitrostack.core.pipeline import run_pipeline
+from nitrostack.core.visibility import VisibilityTransform
+from nitrostack.protocol.meta import (
+ strip_tool_arguments,
+)
+from nitrostack.protocol.mrtr import InputRequiredResult, split_mrtr_from_arguments
+from nitrostack.protocol.tasks import (
+ DEFAULT_TASK_TTL_MS,
+ task_support_forbidden_message,
+ task_support_required_message,
+)
+from nitrostack.runtime.caller import caller_identity
+from nitrostack.runtime.request_ctx import request_ctx
+from nitrostack.tasks.authorization import extract_task_access_context
+from nitrostack.transforms import (
+ SyntheticTool,
+ ToolArgumentError,
+ TransformContext,
+ validate_tool_arguments,
+)
+from nitrostack.transports.headers import (
+ extract_mcp_param_headers,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class InvocationMixin:
+ def _has_spillover(self, method: Callable) -> bool:
+ container = DIContainer.get_instance()
+ return any(
+ isinstance(
+ container.resolve(item) if isinstance(item, type) else item,
+ DataSpilloverInterceptor,
+ )
+ for item in getattr(method, "_mcp_interceptors", [])
+ )
+
+ async def _bind_spillover(self, context: ExecutionContext, rc: Any) -> None:
+ if not self._spillover.routes:
+ return
+ # OAuth guards may verify opaque tokens as well as the shared JWT path.
+ from nitrostack.auth.oauth import OAuthService
+ from nitrostack.auth.request import (
+ auth_context_from_payload,
+ authorization_token_from_request,
+ )
+
+ token = authorization_token_from_request(rc)
+ container = DIContainer.get_instance()
+ if context.auth is None and token and container.has_value(OAuthService):
+ try:
+ payload = await container.resolve(OAuthService).introspect_token(token)
+ if payload.get("active"):
+ context.auth = auth_context_from_payload(payload)
+ except Exception:
+ pass # Invalid credentials remain denied by caller_owner.
+ bind_spillover_context(context, rc, self._spillover, self.protocol_era)
+
+ def _pipeline_stages(
+ self, method: Callable
+ ) -> Tuple[List[Any], List[Any], List[Any], List[Any], List[Any]]:
+ return (
+ getattr(method, "_mcp_guards", []),
+ getattr(method, "_mcp_middleware", []),
+ getattr(method, "_mcp_interceptors", []),
+ getattr(method, "_mcp_pipes", []),
+ getattr(method, "_mcp_filters", []),
+ )
+
+ def _base_lookup(self, name: str):
+ return self._tools.get(name)
+
+ async def _invoke_for_transform(self, name: str, arguments: dict, tctx: TransformContext):
+ # Re-enter the normal call path so guards and validation run for the real tool.
+ return await self._call_tool(name, arguments, _tctx=tctx)
+
+ def _visibility_session_key(self, request_context: Any) -> tuple[str, str] | None:
+ session_id, subject = caller_identity(request_context, self.protocol_era)
+ return VisibilityTransform.session_key(session_id, subject)
+
+ def _tool_visible(self, name: str, request_context: Any) -> bool:
+ entry = self._tools.get(name)
+ if entry is None:
+ # Transform-defined synthetic tools are not in the app registry.
+ # Let the transform resolver decide whether such names exist.
+ return True
+ return self.visibility_transform.is_visible(
+ entry, self._visibility_session_key(request_context)
+ )
+
+ def _configure_visibility_context(
+ self, context: ExecutionContext, request_context: Any
+ ) -> None:
+ key = self._visibility_session_key(request_context)
+ context._tool_visibility_controller = self.visibility_transform
+ context._visibility_session_key = key
+ context._visibility_app = self
+ context._visibility_supported = key is not None
+ context._visibility_change_callback = self._publish_tools_changed
+
+ @staticmethod
+ def _unknown_tool_result(name: str) -> types.CallToolResult:
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=f"Tool '{name}' not found")],
+ isError=True,
+ )
+
+ def _publish_tools_changed(self, context: ExecutionContext) -> None:
+ session = getattr(request_ctx.get(None), "session", None)
+ sender = getattr(session, "send_notification", None) if session is not None else None
+ if sender is None:
+ logger.debug("Transport does not support tools/list_changed notification")
+ return
+
+ async def send_notification() -> None:
+ try:
+ await sender(types.ToolListChangedNotification())
+ except Exception:
+ logger.debug(
+ "Unable to send session tools/list_changed notification", exc_info=True
+ )
+
+ try:
+ asyncio.create_task(send_notification())
+ except RuntimeError:
+ logger.debug("No running event loop for tools/list_changed notification")
+
+ async def _call_tool(
+ self,
+ name: str,
+ arguments: Dict[str, Any],
+ task: Any = None,
+ _tctx: Optional[TransformContext] = None,
+ ):
+ """Resolve through the transform pipeline, then run the real tool path."""
+ if not self._transforms.enabled:
+ return await self._call_real_tool(name, arguments, task=task)
+
+ tctx = _tctx or self._build_transform_context(
+ request_ctx.get(None), invoker=self._invoke_for_transform
+ )
+ try:
+ resolved = await self._transforms.resolve_tool(name, self._base_lookup, tctx)
+ except Exception as exc:
+ logger.exception("Transform failed resolving tool %s", name)
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=str(exc))], isError=True
+ )
+
+ if isinstance(resolved, SyntheticTool):
+ payload = arguments or {}
+ inner = payload.get("input")
+ if (
+ isinstance(inner, dict)
+ and set(payload) <= {"input"}
+ and "input" not in resolved.input_model.model_fields
+ ):
+ payload = inner # accept the older {"input": {...}} wrap
+ try:
+ validated = validate_tool_arguments(resolved.name, resolved.input_model, payload)
+ result = await resolved.handler(validated, tctx)
+ except ToolArgumentError as exc:
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=f"{exc}: {exc.errors}")],
+ isError=True,
+ )
+ except Exception as exc:
+ logger.exception("Synthetic tool %s failed", name)
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=str(exc))], isError=True
+ )
+ return self._to_call_tool_result(result)
+
+ return await self._call_real_tool(name, arguments, task=task)
+
+ async def _call_real_tool(self, name: str, arguments: Dict[str, Any], task: Any = None):
+ entry = self._tools.get(name)
+ if entry is None:
+ return self._unknown_tool_result(name)
+ if not self._tool_visible(name, request_ctx.get(None)):
+ return self._unknown_tool_result(name)
+
+ cfg = entry.config
+ tool_arguments, input_responses, request_state = split_mrtr_from_arguments(
+ strip_tool_arguments(arguments)
+ )
+ rc = request_ctx.get(None)
+ tool_arguments = _tool_arguments_with_mcp_params(
+ tool_arguments,
+ extract_mcp_param_headers(_http_headers_from_request_ctx(rc)),
+ entry.input_model,
+ )
+ # Pydantic validates after accepting either Inspector top-level fields
+ # or the older `{input: {...}}` wrap. Low-level jsonschema is off
+ # (`validate_input=False`) so the wrap is not rejected against the
+ # published top-level inputSchema.
+ input_instance = parse_tool_input(entry.input_model, tool_arguments)
+ guards, middleware, interceptors, pipes, filters = self._pipeline_stages(entry.method)
+
+ # Task metadata: explicit ``params.task``, then the 1.x experimental
+ # slot, then the official request context ``params`` mapping.
+ task_metadata = task
+ session = None
+ progress_token = None
+ if rc is not None:
+ if task_metadata is None and getattr(rc, "experimental", None) is not None:
+ task_metadata = rc.experimental.task_metadata
+ params = getattr(rc, "params", None)
+ if task_metadata is None:
+ task_metadata = getattr(params, "task", None)
+ if task_metadata is None and isinstance(params, Mapping):
+ task_metadata = params.get("task")
+ meta = getattr(rc, "meta", None)
+ if isinstance(meta, Mapping):
+ progress_token = meta.get("progress_token") or meta.get("progressToken")
+ elif meta is not None:
+ progress_token = getattr(meta, "progress_token", None) or getattr(
+ meta, "progressToken", None
+ )
+ session = getattr(rc, "session", None)
+ auth_meta = _auth_metadata_from_request_ctx(rc)
+ trace = _trace_context_from_request_ctx(rc)
+
+ is_task = task_metadata is not None
+ if self.protocol_era in ("auto", "modern") and is_task:
+ raise MCPError(
+ types.INVALID_PARAMS,
+ "Server does not support task augmentation on the MCP 2026 wire",
+ )
+ if cfg.task_support == "forbidden" and task_metadata is not None:
+ raise MCPError(
+ types.METHOD_NOT_FOUND,
+ task_support_forbidden_message(cfg.name),
+ )
+ if cfg.task_support == "required" and task_metadata is None:
+ raise MCPError(
+ types.INVALID_REQUEST,
+ task_support_required_message(cfg.name),
+ )
+
+ if is_task:
+ ttl_ms = (
+ task_metadata.ttl
+ if task_metadata and task_metadata.ttl is not None
+ else DEFAULT_TASK_TTL_MS
+ )
+ task_access = extract_task_access_context(rc, self.protocol_era)
+ task = await self.task_manager.create_task(
+ ttl_ms=ttl_ms,
+ tool_name=cfg.name,
+ owner_id=task_access.user_id if task_access else None,
+ tenant_id=task_access.tenant_id if task_access else None,
+ session_id=task_access.session_id if task_access else None,
+ )
+ task_id = task.id
+ correlation_id, jsonrpc_id = _bind_correlation(rc)
+
+ async def background_execution():
+ task_ctx = ExecutionContext(
+ request_id=correlation_id,
+ correlation_id=correlation_id,
+ jsonrpc_id=jsonrpc_id,
+ tool_name=cfg.name,
+ metadata={"input": input_instance, **auth_meta},
+ input_responses=input_responses,
+ request_state=request_state,
+ trace=trace,
+ )
+ _apply_request_envelope(task_ctx, rc)
+ self._configure_visibility_context(task_ctx, rc)
+ await self._bind_spillover(task_ctx, rc)
+ task_ctx.task = TaskContext(
+ task_id,
+ self.task_manager,
+ session=session,
+ progress_token=progress_token,
+ correlation_id=correlation_id,
+ )
+ try:
+ result = await run_pipeline(
+ handler=entry.method,
+ handler_instance=entry.instance,
+ args=(input_instance, task_ctx),
+ kwargs={},
+ context=task_ctx,
+ guards=guards,
+ middleware=middleware,
+ interceptors=interceptors,
+ pipes=pipes,
+ filters=filters,
+ param_name="input",
+ param_type=entry.input_model,
+ )
+ if isinstance(result, InputRequiredResult):
+ await self.task_manager.require_input(
+ task_id,
+ result.to_wire_dict(),
+ progress=result.message or "Additional input required",
+ )
+ else:
+ await self.task_manager.complete_task(
+ task_id, self._to_call_tool_result(result, entry.component, task_ctx)
+ )
+ except Exception as e:
+ try:
+ await self.task_manager.fail_task(task_id, e)
+ except (TaskAlreadyTerminalError, TaskExpiredError):
+ # Cancelled/expired while running — leave terminal state as-is.
+ pass
+
+ asyncio.create_task(background_execution())
+ return types.CreateTaskResult(task=self._task_data_to_mcp_task(task))
+
+ correlation_id, jsonrpc_id = _bind_correlation(rc)
+ ctx = ExecutionContext(
+ request_id=correlation_id,
+ correlation_id=correlation_id,
+ jsonrpc_id=jsonrpc_id,
+ tool_name=cfg.name,
+ metadata={"input": input_instance, **auth_meta},
+ input_responses=input_responses,
+ request_state=request_state,
+ trace=trace,
+ )
+ _apply_request_envelope(ctx, rc)
+ self._configure_visibility_context(ctx, rc)
+ await self._bind_spillover(ctx, rc)
+ ticket = self._in_flight.register(correlation_id, jsonrpc_id=jsonrpc_id)
+ try:
+ result = await run_pipeline(
+ handler=entry.method,
+ handler_instance=entry.instance,
+ args=(input_instance, ctx),
+ kwargs={},
+ context=ctx,
+ guards=guards,
+ middleware=middleware,
+ interceptors=interceptors,
+ pipes=pipes,
+ filters=filters,
+ param_name="input",
+ param_type=entry.input_model,
+ )
+ except Exception as exc:
+ logger.exception("Tool %s failed", cfg.name)
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=str(exc))],
+ isError=True,
+ )
+ finally:
+ self._in_flight.discard(correlation_id)
+ if ticket.cancel_requested.is_set():
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text="Request was cancelled.")],
+ isError=True,
+ )
+ return self._to_call_tool_result(result, entry.component, ctx)
diff --git a/nitrostack/core/app_mode.py b/nitrostack/core/app_mode.py
index cadb517..e53e7ce 100644
--- a/nitrostack/core/app_mode.py
+++ b/nitrostack/core/app_mode.py
@@ -13,12 +13,18 @@
def get_app_mode() -> AppMode:
- """Parse ``NITROSTACK_APP_MODE`` with lenient aliases.
+ """Parse ``NITROSTACK_APP_MODE`` / ``APP_MODE`` with lenient aliases.
- Default is ``universal`` so MCP Inspector (Apps tab) and ChatGPT both receive
- widget MIME + ``_meta.ui.resourceUri`` without extra env setup.
+ Default is ``openai``. ``NITROSTACK_APP_MODE`` wins when both are set.
"""
- raw = (os.environ.get("NITROSTACK_APP_MODE") or "universal").lower().strip()
+ raw = os.environ.get("NITROSTACK_APP_MODE") or os.environ.get("APP_MODE")
+ if raw is None:
+ return "openai"
+ raw = raw.lower().strip()
+ if not raw:
+ return "openai"
+ if raw in ("openai", "chatgpt"):
+ return "openai"
if raw in ("mcp-app", "mcpapp", "mcp_app", "mcp app", "mcp", "mcpapps"):
return "mcp-app"
if raw in ("universal", "all", "both"):
@@ -38,4 +44,4 @@ def is_openai_mode() -> bool:
def get_widget_mime_type() -> str:
"""MIME for ``resources/read`` widget HTML (never skybridge)."""
- return RESOURCE_MIME_TYPE_MCP_APP if is_mcp_app_mode() else RESOURCE_MIME_TYPE_OPENAI
+ return RESOURCE_MIME_TYPE_MCP_APP if is_mcp_app_mode() else RESOURCE_MIME_TYPE_OPENAI
\ No newline at end of file
diff --git a/nitrostack/core/app_protocol.py b/nitrostack/core/app_protocol.py
new file mode 100644
index 0000000..ba7fcc2
--- /dev/null
+++ b/nitrostack/core/app_protocol.py
@@ -0,0 +1,355 @@
+"""Protocol protocol handlers implementation mixin."""
+
+import logging
+from typing import Any, Dict, Optional
+
+import mcp.types as types
+from mcp import MCPError
+from mcp.server.context import ServerRequestContext
+from mcp.types import (
+ CallToolRequestParams,
+ GetPromptRequestParams,
+ PaginatedRequestParams,
+ ReadResourceRequestParams,
+ RequestParams,
+ SubscribeRequestParams,
+ UnsubscribeRequestParams,
+)
+
+from nitrostack.core.app_context import (
+ _apply_request_envelope,
+ _auth_metadata_from_request_ctx,
+ _bind_correlation,
+ _read_contents_to_result,
+ _trace_context_from_request_ctx,
+)
+from nitrostack.core.context import ExecutionContext
+from nitrostack.core.errors import (
+ ResourceNotFoundError,
+)
+from nitrostack.core.mcp_server import NitroStackMcpServer
+from nitrostack.core.visibility import VisibilityTransform
+from nitrostack.protocol.cache_hints import (
+ build_list_endpoint_cache_hint_meta,
+)
+from nitrostack.protocol.deprecated import (
+ deprecated_method_message,
+)
+from nitrostack.protocol.version import (
+ protocol_version_for_era,
+ rejects_legacy_initialize,
+ supports_resource_subscriptions,
+)
+from nitrostack.runtime.caller import caller_identity
+from nitrostack.runtime.request_ctx import ServerResult, request_ctx
+from nitrostack.transforms import (
+ TransformContext,
+ TransformError,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class ProtocolHandlersMixin:
+ def _tasks_visible_on_wire(self) -> bool:
+ # Tasks remain available to in-process callers and the legacy wire only.
+ # MCP 2026 has no complete tasks surface (notably tasks/update), so
+ # nothing on the 2026 wire may advertise this partial implementation.
+ return self.protocol_era not in ("auto", "modern")
+
+ def _advertise_tasks_extension(self) -> bool:
+ # Legacy task handlers do not implement the complete 2026 extension.
+ # Advertising it is deferred to the dedicated tasks issue.
+ return False
+
+ def _custom_extensions(self) -> Optional[Dict[str, str]]:
+ extensions = getattr(self.server_config, "extensions", None)
+ if not extensions:
+ return None
+ return dict(extensions)
+
+ def handle_server_discover(self, protocol_version: Optional[str] = None) -> Dict[str, Any]:
+ """Single ``server/discover`` result for the mounted HTTP engine."""
+ from nitrostack.protocol.discovery import build_discover_result
+
+ has_widgets = any(
+ getattr(entry, "component", None) is not None
+ for entry in getattr(self, "_tools", {}).values()
+ )
+ version = protocol_version or protocol_version_for_era(
+ getattr(self, "protocol_era", None),
+ self.server_config.protocol_version,
+ )
+ # Same source of truth as `NitroStackMcpServer.get_capabilities`, so
+ # `server/discover` and real capability negotiation never disagree.
+ resources_subscribe = supports_resource_subscriptions(self.protocol_era)
+ result = build_discover_result(
+ server_name=self.server_config.name,
+ server_version=self.server_config.version,
+ protocol_version=version,
+ resources_subscribe=resources_subscribe,
+ advertise_tasks=self._advertise_tasks_extension(),
+ advertise_app=has_widgets,
+ custom_extensions=self._custom_extensions(),
+ )
+ meta = dict(result.get("_meta") or {})
+ meta["io.modelcontextprotocol/serverInfo"] = {
+ "name": self.server_config.name,
+ "version": self.server_config.version,
+ }
+ result["_meta"] = meta
+ result.setdefault("resultType", "complete")
+ return result
+
+ def _list_endpoint_cache_meta(self) -> Dict[str, Any]:
+ return build_list_endpoint_cache_hint_meta()
+
+ def _setup_handlers(self, server: NitroStackMcpServer) -> None:
+ server.protocol_era = self.protocol_era
+
+ async def _list_tools(
+ ctx: ServerRequestContext,
+ _params: Optional[PaginatedRequestParams],
+ ):
+ session_key = self._visibility_session_key(ctx)
+ tools = [
+ self._build_tool_definition(entry)
+ for entry in self._tools.values()
+ if self.visibility_transform.is_visible(entry, session_key)
+ ]
+
+ if self._transforms.enabled:
+ try:
+ context = self._build_transform_context(request_ctx.get(None), invoker=None)
+ tools = await self._transforms.transform_tools(
+ tools,
+ context,
+ )
+ except TransformError as exc:
+ raise MCPError(
+ types.INTERNAL_ERROR,
+ str(exc),
+ ) from exc
+
+ return types.ListToolsResult(
+ tools=tools,
+ _meta=self._list_endpoint_cache_meta(),
+ resultType="complete",
+ )
+
+ async def _ping(_ctx: ServerRequestContext, _params: Optional[RequestParams]):
+ if self.protocol_era == "legacy":
+ return types.EmptyResult()
+ raise MCPError(types.METHOD_NOT_FOUND, "ping was removed in MCP 2026-07-28")
+
+ async def _call_tool(ctx: ServerRequestContext, params: CallToolRequestParams):
+ token = request_ctx.set(ctx)
+ try:
+ if not self._tool_visible(params.name, ctx):
+ return self._unknown_tool_result(params.name)
+ result = await self._call_tool(
+ params.name, params.arguments or {}, task=params.task
+ )
+ if isinstance(result, types.CreateTaskResult):
+ task = result.task
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=task.task_id)],
+ structuredContent={
+ "resultType": "task",
+ "task": task.model_dump(by_alias=True),
+ },
+ isError=False,
+ )
+ return result.model_copy(update={"result_type": result.result_type or "complete"})
+ finally:
+ request_ctx.reset(token)
+
+ async def _list_resources(
+ _ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]
+ ):
+ return types.ListResourcesResult(
+ resources=[
+ self._build_resource_definition(entry) for entry in self._resources.values()
+ ],
+ _meta=self._list_endpoint_cache_meta(),
+ resultType="complete",
+ )
+
+ async def _list_resource_templates(
+ _ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]
+ ):
+ return types.ListResourceTemplatesResult(
+ resource_templates=[
+ self._build_resource_template_definition(entry)
+ for entry in self._resource_templates
+ ],
+ resultType="complete",
+ )
+
+ async def _read_resource(ctx: ServerRequestContext, params: ReadResourceRequestParams):
+ uri = str(params.uri)
+ return _read_contents_to_result(uri, await self._read_resource(uri))
+
+ async def _subscribe_resource(_ctx: ServerRequestContext, params: SubscribeRequestParams):
+ if not supports_resource_subscriptions(self.protocol_era):
+ message = deprecated_method_message("resources/subscribe")
+ raise MCPError(types.METHOD_NOT_FOUND, message or "Not supported")
+ if str(params.uri) not in self._resources:
+ raise ResourceNotFoundError(str(params.uri))
+ return types.EmptyResult()
+
+ async def _unsubscribe_resource(
+ _ctx: ServerRequestContext, _params: UnsubscribeRequestParams
+ ):
+ if not supports_resource_subscriptions(self.protocol_era):
+ raise MCPError(
+ types.METHOD_NOT_FOUND, "Resource subscriptions are not supported in this era"
+ )
+ return types.EmptyResult()
+
+ async def _list_prompts(
+ _ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]
+ ):
+ return types.ListPromptsResult(
+ prompts=[self._build_prompt_definition(entry) for entry in self._prompts.values()],
+ _meta=self._list_endpoint_cache_meta(),
+ resultType="complete",
+ )
+
+ async def _get_prompt(ctx: ServerRequestContext, params: GetPromptRequestParams):
+ arguments = params.arguments or {}
+ result = await self._get_prompt(
+ params.name,
+ {str(key): str(value) for key, value in arguments.items()},
+ )
+ return result.model_copy(update={"result_type": result.result_type or "complete"})
+
+ server.add_request_handler("ping", RequestParams, _ping)
+
+ async def _discover(ctx: ServerRequestContext, _params: Optional[RequestParams]):
+ return self.handle_server_discover(getattr(ctx, "protocol_version", None))
+
+ server.add_request_handler("server/discover", RequestParams, _discover)
+ server.add_request_handler("tools/list", PaginatedRequestParams, _list_tools)
+ server.add_request_handler("tools/call", CallToolRequestParams, _call_tool)
+ server.add_request_handler("resources/list", PaginatedRequestParams, _list_resources)
+ server.add_request_handler(
+ "resources/templates/list", PaginatedRequestParams, _list_resource_templates
+ )
+ server.add_request_handler("resources/read", ReadResourceRequestParams, _read_resource)
+ server.add_request_handler(
+ "resources/subscribe", SubscribeRequestParams, _subscribe_resource
+ )
+ server.add_request_handler(
+ "resources/unsubscribe", UnsubscribeRequestParams, _unsubscribe_resource
+ )
+ server.add_request_handler("prompts/list", PaginatedRequestParams, _list_prompts)
+ server.add_request_handler("prompts/get", GetPromptRequestParams, _get_prompt)
+
+ async def handle_list_tools(req=None):
+ ctx = req if req is not None and hasattr(req, "session") else request_ctx.get(None)
+ return ServerResult(await _list_tools(ctx, None))
+
+ async def handle_call_tool(req=None):
+ params = getattr(req, "params", None) if req is not None else None
+ name = getattr(params, "name", "") if params is not None else ""
+ arguments = (getattr(params, "arguments", None) or {}) if params is not None else {}
+ task = getattr(params, "task", None) if params is not None else None
+ ctx = req if req is not None and hasattr(req, "session") else request_ctx.get(None)
+ if not self._tool_visible(name, ctx):
+ return ServerResult(self._unknown_tool_result(name))
+ token = request_ctx.set(ctx)
+ try:
+ return ServerResult(await self._call_tool(name, arguments, task=task))
+ finally:
+ request_ctx.reset(token)
+
+ async def handle_list_resources(req=None):
+ return ServerResult(await _list_resources(None, None))
+
+ async def handle_list_resource_templates(req=None):
+ return ServerResult(await _list_resource_templates(None, None))
+
+ async def handle_read_resource(req):
+ params = getattr(req, "params", req)
+ uri = str(params.uri)
+ return ServerResult(_read_contents_to_result(uri, await self._read_resource(uri)))
+
+ async def handle_list_prompts(req=None):
+ return ServerResult(await _list_prompts(None, None))
+
+ async def handle_get_prompt(req):
+ params = getattr(req, "params", req)
+ arguments = getattr(params, "arguments", None) or {}
+ return ServerResult(
+ await self._get_prompt(
+ params.name,
+ {str(key): str(value) for key, value in arguments.items()},
+ )
+ )
+
+ server.request_handlers[types.ListToolsRequest] = handle_list_tools
+ server.request_handlers[types.CallToolRequest] = handle_call_tool
+ server.request_handlers[types.ListResourcesRequest] = handle_list_resources
+ server.request_handlers[types.ListResourceTemplatesRequest] = handle_list_resource_templates
+ server.request_handlers[types.ReadResourceRequest] = handle_read_resource
+ server.request_handlers[types.ListPromptsRequest] = handle_list_prompts
+ server.request_handlers[types.GetPromptRequest] = handle_get_prompt
+
+ self._register_task_handlers(server)
+ self._register_initialized_handler(server)
+ server.middleware.insert(1, self._request_scope_middleware)
+
+ def _build_transform_context(self, rc: Any, *, invoker: Any) -> TransformContext:
+ """TransformContext for the in-flight request, identity from ``caller_identity``."""
+ session_id, subject = caller_identity(rc, self.protocol_era)
+ session_key = VisibilityTransform.session_key(session_id, subject)
+ exec_ctx = None
+ if rc is not None:
+ correlation_id, jsonrpc_id = _bind_correlation(rc)
+ exec_ctx = ExecutionContext(
+ request_id=correlation_id,
+ correlation_id=correlation_id,
+ jsonrpc_id=jsonrpc_id,
+ metadata=dict(_auth_metadata_from_request_ctx(rc)),
+ trace=_trace_context_from_request_ctx(rc),
+ )
+ _apply_request_envelope(exec_ctx, rc)
+ self._configure_visibility_context(exec_ctx, rc)
+ visible_tools = [
+ self._build_tool_definition(entry)
+ for entry in self._tools.values()
+ if self.visibility_transform.is_visible(entry, session_key)
+ ]
+ return TransformContext(
+ session_id=session_id,
+ subject=subject,
+ execution_context=exec_ctx,
+ visible_tools=visible_tools,
+ _invoker=invoker,
+ )
+
+ async def _request_scope_middleware(self, ctx: ServerRequestContext, call_next):
+ """Bind ``request_ctx`` once for every handler and gate the 2025 handshake."""
+ if ctx.method == "initialize" and rejects_legacy_initialize(self.protocol_era):
+ raise MCPError(types.METHOD_NOT_FOUND, "Method not found: initialize")
+ token = request_ctx.set(ctx)
+ try:
+ return await call_next(ctx)
+ finally:
+ request_ctx.reset(token)
+
+ def create_configured_mcp_server(self) -> NitroStackMcpServer:
+ """
+ Build a fresh, fully-wired low-level server instance sharing this
+ application's tool/resource/prompt registries. A single shared server is
+ sufficient for the Python `mcp` SDK's HTTP session managers (unlike the TS
+ SDK's `Server`, `.run()` here does not bind a transport for the instance's
+ lifetime), but this factory is kept available for isolated/stateless use
+ cases (e.g. Phase 3 extensions) that want their own server instance.
+ """
+ server = NitroStackMcpServer(
+ name=self.server_config.name, version=self.server_config.version
+ )
+ self._setup_handlers(server)
+ return server
diff --git a/nitrostack/core/app_registration.py b/nitrostack/core/app_registration.py
new file mode 100644
index 0000000..6f6c0cf
--- /dev/null
+++ b/nitrostack/core/app_registration.py
@@ -0,0 +1,367 @@
+"""Registration implementation mixin."""
+
+import datetime
+import inspect
+import json
+import logging
+import time
+from pathlib import Path
+from typing import Any, Callable, List, Sequence, Set, Type
+from unittest.mock import NonCallableMock
+
+import mcp.types as types
+
+from nitrostack.core.additional_decorators import HealthCheckRegistry, ServerHealthPayload
+from nitrostack.core.app_entries import _PromptEntry, _ResourceEntry, _ToolEntry
+from nitrostack.core.app_mode import get_widget_mime_type
+from nitrostack.core.app_schema import get_pydantic_model
+from nitrostack.core.context import ExecutionContext
+from nitrostack.core.decorators import PromptConfig, ResourceConfig, ToolConfig, widget_resource_uri
+from nitrostack.core.di import DIContainer
+from nitrostack.core.errors import (
+ DependencyResolutionError,
+)
+from nitrostack.core.interceptors.data_spillover import (
+ DataSpilloverInterceptor,
+)
+from nitrostack.core.mcp_server import NitroStackMcpServer
+from nitrostack.events.event_emitter import EventEmitter
+from nitrostack.protocol.resources import extract_template_param_names, uri_template_to_pattern
+from nitrostack.protocol.schema import (
+ gate_registered_schema,
+)
+from nitrostack.widgets.component import (
+ Component,
+ find_project_root,
+ load_widget_html,
+ parse_widget_options,
+)
+from nitrostack.widgets.registry import WIDGET_EXAMPLES_URI, WidgetRegistry
+from nitrostack.widgets.route_templates import build_missing_widget
+
+logger = logging.getLogger(__name__)
+
+
+class RegistrationMixin:
+ def _base_tool_list(self) -> List[types.Tool]:
+ return [self._build_tool_definition(entry) for entry in self._tools.values()]
+
+ def _bootstrap(self) -> None:
+ # 1. Construct the low-level server directly.
+ self.mcp_server = NitroStackMcpServer(
+ name=self.server_config.name,
+ version=self.server_config.version,
+ )
+
+ # 2. Resolve Module Tree recursively and register services
+ resolved_modules: List[Type] = []
+ resolved_seen: Set[Type] = set()
+ self._resolve_modules(self.root_module, resolved_modules, resolved_seen)
+
+ container = DIContainer.get_instance()
+ self._assert_declared_dependencies(resolved_modules, container)
+
+ # Instantiate all providers and controllers to populate container.
+ # Scan both: providers with @tool/@resource/@prompt must stay discoverable.
+ module_instances: List[Any] = []
+ seen_instance_ids: Set[int] = set()
+ for mod in resolved_modules:
+ mod_config = getattr(mod, "_mcp_module_config", None)
+ if mod_config:
+ for provider in mod_config.providers:
+ instance = container.resolve(provider)
+ if id(instance) not in seen_instance_ids:
+ seen_instance_ids.add(id(instance))
+ module_instances.append(instance)
+ for controller in mod_config.controllers:
+ instance = container.resolve(controller)
+ if id(instance) not in seen_instance_ids:
+ seen_instance_ids.add(id(instance))
+ module_instances.append(instance)
+
+ # 3. Discover decorated methods on resolved module providers and controllers
+ for instance in module_instances:
+ # Scan members of this instance
+ for _name, member in inspect.getmembers(instance):
+ # A test mock answers hasattr() for everything, so it would look like a tool.
+ if isinstance(member, NonCallableMock):
+ continue
+ # Discover Tools
+ if hasattr(member, "_mcp_tool_config"):
+ tool_config: ToolConfig = member._mcp_tool_config
+ self._register_tool(instance, member, tool_config)
+
+ # Discover Resources
+ if hasattr(member, "_mcp_resource_config"):
+ resource_config: ResourceConfig = member._mcp_resource_config
+ self._register_resource(instance, member, resource_config)
+
+ # Discover Prompts
+ if hasattr(member, "_mcp_prompt_config"):
+ prompt_config: PromptConfig = member._mcp_prompt_config
+ self._register_prompt(instance, member, prompt_config)
+
+ # Bind Health Checks
+ if hasattr(member, "_mcp_health_check_name"):
+ check_name = member._mcp_health_check_name
+ HealthCheckRegistry.bind_instance(
+ check_name,
+ member,
+ instance,
+ timeout=float(getattr(member, "_mcp_health_check_timeout", 5.0)),
+ )
+
+ # Bind Event Listeners
+ if hasattr(member, "_mcp_event_name"):
+ event_name = member._mcp_event_name
+ EventEmitter.get_instance().bind_instance(event_name, member, instance)
+
+ self.widget_registry: WidgetRegistry = WidgetRegistry._from_tools(self._tools.values())
+ if self.widget_registry.get_all_widgets():
+ self._register_widget_examples_resource()
+
+ # 4. Register Built-in Health check Resource if any checks exist
+ if HealthCheckRegistry.get_checks():
+ self._register_health_resource()
+
+ # 5. Wire every protocol handler (tools/resources/prompts/tasks/notifications)
+ # onto the owned low-level server. This is factored out so additional server
+ # instances (e.g. one per HTTP session) can be configured identically.
+ for entry in self._tools.values():
+ self._wire_spillover_for_entry(entry)
+ self._setup_handlers(self.mcp_server)
+
+ def _wire_spillover_for_entry(self, entry: _ToolEntry) -> None:
+ container = DIContainer.get_instance()
+ for candidate in getattr(entry.method, "_mcp_interceptors", []):
+ interceptor = (
+ container.resolve(candidate) if isinstance(candidate, type) else candidate
+ )
+ if isinstance(interceptor, DataSpilloverInterceptor):
+ self._spillover.register(interceptor)
+
+ def _assert_declared_dependencies(
+ self, resolved_modules: Sequence[Type], container: DIContainer
+ ) -> None:
+ """Fail at bootstrap when a string ``deps=[...]`` token was never registered."""
+ missing: List[str] = []
+ seen: Set[Type] = set()
+
+ def walk(cls: Any) -> None:
+ if not isinstance(cls, type) or cls in seen:
+ return
+ seen.add(cls)
+ for dep in getattr(cls, "_mcp_deps", []) or []:
+ if isinstance(dep, str):
+ if not container.has_value(dep) and dep not in container._registry:
+ missing.append(f"{cls.__name__} -> '{dep}'")
+ elif isinstance(dep, type):
+ walk(dep)
+
+ for mod in resolved_modules:
+ mod_config = getattr(mod, "_mcp_module_config", None)
+ if not mod_config:
+ continue
+ for cls in [*mod_config.providers, *mod_config.controllers]:
+ walk(cls)
+
+ if missing:
+ raise DependencyResolutionError(
+ "Missing dependency at app bootstrap (referenced in deps=[...] "
+ "but never registered): " + "; ".join(missing)
+ )
+
+ def _resolve_modules(
+ self,
+ module_class: Type,
+ resolved_modules: List[Type],
+ resolved_seen: Set[Type],
+ ) -> None:
+ if module_class in resolved_seen:
+ return
+ resolved_seen.add(module_class)
+ resolved_modules.append(module_class)
+
+ mod_config = getattr(module_class, "_mcp_module_config", None)
+ if mod_config:
+ for imp in mod_config.imports:
+ self._resolve_modules(imp, resolved_modules, resolved_seen)
+
+ def _register_tool(self, instance: Any, method: Callable, tool_config: ToolConfig) -> None:
+ gate_registered_schema(tool_config.input_schema, name=f"tool {tool_config.name!r} input")
+ gate_registered_schema(tool_config.output_schema, name=f"tool {tool_config.name!r} output")
+ input_model = get_pydantic_model(tool_config.input_schema)
+ entry = _ToolEntry(
+ config=tool_config, input_model=input_model, instance=instance, method=method
+ )
+
+ widget_spec = getattr(method, "_mcp_widget", None)
+ if widget_spec is not None:
+ options = parse_widget_options(widget_spec)
+ resource_uri = widget_resource_uri(options.route)
+ route_id = resource_uri.removeprefix("ui://widget/").removesuffix(".html")
+ from_file = None
+ method_module = inspect.getmodule(method)
+ if method_module and getattr(method_module, "__file__", None):
+ from_file = Path(method_module.__file__).resolve()
+ project_root = find_project_root(from_file)
+ html = load_widget_html(
+ route_id,
+ html=options.html,
+ from_file=from_file,
+ project_root=project_root,
+ )
+ if not html:
+ html = build_missing_widget(route_id)
+ component = Component(
+ id=route_id,
+ name=tool_config.title or tool_config.name,
+ html=html,
+ description=options.description or tool_config.description,
+ css=options.css,
+ js=options.js,
+ csp=options.csp,
+ domain=options.domain,
+ prefers_border=options.prefers_border,
+ can_invoke_tools=options.can_invoke_tools,
+ )
+ entry.component = component
+ self._register_widget_resource(component)
+
+ self._tools[tool_config.name] = entry
+ if tool_config.is_initial:
+ self._initial_tools.append((instance, method, tool_config))
+ if self.mcp_server is not None:
+ self._wire_spillover_for_entry(entry)
+
+ def _register_widget_resource(self, component: Component) -> None:
+ config = ResourceConfig(
+ uri=component.resource_uri,
+ name=component.name,
+ description=component.description or f"UI widget for {component.name}",
+ mime_type=get_widget_mime_type(),
+ )
+
+ async def widget_resource_handler(context: ExecutionContext) -> str:
+ return component.get_bundle()
+
+ self._resources[config.uri] = _ResourceEntry(
+ config=config,
+ instance=None,
+ method=widget_resource_handler,
+ component=component,
+ )
+
+ def _register_widget_examples_resource(self) -> None:
+ if WIDGET_EXAMPLES_URI in self._resources:
+ raise ValueError(
+ f"Resource URI {WIDGET_EXAMPLES_URI!r} is reserved for the widget manifest"
+ )
+
+ async def widget_examples(context: ExecutionContext) -> dict:
+ return self.widget_registry.get_manifest().to_dict()
+
+ self._resources[WIDGET_EXAMPLES_URI] = _ResourceEntry(
+ config=ResourceConfig(
+ uri=WIDGET_EXAMPLES_URI,
+ name="Widget Examples",
+ description="Provides metadata and examples for all registered UI widgets",
+ mime_type="application/json",
+ ),
+ instance=None,
+ method=widget_examples,
+ )
+
+ def _register_resource(
+ self, instance: Any, method: Callable, resource_config: ResourceConfig
+ ) -> None:
+ gate_registered_schema(
+ getattr(resource_config, "schema", None)
+ or (resource_config.metadata or {}).get("schema"),
+ name=f"resource {resource_config.uri!r}",
+ )
+ param_names = extract_template_param_names(resource_config.uri)
+ entry = _ResourceEntry(
+ config=resource_config, instance=instance, method=method, param_names=param_names
+ )
+
+ if param_names:
+ entry.pattern = uri_template_to_pattern(resource_config.uri)
+ self._resource_templates.append(entry)
+ else:
+ self._resources[resource_config.uri] = entry
+
+ def _register_prompt(
+ self, instance: Any, method: Callable, prompt_config: PromptConfig
+ ) -> None:
+ for argument in prompt_config.arguments or []:
+ gate_registered_schema(
+ getattr(argument, "schema", None),
+ name=f"prompt {prompt_config.name!r} argument {argument.name!r}",
+ )
+ self._prompts[prompt_config.name] = _PromptEntry(
+ config=prompt_config, instance=instance, method=method
+ )
+
+ def _register_health_resource(self) -> None:
+ status_config = ResourceConfig(
+ uri="health://status",
+ name="Health Status",
+ description="System health status check",
+ mime_type="application/json",
+ )
+ checks_config = ResourceConfig(
+ uri="health://checks",
+ name="Health Checks & Pipeline Telemetry",
+ description="Current health status and transform pipeline telemetry",
+ mime_type="application/json",
+ )
+
+ async def health_status_resource(context: ExecutionContext) -> str:
+ # Keep the original string map at health://status for existing clients.
+ results = await HealthCheckRegistry.run_all()
+ return json.dumps(results)
+
+ async def health_checks_resource(context: ExecutionContext) -> ServerHealthPayload:
+ checks = await HealthCheckRegistry.run_detailed()
+ has_failures = any(check["status"] in {"error", "timeout"} for check in checks)
+ has_unhealthy = any(check["status"] == "unhealthy" for check in checks)
+ transforms = []
+ configured_transforms = getattr(self.app_class, "_mcp_transforms", None) or []
+ for order, transform in enumerate(configured_transforms):
+ transforms.append(
+ {
+ "name": getattr(transform, "name", transform.__class__.__name__),
+ "type": transform.__class__.__name__,
+ "order": order,
+ "details": {},
+ }
+ )
+ public_checks = [
+ {
+ **check,
+ "message": "Check failed" if check["status"] == "error" else check["message"],
+ }
+ for check in checks
+ ]
+ payload: ServerHealthPayload = {
+ "status": (
+ "unhealthy" if has_failures else "degraded" if has_unhealthy else "healthy"
+ ),
+ "uptimeSeconds": int(time.monotonic() - self._started_at),
+ "checks": public_checks,
+ "count": len(public_checks),
+ "transforms": transforms,
+ "timestamp": datetime.datetime.now(datetime.timezone.utc)
+ .isoformat()
+ .replace("+00:00", "Z"),
+ "sdkVersion": self._sdk_version,
+ }
+ return payload
+
+ self._resources[status_config.uri] = _ResourceEntry(
+ config=status_config, instance=None, method=health_status_resource
+ )
+ self._resources[checks_config.uri] = _ResourceEntry(
+ config=checks_config, instance=None, method=health_checks_resource
+ )
diff --git a/nitrostack/core/app_resources.py b/nitrostack/core/app_resources.py
new file mode 100644
index 0000000..161a8ee
--- /dev/null
+++ b/nitrostack/core/app_resources.py
@@ -0,0 +1,156 @@
+"""Resources implementation mixin."""
+
+import json
+import logging
+import uuid
+from typing import Dict, List
+
+import mcp.types as types
+from mcp.server.lowlevel.helper_types import ReadResourceContents
+from pydantic import BaseModel
+
+from nitrostack.core.app_context import _apply_request_envelope, _http_headers_from_request_ctx
+from nitrostack.core.app_mode import get_widget_mime_type
+from nitrostack.core.context import ExecutionContext
+from nitrostack.core.errors import (
+ PromptNotFoundError,
+ ResourceNotFoundError,
+)
+from nitrostack.core.interceptors.data_spillover import (
+ caller_owner,
+)
+from nitrostack.core.pipeline import run_pipeline
+from nitrostack.runtime.request_ctx import request_ctx
+from nitrostack.transports.headers import (
+ extract_mcp_param_headers,
+ merge_mcp_param_headers,
+)
+from nitrostack.widgets.mcp_meta import resource_read_contents_meta
+
+logger = logging.getLogger(__name__)
+
+
+class ResourcesMixin:
+ async def _read_resource(self, uri: str) -> List[ReadResourceContents]:
+ for prefix, store in self._spillover.routes.items():
+ if uri.startswith(prefix):
+ ctx = ExecutionContext(request_id=str(uuid.uuid4()))
+ rc = request_ctx.get(None)
+ _apply_request_envelope(ctx, rc)
+ await self._bind_spillover(ctx, rc)
+ try:
+ entry = await store.get(uri[len(prefix) :], owner=caller_owner(ctx))
+ except (PermissionError, ValueError):
+ raise ResourceNotFoundError(uri) from None
+ if entry is None:
+ raise ResourceNotFoundError(uri)
+ return [
+ ReadResourceContents(
+ content=entry.payload.decode("utf-8"),
+ mime_type=entry.mime_type,
+ )
+ ]
+ entry = self._resources.get(uri)
+ path_kwargs: Dict[str, str] = {}
+
+ if entry is None:
+ for template_entry in self._resource_templates:
+ match = template_entry.pattern.match(uri) if template_entry.pattern else None
+ if match:
+ entry = template_entry
+ path_kwargs = match.groupdict()
+ break
+
+ if entry is None:
+ raise ResourceNotFoundError(uri)
+
+ if entry.component is not None:
+ return [
+ ReadResourceContents(
+ content=entry.component.get_bundle(),
+ mime_type=get_widget_mime_type(),
+ meta=resource_read_contents_meta(entry.component),
+ )
+ ]
+
+ cfg = entry.config
+ ctx = ExecutionContext(request_id=str(uuid.uuid4()), metadata=dict(path_kwargs))
+ _apply_request_envelope(ctx, request_ctx.get(None))
+ guards, middleware, interceptors, pipes, filters = self._pipeline_stages(entry.method)
+
+ result = await run_pipeline(
+ handler=entry.method,
+ handler_instance=entry.instance,
+ args=(),
+ kwargs={**path_kwargs, "context": ctx},
+ context=ctx,
+ guards=guards,
+ middleware=middleware,
+ interceptors=interceptors,
+ pipes=pipes,
+ filters=filters,
+ )
+
+ # Support Discriminated Union formats for return (Section 1.2)
+ if isinstance(result, dict) and "type" in result and "data" in result:
+ result = result["data"]
+
+ if isinstance(result, BaseModel):
+ result = result.model_dump()
+
+ if isinstance(result, bytes):
+ return [
+ ReadResourceContents(
+ content=result, mime_type=cfg.mime_type or "application/octet-stream"
+ )
+ ]
+
+ if isinstance(result, str):
+ return [ReadResourceContents(content=result, mime_type=cfg.mime_type or "text/plain")]
+
+ text = json.dumps(result, indent=2, default=str)
+ return [ReadResourceContents(content=text, mime_type=cfg.mime_type or "application/json")]
+
+ async def _get_prompt(self, name: str, arguments: Dict[str, str]) -> types.GetPromptResult:
+ entry = self._prompts.get(name)
+ if entry is None:
+ raise PromptNotFoundError(name)
+
+ cfg = entry.config
+ args_dict = dict(arguments or {})
+ rc = request_ctx.get(None)
+ allowed = {arg.name for arg in cfg.arguments} if cfg.arguments else None
+ args_dict = merge_mcp_param_headers(
+ args_dict,
+ extract_mcp_param_headers(_http_headers_from_request_ctx(rc)),
+ allowed_fields=allowed,
+ )
+ ctx = ExecutionContext(request_id=str(uuid.uuid4()), metadata=args_dict)
+ _apply_request_envelope(ctx, rc)
+ guards, middleware, interceptors, pipes, filters = self._pipeline_stages(entry.method)
+
+ raw_messages = await run_pipeline(
+ handler=entry.method,
+ handler_instance=entry.instance,
+ args=(args_dict, ctx),
+ kwargs={},
+ context=ctx,
+ guards=guards,
+ middleware=middleware,
+ interceptors=interceptors,
+ pipes=pipes,
+ filters=filters,
+ )
+
+ if not isinstance(raw_messages, (list, tuple)):
+ raw_messages = [raw_messages]
+
+ messages: List[types.PromptMessage] = []
+ for msg in raw_messages:
+ role = msg.role if hasattr(msg, "role") else msg.get("role")
+ content = msg.content if hasattr(msg, "content") else msg.get("content")
+ messages.append(
+ types.PromptMessage(role=role, content=types.TextContent(type="text", text=content))
+ )
+
+ return types.GetPromptResult(description=cfg.description, messages=messages)
diff --git a/nitrostack/core/app_runtime.py b/nitrostack/core/app_runtime.py
new file mode 100644
index 0000000..d863230
--- /dev/null
+++ b/nitrostack/core/app_runtime.py
@@ -0,0 +1,103 @@
+"""Application runtime orchestration and compatibility exports."""
+
+import logging
+import time
+from typing import Any, Callable, Dict, List, Optional, Tuple, Type
+
+from nitrostack import __version__ as _sdk_version
+from nitrostack.core.app_config import (
+ ServerConfig,
+ _apply_project_identity,
+)
+from nitrostack.core.app_definitions import DefinitionsMixin
+from nitrostack.core.app_entries import _PromptEntry, _ResourceEntry, _ToolEntry
+from nitrostack.core.app_invocation import InvocationMixin
+from nitrostack.core.app_protocol import ProtocolHandlersMixin
+from nitrostack.core.app_registration import RegistrationMixin
+from nitrostack.core.app_resources import ResourcesMixin
+from nitrostack.core.app_startup import StartupMixin
+from nitrostack.core.app_tasks import TaskProtocolMixin
+from nitrostack.core.app_tool_results import ToolResultsMixin
+from nitrostack.core.decorators import ToolConfig
+from nitrostack.core.interceptors.data_spillover import (
+ SpilloverRegistry,
+)
+from nitrostack.core.mcp_server import NitroStackMcpServer
+from nitrostack.core.task import TaskManager
+from nitrostack.core.visibility import VisibilityTransform
+from nitrostack.protocol.version import (
+ EraSource,
+ ProtocolEra,
+ resolve_protocol_era_resolution,
+)
+from nitrostack.runtime.correlation import InFlightRegistry
+from nitrostack.transforms import (
+ TransformPipeline,
+ TransformRegistry,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class McpApplication(
+ RegistrationMixin,
+ ProtocolHandlersMixin,
+ DefinitionsMixin,
+ InvocationMixin,
+ ToolResultsMixin,
+ ResourcesMixin,
+ TaskProtocolMixin,
+ StartupMixin,
+):
+ def __init__(self, app_class: Type):
+ self.app_class = app_class
+ self._started_at = time.monotonic()
+ self._sdk_version = _sdk_version
+ if hasattr(app_class, "_mcp_app_module"):
+ self.root_module = app_class._mcp_app_module
+ self.server_config = app_class._mcp_app_server
+ elif hasattr(app_class, "_mcp_module_config"):
+ self.root_module = app_class
+ self.server_config = ServerConfig(
+ name=app_class._mcp_module_config.name or "mcp-server"
+ )
+ else:
+ raise ValueError(
+ "Invalid application class. Must be decorated with @mcp_app or @module."
+ )
+ _apply_project_identity(self.server_config)
+
+ self.mcp_server: Optional[NitroStackMcpServer] = None
+ era_resolution = resolve_protocol_era_resolution(
+ config_value=self.server_config.protocol_era
+ )
+ self.protocol_era: ProtocolEra = era_resolution.era
+ self.protocol_era_source: EraSource = era_resolution.source
+
+ # nitrostack owns these registries so any number of low-level `Server`
+ # instances can be wired against the same tools/resources/prompts (see
+ # `create_configured_mcp_server`).
+ self._tools: Dict[str, _ToolEntry] = {}
+ self._resources: Dict[str, _ResourceEntry] = {}
+ self._resource_templates: List[_ResourceEntry] = []
+ self._prompts: Dict[str, _PromptEntry] = {}
+ self._initial_tools: List[Tuple[Any, Callable, ToolConfig]] = []
+ self.task_manager = TaskManager()
+ self._in_flight = InFlightRegistry()
+ self.visibility_transform = VisibilityTransform()
+ self._spillover = SpilloverRegistry()
+
+ # Pipeline first: handlers consult it lazily when requests arrive.
+ self._transforms = TransformPipeline(getattr(self.app_class, "_mcp_transforms", None) or [])
+
+ self._bootstrap()
+
+ # Tools are registered now, so transforms can see the catalog.
+ self._transforms.register(TransformRegistry(self._base_tool_list))
+
+
+class McpApplicationFactory:
+ @classmethod
+ async def create(cls, app_class: Type) -> McpApplication:
+ """Bootstraps and instantiates the McpApplication class."""
+ return McpApplication(app_class)
diff --git a/nitrostack/core/app_schema.py b/nitrostack/core/app_schema.py
new file mode 100644
index 0000000..d165ba6
--- /dev/null
+++ b/nitrostack/core/app_schema.py
@@ -0,0 +1,158 @@
+"""Schema and tool input normalization for the application runtime."""
+
+import logging
+from typing import Any, Dict, Optional, Type
+
+from pydantic import BaseModel, create_model
+
+from nitrostack.protocol.schema import (
+ normalize_output_schema,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def get_pydantic_model(schema: Any) -> Type[BaseModel]:
+ """Helper to resolve or construct a Pydantic model for input validation."""
+ if isinstance(schema, type) and issubclass(schema, BaseModel):
+ return schema
+ if isinstance(schema, dict):
+ # Dynamically build a Pydantic model from JSON schema
+ properties = schema.get("properties", {})
+ required = schema.get("required", [])
+ fields = {}
+ for name, prop in properties.items():
+ t = Any
+ prop_type = prop.get("type")
+ if prop_type == "string":
+ t = str
+ elif prop_type == "integer":
+ t = int
+ elif prop_type == "number":
+ t = float
+ elif prop_type == "boolean":
+ t = bool
+ elif prop_type == "array":
+ t = list
+ elif prop_type == "object":
+ t = dict
+
+ default = ... if name in required else None
+ fields[name] = (t, default)
+ return create_model("DynamicInputModel", **fields)
+
+ # Return a default empty model if invalid or empty
+ return create_model("EmptyInputModel")
+
+
+def _is_null_schema(node: Any) -> bool:
+ return isinstance(node, dict) and node.get("type") == "null"
+
+
+def _unwrap_nullable_schema(schema: Dict[str, Any]) -> Dict[str, Any]:
+ """Turn JSON Schema `T | null` into `T` so MCP Inspector can render widgets.
+
+ Pydantic v2 emits Optional fields as `anyOf: [{type: T}, {type: null}]` (or
+ `type: [T, "null"]`). Inspector/RJSF shows the property name but no input
+ control for those unions.
+ """
+ for key in ("anyOf", "oneOf"):
+ variants = schema.get(key)
+ if not isinstance(variants, list) or len(variants) != 2:
+ continue
+ non_null = [item for item in variants if not _is_null_schema(item)]
+ if len(non_null) != 1:
+ continue
+ merged = dict(non_null[0])
+ for extra_key, extra_val in schema.items():
+ if extra_key == key:
+ continue
+ if extra_key not in merged:
+ merged[extra_key] = extra_val
+ elif extra_key in ("description", "title", "default") and extra_val is not None:
+ merged[extra_key] = extra_val
+ if merged.get("default") is None:
+ merged.pop("default", None)
+ return merged
+
+ types = schema.get("type")
+ if isinstance(types, list):
+ non_null = [item for item in types if item != "null"]
+ if len(non_null) == 1:
+ schema = {**schema, "type": non_null[0]}
+ if schema.get("default") is None:
+ schema.pop("default", None)
+ return schema
+
+
+def inspector_friendly_schema(node: Any) -> Any:
+ """Normalize a Pydantic JSON Schema so MCP Inspector can render form fields."""
+ if isinstance(node, list):
+ return [inspector_friendly_schema(item) for item in node]
+ if not isinstance(node, dict):
+ return node
+ unwrapped = _unwrap_nullable_schema(node)
+ return {key: inspector_friendly_schema(value) for key, value in unwrapped.items()}
+
+
+def tool_json_schema(schema_spec: Any) -> Optional[Dict[str, Any]]:
+ """Convert a Pydantic model class or JSON-schema dict to MCP 2026-07-28 outputSchema.
+
+ Output schemas describe real results, so ``null`` branches of Optional fields are kept.
+ ``inspector_friendly_schema`` is only for input forms.
+ """
+ if schema_spec is None:
+ return None
+ if isinstance(schema_spec, dict):
+ return normalize_output_schema(schema_spec)
+ model = get_pydantic_model(schema_spec)
+ if model is not None:
+ return normalize_output_schema(model.model_json_schema())
+ return None
+
+
+def _is_blank_inspector_value(value: Any) -> bool:
+ """Inspector leaves unused form fields as ``""`` (or whitespace)."""
+ return value is None or (isinstance(value, str) and not value.strip())
+
+
+def _omit_blank_optional_fields(
+ payload: Dict[str, Any], input_model: Type[BaseModel]
+) -> Dict[str, Any]:
+ """Drop blank optional/defaulted fields so Pydantic defaults apply.
+
+ MCP Inspector sends ``filter: ""`` when the enum is left empty. Zod in the
+ TS SDK marks that field ``.optional()`` and then uses ``args.filter || 'all'``.
+ Pydantic ``default='all'`` only runs when the key is missing, not when it is
+ an empty string — so we omit blanks for non-required fields.
+ """
+ fields = getattr(input_model, "model_fields", {}) or {}
+ cleaned: Dict[str, Any] = {}
+ for key, value in payload.items():
+ field = fields.get(key)
+ if field is not None and (not field.is_required()) and _is_blank_inspector_value(value):
+ continue
+ cleaned[key] = value
+ return cleaned
+
+
+def parse_tool_input(
+ input_model: Type[BaseModel], arguments: Optional[Dict[str, Any]]
+) -> BaseModel:
+ """Validate tool arguments from Inspector or the older nested wrap.
+
+ Inspector sends top-level fields (`{openNow: true}`).
+ Older Python clients wrap them (`{input: {openNow: true}}`).
+ Empty strings on optional fields are treated as omitted (Inspector dropdowns).
+ """
+ arguments = arguments or {}
+ inner = arguments.get("input")
+ looks_wrapped = (
+ isinstance(inner, dict)
+ and set(arguments.keys()) <= {"input"}
+ and "input" not in input_model.model_fields
+ )
+ payload = inner if looks_wrapped else arguments
+ if not isinstance(payload, dict):
+ payload = {}
+ return input_model.model_validate(_omit_blank_optional_fields(payload, input_model))
diff --git a/nitrostack/core/app_startup.py b/nitrostack/core/app_startup.py
new file mode 100644
index 0000000..18efc6f
--- /dev/null
+++ b/nitrostack/core/app_startup.py
@@ -0,0 +1,169 @@
+"""Startup implementation mixin."""
+
+import logging
+import os
+from typing import Any, Optional
+
+from nitrostack.core.app_config import resolve_http_host, resolve_http_port
+from nitrostack.core.di import DIContainer
+from nitrostack.protocol.version import (
+ ProtocolEra,
+ resolve_http_engine,
+ resolve_protocol_era_resolution,
+ wire_mode_for_era,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class StartupMixin:
+ def _apply_protocol_era(self) -> ProtocolEra:
+ """Re-read env/config, store the era, and log how it was chosen."""
+ resolution = resolve_protocol_era_resolution(config_value=self.server_config.protocol_era)
+ self.protocol_era = resolution.era
+ self.protocol_era_source = resolution.source
+ logger.info(resolution.log_line())
+ return resolution.era
+
+ def get_combined_app(
+ self,
+ *,
+ max_sessions: Optional[int] = None,
+ session_idle_timeout: Optional[float] = None,
+ enable_cors: Optional[bool] = None,
+ stateless: Optional[bool] = None,
+ json_response: Optional[bool] = None,
+ ) -> Any:
+ """
+ Build the Starlette app wiring the owned low-level server to the Streamable
+ HTTP (`/mcp`), legacy SSE (`/sse` + `/mcp/messages/`), and health-check
+ (`/mcp/health`) endpoints. See `nitrostack.transports.http.build_http_app`
+ for the full behavior (session cap, CORS, DNS-rebinding protection).
+
+ Any argument left as ``None`` falls back to env
+ (``MCP_STATELESS``, ``NITRO_MCP_PROTOCOL_VERSION``, ``ENABLE_CORS``)
+ then this app's ``ServerConfig.protocol_era``. Unset protocol era is ``auto``.
+ """
+ from nitrostack.transports.http import build_http_app
+
+ era = self._apply_protocol_era()
+ wire_mode = wire_mode_for_era(era)
+ # Sessionful 1.x only when era is legacy. auto/modern stay sessionless.
+ http_engine = resolve_http_engine(era, stateless=stateless)
+ effective_stateless = http_engine == "sessionless"
+
+ if enable_cors is None:
+ env_cors = self._env_bool("ENABLE_CORS")
+ enable_cors = True if env_cors is None else env_cors
+
+ http_app = build_http_app(
+ self,
+ max_sessions=max_sessions
+ if max_sessions is not None
+ else self.server_config.max_sessions,
+ session_idle_timeout=session_idle_timeout,
+ enable_cors=enable_cors,
+ stateless=effective_stateless,
+ json_response=self.server_config.json_response
+ if json_response is None
+ else json_response,
+ protocol_era=era,
+ wire_mode=wire_mode,
+ http_engine=http_engine,
+ json_body_limit=self.server_config.json_body_limit,
+ )
+
+ # The official MCP SDK owns the complete Streamable HTTP request lifecycle
+ # mounted by ``build_http_app``. Do not wrap it in a second JSON-RPC
+ # dispatcher: a sidecar would answer ping/initialize/tools/call itself and
+ # could diverge from the protocol and session behaviour of the SDK.
+ return http_app
+
+ async def _run_stdio(self) -> None:
+ from nitrostack.transports.stdio import run_stdio
+
+ await run_stdio(self.mcp_server, self.protocol_era)
+
+ @staticmethod
+ def _env_int(name: str) -> Optional[int]:
+ raw = os.environ.get(name)
+ if raw is None or raw == "":
+ return None
+ try:
+ return int(raw)
+ except ValueError:
+ return None
+
+ @staticmethod
+ def _env_bool(name: str) -> Optional[bool]:
+ raw = os.environ.get(name)
+ if raw is None or raw == "":
+ return None
+ return raw.strip().lower() in ("1", "true", "yes", "on")
+
+ async def start(self) -> None:
+ """Starts the MCP application based on transport configurations."""
+ # Start background OAuth discovery only when OAuthModule registered a service.
+ # resolve(OAuthService) would otherwise auto-instantiate and fail closed.
+ from nitrostack.auth.oauth import OAuthService, warn_if_oauth_fail_open
+
+ container = DIContainer.get_instance()
+ if container.has_value(OAuthService):
+ oauth_service = container.resolve(OAuthService)
+ oauth_service.start_discovery_server()
+ warn_if_oauth_fail_open()
+
+ transport = os.environ.get("MCP_TRANSPORT_TYPE") or self.server_config.transport_type
+ node_env = os.environ.get("NODE_ENV", "development")
+ port = resolve_http_port()
+ host = resolve_http_host()
+
+ json_response = self._env_bool("MCP_JSON_RESPONSE")
+ if json_response is None:
+ json_response = self.server_config.json_response
+ max_sessions = self._env_int("MCP_MAX_SESSIONS") or self.server_config.max_sessions
+ session_timeout_ms = (
+ self._env_int("MCP_SESSION_TIMEOUT_MS") or self.server_config.session_timeout_ms
+ )
+ session_idle_timeout = (session_timeout_ms / 1000) if session_timeout_ms else None
+ graceful_timeout_ms = self._env_int("MCP_GRACEFUL_SHUTDOWN_TIMEOUT_MS") or 10000
+
+ if transport == "http":
+ import uvicorn
+
+ app = self.get_combined_app(
+ max_sessions=max_sessions,
+ session_idle_timeout=session_idle_timeout,
+ json_response=json_response,
+ )
+ config = uvicorn.Config(
+ app,
+ host=host,
+ port=port,
+ log_level="info",
+ timeout_graceful_shutdown=graceful_timeout_ms / 1000,
+ )
+ server = uvicorn.Server(config)
+ await server.serve()
+ elif transport == "dual" or (node_env == "production" and not transport):
+ from nitrostack.transports.dual import run_dual
+
+ app = self.get_combined_app(
+ max_sessions=max_sessions,
+ session_idle_timeout=session_idle_timeout,
+ json_response=json_response,
+ )
+ await run_dual(
+ self,
+ app,
+ host=host,
+ port=port,
+ graceful_timeout=graceful_timeout_ms / 1000,
+ )
+ else:
+ # Default Stdio
+ self._apply_protocol_era()
+ from nitrostack.transports.stdio import safe_stdio_transport
+
+ with safe_stdio_transport():
+ await self._run_stdio()
diff --git a/nitrostack/core/app_tasks.py b/nitrostack/core/app_tasks.py
new file mode 100644
index 0000000..1705ba9
--- /dev/null
+++ b/nitrostack/core/app_tasks.py
@@ -0,0 +1,235 @@
+"""TaskProtocol implementation mixin."""
+
+import logging
+import sys
+import uuid
+from typing import Any, Dict, Optional
+
+import mcp.types as types
+from mcp import MCPError
+from mcp.server.context import ServerRequestContext
+from mcp.types import (
+ PaginatedRequestParams,
+)
+from pydantic import BaseModel
+
+from nitrostack.core.app_config import GetTaskResult, _iso_timestamp
+from nitrostack.core.app_context import _apply_request_envelope
+from nitrostack.core.context import ExecutionContext
+from nitrostack.core.errors import (
+ TaskAlreadyTerminalError,
+ TaskExpiredError,
+ TaskNotFoundError,
+)
+from nitrostack.core.mcp_server import NitroStackMcpServer
+from nitrostack.core.pipeline import run_pipeline
+from nitrostack.core.task import TaskStatus
+from nitrostack.protocol.deprecated import (
+ deprecated_method_message,
+ rejects_deprecated_method,
+)
+from nitrostack.runtime.request_ctx import request_ctx
+from nitrostack.tasks.authorization import extract_task_access_context
+
+logger = logging.getLogger(__name__)
+
+
+class TaskProtocolMixin:
+ def _task_data_to_mcp_task(self, task) -> types.Task:
+ """Map TaskData to MCP Task. EXPIRED is not an MCP wire status — surface as error."""
+ if task.status == TaskStatus.EXPIRED:
+ raise MCPError(types.INVALID_PARAMS, f"Task {task.id} has expired")
+ return types.Task(
+ taskId=task.id,
+ status=task.status.value,
+ statusMessage=task.progress or "",
+ createdAt=_iso_timestamp(task.created_at),
+ lastUpdatedAt=_iso_timestamp(task.last_updated_at or task.created_at),
+ ttl=task.ttl if task.ttl is not None else 0,
+ pollInterval=task.poll_interval,
+ )
+
+ def _serialize_task_result_payload(self, result: Any) -> Any:
+ if isinstance(result, types.CallToolResult):
+ return result.model_dump(by_alias=True, exclude_none=True)
+ if isinstance(result, BaseModel):
+ return result.model_dump()
+ return result
+
+ def _build_get_task_result(self, task) -> types.GetTaskResult:
+ mcp_task = self._task_data_to_mcp_task(task)
+ payload: Dict[str, Any] = {
+ "taskId": mcp_task.task_id,
+ "status": mcp_task.status,
+ "statusMessage": mcp_task.status_message,
+ "createdAt": mcp_task.created_at,
+ "lastUpdatedAt": mcp_task.last_updated_at,
+ "ttl": mcp_task.ttl,
+ "pollInterval": mcp_task.poll_interval,
+ }
+ if task.status == TaskStatus.COMPLETED and task.result is not None:
+ payload["result"] = self._serialize_task_result_payload(task.result)
+ elif task.status == TaskStatus.FAILED and task.error is not None:
+ payload["error"] = {"message": str(task.error)}
+ elif task.status == TaskStatus.INPUT_REQUIRED and task.result is not None:
+ payload["result"] = task.result
+ return GetTaskResult(**payload)
+
+ def _register_task_handlers(self, server: NitroStackMcpServer) -> None:
+ if self.protocol_era in ("auto", "modern"):
+ server.has_task_support = False
+ return
+
+ async def handle_list_tasks(req):
+ if rejects_deprecated_method("tasks/list", self.protocol_era):
+ message = deprecated_method_message("tasks/list")
+ raise MCPError(types.METHOD_NOT_FOUND, message or "Not supported")
+ tasks_list = []
+ access = extract_task_access_context(request_ctx.get(None), self.protocol_era)
+ params = getattr(req, "params", req)
+ cursor = getattr(params, "cursor", None) if params is not None else None
+ tasks_page, next_cursor = await self.task_manager.list_tasks_page(
+ access_context=access,
+ cursor=cursor,
+ )
+ for t in tasks_page:
+ if t.status == TaskStatus.EXPIRED:
+ continue
+ tasks_list.append(self._task_data_to_mcp_task(t))
+ return types.ListTasksResult(tasks=tasks_list, nextCursor=next_cursor)
+
+ async def handle_get_task(req):
+ params = getattr(req, "params", req)
+ task_id = getattr(params, "task_id", None) or getattr(params, "taskId", None)
+ access = extract_task_access_context(request_ctx.get(None), self.protocol_era)
+ try:
+ t = await self.task_manager.get_task(task_id, access_context=access)
+ except TaskNotFoundError:
+ raise MCPError(types.INVALID_PARAMS, f"Task {task_id} not found") # noqa: B904
+ return self._build_get_task_result(t)
+
+ async def handle_cancel_task(req):
+ params = getattr(req, "params", req)
+ task_id = getattr(params, "task_id", None) or getattr(params, "taskId", None)
+ access = extract_task_access_context(request_ctx.get(None), self.protocol_era)
+ try:
+ await self.task_manager.cancel_task(task_id, access_context=access)
+ t = await self.task_manager.get_task(task_id, access_context=access)
+ except TaskNotFoundError:
+ raise MCPError(types.INVALID_PARAMS, f"Task {task_id} not found") # noqa: B904
+ except TaskExpiredError:
+ raise MCPError(types.INVALID_PARAMS, f"Task {task_id} has expired") # noqa: B904
+ except TaskAlreadyTerminalError as e:
+ raise MCPError(types.INVALID_PARAMS, str(e)) # noqa: B904
+ mcp_task = self._task_data_to_mcp_task(t)
+ return types.CancelTaskResult(
+ taskId=mcp_task.task_id,
+ status=mcp_task.status,
+ statusMessage=mcp_task.status_message,
+ createdAt=mcp_task.created_at,
+ lastUpdatedAt=mcp_task.last_updated_at,
+ ttl=mcp_task.ttl,
+ pollInterval=mcp_task.poll_interval,
+ )
+
+ async def handle_get_task_payload(req):
+ if rejects_deprecated_method("tasks/result", self.protocol_era):
+ message = deprecated_method_message("tasks/result")
+ raise MCPError(types.METHOD_NOT_FOUND, message or "Not supported")
+ params = getattr(req, "params", req)
+ task_id = getattr(params, "task_id", None) or getattr(params, "taskId", None)
+ access = extract_task_access_context(request_ctx.get(None), self.protocol_era)
+ try:
+ t = await self.task_manager.wait_until_done(task_id, access_context=access)
+ except TaskNotFoundError:
+ raise MCPError(types.INVALID_PARAMS, f"Task {task_id} not found") # noqa: B904
+ if t.status == TaskStatus.COMPLETED:
+ return t.result
+ if t.status == TaskStatus.CANCELLED:
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text="Task was cancelled.")],
+ isError=True,
+ )
+ if t.status == TaskStatus.EXPIRED:
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text="Task has expired.")],
+ isError=True,
+ )
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=str(t.error or t.progress))],
+ isError=True,
+ )
+
+ async def on_list_tasks(
+ ctx: ServerRequestContext, params: Optional[PaginatedRequestParams]
+ ):
+ return await handle_list_tasks(types.ListTasksRequest(params=params))
+
+ async def on_get_task(ctx: ServerRequestContext, params: types.GetTaskRequestParams):
+ return await handle_get_task(types.GetTaskRequest(params=params))
+
+ async def on_cancel_task(ctx: ServerRequestContext, params: types.CancelTaskRequestParams):
+ return await handle_cancel_task(types.CancelTaskRequest(params=params))
+
+ async def on_get_task_payload(
+ ctx: ServerRequestContext, params: types.GetTaskPayloadRequestParams
+ ):
+ return await handle_get_task_payload(types.GetTaskPayloadRequest(params=params))
+
+ server.add_request_handler("tasks/list", PaginatedRequestParams, on_list_tasks)
+ server.add_request_handler("tasks/get", types.GetTaskRequestParams, on_get_task)
+ server.add_request_handler("tasks/cancel", types.CancelTaskRequestParams, on_cancel_task)
+ server.add_request_handler(
+ "tasks/result", types.GetTaskPayloadRequestParams, on_get_task_payload
+ )
+ server.request_handlers[types.ListTasksRequest] = handle_list_tasks
+ server.request_handlers[types.GetTaskRequest] = handle_get_task
+ server.request_handlers[types.CancelTaskRequest] = handle_cancel_task
+ server.request_handlers[types.GetTaskPayloadRequest] = handle_get_task_payload
+ server.has_task_support = True
+
+ def _register_initialized_handler(self, server: NitroStackMcpServer) -> None:
+ async def handle_initialized(notification: types.InitializedNotification):
+ for instance, method, config in self._initial_tools:
+ try:
+ entry = self._tools[config.name]
+ try:
+ input_inst = entry.input_model()
+ except Exception:
+ input_inst = None
+
+ ctx = ExecutionContext(
+ request_id=f"initial-tool-{uuid.uuid4().hex[:8]}",
+ tool_name=config.name,
+ metadata={},
+ )
+ _apply_request_envelope(ctx, request_ctx.get(None))
+ guards, middleware, interceptors, pipes, filters = self._pipeline_stages(method)
+
+ await run_pipeline(
+ handler=method,
+ handler_instance=instance,
+ args=(input_inst, ctx),
+ kwargs={},
+ context=ctx,
+ guards=guards,
+ middleware=middleware,
+ interceptors=interceptors,
+ pipes=pipes,
+ filters=filters,
+ param_name="input",
+ param_type=entry.input_model,
+ )
+ except Exception as e:
+ sys.stderr.write(f"Error executing initial tool '{config.name}': {e}\n")
+ sys.stderr.flush()
+
+ async def on_initialized(
+ ctx: ServerRequestContext, _params: Optional[types.NotificationParams]
+ ):
+ await handle_initialized(types.InitializedNotification())
+
+ server.add_notification_handler(
+ "notifications/initialized", types.NotificationParams, on_initialized
+ )
+ server.notification_handlers[types.InitializedNotification] = handle_initialized
diff --git a/nitrostack/core/app_tool_results.py b/nitrostack/core/app_tool_results.py
new file mode 100644
index 0000000..12c616f
--- /dev/null
+++ b/nitrostack/core/app_tool_results.py
@@ -0,0 +1,153 @@
+"""ToolResults implementation mixin."""
+
+import json
+import logging
+from typing import Any, Dict, List, Optional
+
+import mcp.types as types
+from pydantic import BaseModel
+
+from nitrostack.core.app_mode import get_widget_mime_type
+from nitrostack.core.context import ExecutionContext
+from nitrostack.core.interceptors.data_spillover import (
+ SpilloverResult,
+)
+from nitrostack.protocol.mrtr import InputRequiredResult
+from nitrostack.widgets.component import Component
+from nitrostack.widgets.mcp_meta import build_call_tool_result_meta
+
+logger = logging.getLogger(__name__)
+
+
+class ToolResultsMixin:
+ def _to_call_tool_result(
+ self,
+ result: Any,
+ component: Optional[Component] = None,
+ context: Optional[ExecutionContext] = None,
+ ) -> types.CallToolResult:
+ if isinstance(result, SpilloverResult):
+ return result.to_mcp()
+ if isinstance(result, InputRequiredResult):
+ wire = result.to_wire_dict()
+ return types.CallToolResult(
+ content=[
+ types.TextContent(type="text", text=wire.get("message", "Input required"))
+ ],
+ structuredContent=wire,
+ isError=False,
+ )
+ mrtr_result = None
+ if isinstance(result, dict) and result.get("resultType") == "input_required":
+ from nitrostack.protocol.mrtr import coerce_input_required_result
+
+ mrtr_result = coerce_input_required_result(result)
+ if mrtr_result is not None:
+ wire = mrtr_result.to_wire_dict()
+ return types.CallToolResult(
+ content=[
+ types.TextContent(type="text", text=wire.get("message", "Input required"))
+ ],
+ structuredContent=wire,
+ isError=False,
+ )
+ if isinstance(result, types.CallToolResult):
+ if component is not None:
+ result = result.model_copy(
+ update={
+ "meta": build_call_tool_result_meta(
+ component, self._call_tool_result_meta(result)
+ )
+ }
+ )
+ return result
+ if isinstance(result, BaseModel):
+ result = result.model_dump()
+
+ structured: Any = result
+ result_meta: Optional[Dict[str, Any]] = None
+
+ if component is not None:
+ if component.transformer is not None:
+ structured = component.transformer(result, context)
+ if component.meta_transformer is not None:
+ result_meta = component.meta_transformer(result, context) or {}
+ if isinstance(structured, BaseModel):
+ structured = structured.model_dump()
+
+ if isinstance(result, dict) and "content" in result and "isError" in result:
+ call_result = types.CallToolResult(**result)
+ if component is not None:
+ call_result = call_result.model_copy(
+ update={
+ "meta": build_call_tool_result_meta(
+ component, self._call_tool_result_meta(call_result)
+ )
+ }
+ )
+ return call_result
+
+ if isinstance(structured, dict):
+ widget_meta = (
+ build_call_tool_result_meta(component, result_meta) if component else result_meta
+ )
+ return types.CallToolResult(
+ content=self._widget_result_content(structured, component),
+ structuredContent=structured,
+ **({"_meta": widget_meta} if widget_meta else {}),
+ isError=False,
+ )
+
+ return types.CallToolResult(
+ content=[types.TextContent(type="text", text=str(structured))],
+ isError=False,
+ )
+
+ @staticmethod
+ def _call_tool_result_meta(result: types.CallToolResult) -> Optional[Dict[str, Any]]:
+ """Read caller ``_meta`` from the field or pydantic extra (alias vs extra)."""
+ if result.meta:
+ return dict(result.meta)
+ extra = getattr(result, "model_extra", None) or {}
+ raw = extra.get("_meta") or extra.get("meta")
+ return dict(raw) if isinstance(raw, dict) else None
+
+ def _widget_result_content(
+ self, structured: Dict[str, Any], component: Optional[Component]
+ ) -> List[Any]:
+ """Text fallback plus data-filled HTML so Inspector/Studio can paint the live result."""
+ content: List[Any] = [
+ types.TextContent(type="text", text=json.dumps(structured, indent=2, default=str)),
+ ]
+ if component is None:
+ return content
+ mime = get_widget_mime_type()
+ try:
+ filled = component.html_with_data(structured)
+ except Exception:
+ logger.exception(
+ "Widget HTML render failed for %s; returning JSON without embedded HTML",
+ component.id,
+ )
+ filled = None
+ if filled is not None:
+ content.append(
+ types.EmbeddedResource(
+ type="resource",
+ resource=types.TextResourceContents(
+ uri=component.resource_uri,
+ mimeType=mime,
+ text=filled,
+ ),
+ )
+ )
+ content.append(
+ types.ResourceLink(
+ type="resource_link",
+ uri=component.resource_uri,
+ name=component.name,
+ description=component.description,
+ mimeType=mime,
+ )
+ )
+ return content
diff --git a/nitrostack/core/context.py b/nitrostack/core/context.py
index 42cf129..15e5c03 100644
--- a/nitrostack/core/context.py
+++ b/nitrostack/core/context.py
@@ -34,8 +34,13 @@ def __init__(self, log_file: Optional[str] = None, name: str = "nitrostack"):
level = getattr(logging, level_str, logging.DEBUG)
self.logger.setLevel(level)
- # Avoid adding duplicate handlers if initialized multiple times
- if not self.logger.handlers:
+ # The log-emitter bridge is not an output handler; keep configuring
+ # the file/stdout destination even though that bridge is installed.
+ has_output_handler = any(
+ not getattr(handler, "_nitrostack_log_emitter", False)
+ for handler in self.logger.handlers
+ )
+ if not has_output_handler:
formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] (%(name)s): %(message)s'
)
@@ -107,8 +112,9 @@ class TaskContext:
whichever transport (STDIO or Streamable HTTP) initiated the task —
transport-agnostic since both use the same ``mcp.server.session.ServerSession``.
The client only receives these if it supplied a ``progressToken`` in the
- original ``tools/call`` request's ``_meta``; ``TaskManager``-backed polling via
- ``tasks/get`` always works regardless, so this is additive, not required.
+ original ``tools/call`` request's ``_meta``. TaskManager-backed polling is
+ retained for in-process callers and the legacy wire; the incomplete Tasks
+ surface is deliberately not advertised on MCP 2026.
"""
def __init__(
@@ -197,6 +203,13 @@ class ExecutionContext:
rpc_meta: Optional["RequestMeta"] = None
mcp_headers: Dict[str, str] = field(default_factory=dict)
mcp_param_headers: Dict[str, str] = field(default_factory=dict)
+ _tool_visibility_controller: Any = field(default=None, repr=False, compare=False)
+ _visibility_session_key: Any = field(default=None, repr=False, compare=False)
+ _visibility_change_callback: Any = field(default=None, repr=False, compare=False)
+ _visibility_supported: bool = field(default=False, repr=False, compare=False)
+ spillover_session_key: Optional[str] = field(default=None, repr=False)
+ spillover_invalid_auth: bool = field(default=False, repr=False)
+ input: Optional[Dict[str, Any]] = None
def __post_init__(self) -> None:
if not self.correlation_id:
@@ -208,3 +221,19 @@ def user(self) -> Optional[str]:
if self.auth is None:
return None
return self.auth.subject
+
+ def enable_tools(self, names: List[str]) -> None:
+ """Enable registered tools for this verified transport session."""
+ self._change_tool_visibility(names, visible=True)
+
+ def disable_tools(self, names: List[str]) -> None:
+ """Disable registered tools for this verified transport session."""
+ self._change_tool_visibility(names, visible=False)
+
+ def _change_tool_visibility(self, names: List[str], *, visible: bool) -> None:
+ if not self._visibility_supported or self._tool_visibility_controller is None:
+ self.logger.warn("Tool visibility changes require a sessionful transport session")
+ return
+ changed = self._tool_visibility_controller.change(self, names, visible=visible)
+ if changed and self._visibility_change_callback is not None:
+ self._visibility_change_callback(self)
diff --git a/nitrostack/core/decorators.py b/nitrostack/core/decorators.py
index 60f4323..9a9b39f 100644
--- a/nitrostack/core/decorators.py
+++ b/nitrostack/core/decorators.py
@@ -53,6 +53,7 @@ class ToolConfig:
invocation: Optional[ToolInvocation] = None
metadata: Dict[str, Any] = field(default_factory=dict)
is_initial: bool = False
+ default_visible: Optional[bool] = None
@dataclass
class ResourceConfig:
@@ -101,6 +102,7 @@ def tool(
examples: Optional[ToolExamples] = None,
invocation: Optional[ToolInvocation] = None,
metadata: Optional[Dict[str, Any]] = None,
+ default_visible: Optional[bool] = None,
):
"""
Decorator to register a method as an MCP Tool.
@@ -121,6 +123,7 @@ def decorator(func: Callable):
annotations=annotations,
task_support=task_support,
visibility=visibility,
+ default_visible=(visibility == "visible") if default_visible is None else default_visible,
examples=examples,
invocation=invocation,
metadata=metadata,
diff --git a/nitrostack/core/errors.py b/nitrostack/core/errors.py
index b5f1c50..5830601 100644
--- a/nitrostack/core/errors.py
+++ b/nitrostack/core/errors.py
@@ -1,6 +1,10 @@
from typing import Any
+class PayloadTooLargeError(ValueError):
+ """A serialized tool result exceeds the spillover store's per-result limit."""
+
+
class ToolExecutionError(Exception):
"""Raised when tool execution fails."""
pass
@@ -9,6 +13,13 @@ class ValidationError(Exception):
"""Raised when inputs or outputs fail schema validation."""
pass
+class RateLimitExceededError(ValueError):
+ """Raised when a @rate_limit bucket is exhausted."""
+
+ def __init__(self, message: str, retry_after_seconds: float):
+ super().__init__(message)
+ self.retry_after_seconds = retry_after_seconds
+
class ResourceNotFoundError(Exception):
"""Raised when a requested resource is not found."""
pass
diff --git a/nitrostack/core/interceptors/__init__.py b/nitrostack/core/interceptors/__init__.py
new file mode 100644
index 0000000..4344182
--- /dev/null
+++ b/nitrostack/core/interceptors/__init__.py
@@ -0,0 +1,15 @@
+"""Built-in tool interceptors and spillover storage adapters."""
+
+from .data_spillover import DataSpilloverInterceptor, generate_preview
+from .spillover import (
+ FileSpilloverStore,
+ MemorySpilloverStore,
+ PayloadTooLargeError,
+ SpilloverEntry,
+ SpilloverStore,
+)
+
+__all__ = [
+ "DataSpilloverInterceptor", "FileSpilloverStore", "MemorySpilloverStore",
+ "PayloadTooLargeError", "SpilloverEntry", "SpilloverStore", "generate_preview",
+]
diff --git a/nitrostack/core/interceptors/data_spillover.py b/nitrostack/core/interceptors/data_spillover.py
new file mode 100644
index 0000000..ee9ae97
--- /dev/null
+++ b/nitrostack/core/interceptors/data_spillover.py
@@ -0,0 +1,186 @@
+"""Tool-result spillover, bounded previews, and trusted caller ownership."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+import weakref
+from dataclasses import dataclass
+from itertools import islice
+from typing import Any
+from urllib.parse import urlsplit
+
+import mcp.types as types
+from pydantic import BaseModel
+
+from nitrostack.auth.request import authorization_token_from_request, tenant_from_claims
+from nitrostack.core.context import ExecutionContext
+from nitrostack.protocol.mrtr import InputRequiredResult
+from nitrostack.core.interceptors.spillover import MemorySpilloverStore, SpilloverStore
+from nitrostack.protocol.version import wire_mode_for_era
+from nitrostack.runtime.caller import session_id_from_request_context
+from nitrostack.runtime.request_ctx import RequestContext, stdio_connection_id
+
+
+def generate_preview(value: Any, *, max_bytes: int = 2048) -> dict:
+ """Include head items and counts, shrinking even deeply nested values to fit."""
+ if max_bytes < 128:
+ raise ValueError("Preview budget must be at least 128 bytes")
+ if isinstance(value, list):
+ preview = {"type": "list", "count": len(value), "head": value[:5], "truncated": len(value) > 5}
+ elif isinstance(value, dict):
+ preview = {"type": "dict", "count": len(value), "head": dict(islice(value.items(), 5)),
+ "truncated": len(value) > 5}
+ else:
+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, default=str)
+ preview = {"type": "string", "count": len(text), "text": text[:512], "truncated": len(text) > 512}
+ encoded = json.dumps(preview, ensure_ascii=False, default=str).encode("utf-8")
+ if len(encoded) > max_bytes:
+ text = json.dumps(preview.get("head", preview.get("text")), ensure_ascii=False, default=str)
+ preview.pop("head", None)
+ preview["text"] = text[:512]
+ preview["truncated"] = True
+ while len(json.dumps(preview, ensure_ascii=False, default=str).encode("utf-8")) > max_bytes:
+ preview["text"] = preview["text"][:len(preview["text"]) // 2]
+ return preview
+
+
+@dataclass(frozen=True)
+class SpilloverResult:
+ preview: dict
+ resource_uri: str
+ original_size_bytes: int
+
+ def to_mcp(self) -> types.CallToolResult:
+ data = dict(preview=self.preview, resource_uri=self.resource_uri,
+ original_size_bytes=self.original_size_bytes)
+ return types.CallToolResult(
+ content=[
+ types.TextContent(type="text", text=json.dumps(data, ensure_ascii=False, default=str)),
+ types.ResourceLink(type="resource_link", uri=self.resource_uri,
+ name="Full tool result"),
+ ],
+ structuredContent=data, isError=False,
+ )
+
+
+SPILLOVER_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "preview": {"type": "object"},
+ "resource_uri": {"type": "string"},
+ "original_size_bytes": {"type": "integer", "minimum": 0},
+ },
+ "required": ["preview", "resource_uri", "original_size_bytes"],
+}
+
+
+class SpilloverRegistry:
+ """Per-application routes and weakly held anonymous session identities."""
+
+ def __init__(self):
+ self.routes: dict[str, SpilloverStore] = {}
+ self._sessions: dict[int, tuple[weakref.ref, str]] = {}
+
+ def register(self, interceptor):
+ prefix, store = interceptor.resource_uri_prefix, interceptor.store
+ for existing, registered in self.routes.items():
+ if prefix.startswith(existing) or existing.startswith(prefix):
+ if prefix != existing or store is not registered:
+ raise ValueError("Conflicting spillover resource prefixes")
+ self.routes[prefix] = store
+
+ def session_key(self, rc, era=None):
+ request = getattr(rc, "request", None)
+ if getattr(request, "scope", {}).get("type") == "http":
+ # Only routed requests reach here: the official manager has validated
+ # this ID. SDK session proxies themselves are per-request objects.
+ if wire_mode_for_era(era or "auto") != "sessionful":
+ return None
+ session_id = session_id_from_request_context(rc)
+ return "http:" + session_id if session_id else None
+ connection_id = stdio_connection_id.get()
+ if connection_id is not None:
+ return "stdio:" + connection_id
+ # Explicit in-process contexts retain their weakly-held test/session key.
+ # Never infer ownership from an official SDK request's proxy identity.
+ if not isinstance(rc, RequestContext):
+ return None
+ session = getattr(rc, "session", None)
+ if session is None:
+ return None
+ identity = id(session)
+ existing = self._sessions.get(identity)
+ if existing is not None and existing[0]() is session:
+ return existing[1]
+ key = "in-process:" + uuid.uuid4().hex
+ try:
+ reference = weakref.ref(session, lambda _: self._sessions.pop(identity, None))
+ except TypeError:
+ return None
+ self._sessions[identity] = (reference, key)
+ return key
+
+
+def caller_owner(context: ExecutionContext) -> str:
+ auth = context.auth
+ if auth is not None and (auth.subject or auth.client_id):
+ identity = ["principal", auth.iss, auth.subject, auth.client_id,
+ tenant_from_claims(auth.claims)]
+ elif context.spillover_invalid_auth:
+ raise PermissionError("Verified identity required for spillover")
+ elif context.spillover_session_key:
+ identity = ["session", context.spillover_session_key]
+ else:
+ raise PermissionError("Spillover requires a verified caller or trusted MCP session")
+ return hashlib.sha256(json.dumps(identity).encode("utf-8")).hexdigest()
+
+
+def bind_spillover_context(context, rc, registry, era=None):
+ context.spillover_session_key = registry.session_key(rc, era)
+ context.spillover_invalid_auth = bool(
+ authorization_token_from_request(rc) and context.auth is None
+ )
+
+
+class DataSpilloverInterceptor:
+ def __init__(
+ self, threshold_bytes: int = 64 * 1024, store: SpilloverStore | None = None,
+ resource_uri_prefix: str = "resource://data-spillover/",
+ ):
+ if type(threshold_bytes) is not int or threshold_bytes < 0:
+ raise ValueError("Spillover threshold must be a nonnegative integer")
+ parts = urlsplit(resource_uri_prefix)
+ if (not parts.scheme or not parts.netloc or parts.query or parts.fragment
+ or not resource_uri_prefix.endswith("/")):
+ raise ValueError("Resource prefix must be an absolute URI ending in '/'")
+ self.threshold_bytes = threshold_bytes
+ self.store = store if store is not None else MemorySpilloverStore()
+ self.resource_uri_prefix = resource_uri_prefix
+
+ async def intercept(self, context, next_fn):
+ result = await next_fn()
+ if isinstance(result, (InputRequiredResult, SpilloverResult)):
+ return result
+ if isinstance(result, dict) and result.get("resultType") == "input_required":
+ return result
+ value = result
+ if isinstance(value, types.CallToolResult):
+ if value.is_error or value.result_type == "input_required":
+ return result
+ value = value.model_dump(mode="json", by_alias=True, exclude_none=True)
+ elif isinstance(value, dict) and value.get("isError"):
+ return result
+ elif isinstance(value, BaseModel):
+ value = value.model_dump(mode="json")
+ if isinstance(value, str):
+ payload, mime = value.encode("utf-8"), "text/plain"
+ else:
+ payload = json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str).encode("utf-8")
+ mime = "application/json"
+ if len(payload) <= self.threshold_bytes:
+ return result
+ owner = caller_owner(context)
+ key = await self.store.put(payload, owner=owner, mime_type=mime)
+ return SpilloverResult(generate_preview(value), self.resource_uri_prefix + key, len(payload))
diff --git a/nitrostack/core/interceptors/spillover.py b/nitrostack/core/interceptors/spillover.py
new file mode 100644
index 0000000..7ab5482
--- /dev/null
+++ b/nitrostack/core/interceptors/spillover.py
@@ -0,0 +1,218 @@
+"""Bounded, caller-scoped storage for serialized tool results."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+import math
+import os
+import re
+import threading
+import time
+import uuid
+from collections import OrderedDict
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Protocol
+
+from nitrostack.core.errors import PayloadTooLargeError
+
+
+@dataclass(frozen=True)
+class SpilloverEntry:
+ payload: bytes
+ owner: str
+ mime_type: str
+ expires_at: float
+
+
+class SpilloverStore(Protocol):
+ max_bytes: int
+ ttl_seconds: float
+
+ async def put(
+ self, payload: bytes, *, owner: str, mime_type: str,
+ ttl_seconds: float | None = None,
+ ) -> str: ...
+
+ async def get(self, key: str, *, owner: str) -> SpilloverEntry | None: ...
+
+ async def delete(self, key: str, *, owner: str) -> bool: ...
+
+ async def cleanup_expired(self) -> int: ...
+
+
+def _valid_key(key: str) -> bool:
+ return isinstance(key, str) and re.fullmatch(r"[0-9a-f]{32}", key) is not None
+
+
+class MemorySpilloverStore:
+ """Thread-safe payload cache with absolute TTL and LRU eviction."""
+
+ def __init__(
+ self, *, max_bytes: int = 10 * 1024 * 1024,
+ max_total_bytes: int = 100 * 1024 * 1024, ttl_seconds: float = 300,
+ ):
+ if any(type(limit) is not int or limit <= 0 for limit in (max_bytes, max_total_bytes)):
+ raise ValueError("Storage limits must be positive integers")
+ if not math.isfinite(ttl_seconds) or ttl_seconds <= 0:
+ raise ValueError("TTL must be positive and finite")
+ self.max_bytes = max_bytes
+ self.max_total_bytes = max_total_bytes
+ self.ttl_seconds = ttl_seconds
+ self._entries: OrderedDict[str, SpilloverEntry] = OrderedDict()
+ self._lock = threading.RLock()
+ self._size = 0
+
+ def _entry(self, payload, owner, mime_type, ttl_seconds):
+ if not isinstance(payload, bytes):
+ raise TypeError("Store payload must be bytes")
+ if not owner:
+ raise ValueError("A caller owner is required")
+ if len(payload) > self.max_bytes:
+ raise PayloadTooLargeError(f"Payload exceeds max_bytes={self.max_bytes}")
+ ttl = self.ttl_seconds if ttl_seconds is None else ttl_seconds
+ if not math.isfinite(ttl) or ttl <= 0:
+ raise ValueError("TTL must be positive and finite")
+ return SpilloverEntry(payload, owner, mime_type, time.time() + ttl)
+
+ def _remove(self, key):
+ entry = self._entries.pop(key)
+ self._size -= len(entry.payload)
+
+ def _cleanup(self):
+ expired = [key for key, entry in self._entries.items() if entry.expires_at <= time.time()]
+ for key in expired:
+ self._remove(key)
+ return len(expired)
+
+ async def put(self, payload, *, owner, mime_type, ttl_seconds=None):
+ entry = self._entry(payload, owner, mime_type, ttl_seconds)
+ if len(payload) > self.max_total_bytes:
+ raise ValueError("Payload exceeds total store capacity")
+ with self._lock:
+ self._cleanup()
+ while self._size + len(payload) > self.max_total_bytes:
+ self._remove(next(iter(self._entries)))
+ key = uuid.uuid4().hex
+ self._entries[key] = entry
+ self._size += len(payload)
+ return key
+
+ async def get(self, key, *, owner):
+ with self._lock:
+ self._cleanup()
+ entry = self._entries.get(key) if _valid_key(key) else None
+ if entry is None or entry.owner != owner:
+ return None
+ self._entries.move_to_end(key)
+ return entry
+
+ async def delete(self, key, *, owner):
+ with self._lock:
+ entry = self._entries.get(key) if _valid_key(key) else None
+ if entry is None or entry.owner != owner:
+ return False
+ self._remove(key)
+ return True
+
+ async def cleanup_expired(self):
+ with self._lock:
+ return self._cleanup()
+
+
+class FileSpilloverStore(MemorySpilloverStore):
+ """Atomic disk store. Each root must be owned by one store instance/process.
+
+ Total capacity counts actual JSON file bytes, including base64 and metadata.
+ File operations run in worker threads; no background cleanup task is needed.
+ """
+
+ def __init__(self, root: str | Path, **kwargs):
+ super().__init__(**kwargs)
+ self.root = Path(root).resolve()
+ self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
+ self._cleanup_files()
+
+ def _path(self, key):
+ if not _valid_key(key):
+ raise ValueError("Invalid spillover ID")
+ path = self.root / f"{key}.json"
+ if path.is_symlink() or path.resolve().parent != self.root:
+ raise ValueError("Spillover path escapes storage root")
+ return path
+
+ def _read(self, path):
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ return SpilloverEntry(
+ base64.b64decode(raw["payload"], validate=True), raw["owner"],
+ raw["mime_type"], raw["expires_at"],
+ )
+
+ def _cleanup_files(self):
+ count = 0
+ for candidate in self.root.glob("*.json"):
+ if not _valid_key(candidate.stem):
+ continue
+ path = self._path(candidate.stem)
+ if self._read(path).expires_at <= time.time():
+ path.unlink()
+ count += 1
+ return count
+
+ def _put_file(self, payload, owner, mime_type, ttl_seconds):
+ entry = self._entry(payload, owner, mime_type, ttl_seconds)
+ encoded = json.dumps({
+ "payload": base64.b64encode(payload).decode("ascii"),
+ "owner": entry.owner, "mime_type": entry.mime_type,
+ "expires_at": entry.expires_at,
+ }).encode("utf-8")
+ with self._lock:
+ self._cleanup_files()
+ used = sum(self._path(p.stem).stat().st_size for p in self.root.glob("*.json")
+ if _valid_key(p.stem))
+ if used + len(encoded) > self.max_total_bytes:
+ raise ValueError("File store capacity exceeded")
+ key = uuid.uuid4().hex
+ target = self._path(key)
+ temporary = self.root / f"{key}.tmp"
+ try:
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(encoded)
+ temporary.replace(target)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return key
+
+ def _get_file(self, key, owner, delete=False):
+ with self._lock:
+ path = self._path(key)
+ self._cleanup_files()
+ if not path.exists():
+ return None
+ entry = self._read(path)
+ if entry.expires_at <= time.time():
+ path.unlink()
+ return None
+ if entry.owner != owner:
+ return None
+ if delete:
+ path.unlink()
+ return entry
+
+ async def put(self, payload, *, owner, mime_type, ttl_seconds=None):
+ return await asyncio.to_thread(self._put_file, payload, owner, mime_type, ttl_seconds)
+
+ async def get(self, key, *, owner):
+ return await asyncio.to_thread(self._get_file, key, owner)
+
+ async def delete(self, key, *, owner):
+ return await asyncio.to_thread(self._get_file, key, owner, True) is not None
+
+ async def cleanup_expired(self):
+ def cleanup():
+ with self._lock:
+ return self._cleanup_files()
+ return await asyncio.to_thread(cleanup)
diff --git a/nitrostack/core/log_emitter.py b/nitrostack/core/log_emitter.py
new file mode 100644
index 0000000..bee944a
--- /dev/null
+++ b/nitrostack/core/log_emitter.py
@@ -0,0 +1,193 @@
+"""Process-wide bridge from Python logging to tooling subscribers."""
+from __future__ import annotations
+
+import logging
+import queue
+import threading
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Callable
+
+
+DEFAULT_BUFFER_SIZE = 256
+_STANDARD_RECORD_FIELDS = frozenset(
+ logging.makeLogRecord({}).__dict__.keys()
+) | {"message", "asctime"}
+
+
+@dataclass(frozen=True)
+class LogRecord:
+ """A structured logging record delivered to tooling subscribers."""
+
+ level: str
+ levelno: int
+ message: str
+ timestamp: str
+ logger_name: str
+ extra: dict[str, Any]
+
+
+class _Subscriber:
+ def __init__(self, callback: Callable[[LogRecord], Any], max_buffer: int):
+ self.callback = callback
+ self.queue: queue.Queue[LogRecord | None] = queue.Queue(maxsize=max_buffer)
+ self.active = True
+ self.condition = threading.Condition()
+ self.callback_thread: int | None = None
+ self.thread = threading.Thread(target=self._deliver, daemon=True, name="nitrostack-log-subscriber")
+ self.thread.start()
+
+ def enqueue(self, record: LogRecord) -> None:
+ with self.condition:
+ if not self.active:
+ return
+ try:
+ self.queue.put_nowait(record)
+ except queue.Full:
+ # Preserve the newest logs when a subscriber cannot keep up.
+ try:
+ self.queue.get_nowait()
+ except queue.Empty:
+ pass
+ try:
+ self.queue.put_nowait(record)
+ except queue.Full:
+ pass
+
+ def unsubscribe(self) -> None:
+ with self.condition:
+ if not self.active:
+ return
+ self.active = False
+ while True:
+ try:
+ self.queue.get_nowait()
+ except queue.Empty:
+ break
+ self.queue.put_nowait(None)
+ if self.callback_thread != threading.get_ident():
+ while self.callback_thread is not None:
+ self.condition.wait()
+
+ def _deliver(self) -> None:
+ while True:
+ record = self.queue.get()
+ if record is None:
+ return
+ with self.condition:
+ if not self.active:
+ continue
+ self.callback_thread = threading.get_ident()
+ try:
+ self.callback(record)
+ except Exception:
+ # Subscriber code must not interfere with logging or peers.
+ continue
+ finally:
+ with self.condition:
+ self.callback_thread = None
+ self.condition.notify_all()
+
+
+class LogEmitter:
+ """Thread-safe subscription point for records from ``nitrostack`` loggers."""
+
+ def __init__(self, max_buffer: int = DEFAULT_BUFFER_SIZE):
+ if max_buffer < 1:
+ raise ValueError("max_buffer must be at least 1")
+ self._max_buffer = max_buffer
+ self._subscribers: set[_Subscriber] = set()
+ self._lock = threading.Lock()
+ self._installed_handlers: dict[str, logging.Handler] = {}
+ # Loggers to bridge while subscribers exist. A logger with
+ # ``propagate=False`` never reaches ``nitrostack``, so it needs its own.
+ self._bridged_loggers: set[str] = {"nitrostack"}
+
+ def subscribe(self, callback: Callable[[LogRecord], Any]) -> Callable[[], None]:
+ """Subscribe to records; return an idempotent function to stop delivery."""
+ subscriber = _Subscriber(callback, self._max_buffer)
+ with self._lock:
+ self._subscribers.add(subscriber)
+ # Only the process-wide emitter owns NitroStack logger wiring.
+ # Standalone emitters are connected explicitly with
+ # LogEmitterHandler, avoiding duplicate delivery from the shared
+ # ``nitrostack`` logger hierarchy.
+ if self is log_emitter:
+ self._install_handlers_locked()
+
+ def unsubscribe() -> None:
+ with self._lock:
+ self._subscribers.discard(subscriber)
+ if not self._subscribers:
+ self._remove_handlers_locked()
+ subscriber.unsubscribe()
+
+ return unsubscribe
+
+ def _publish(self, record: LogRecord) -> None:
+ with self._lock:
+ subscribers = tuple(self._subscribers)
+ for subscriber in subscribers:
+ subscriber.enqueue(record)
+
+ def _install_handlers_locked(self) -> None:
+ for logger_name in self._bridged_loggers:
+ self._install_handler_locked(logger_name)
+
+ def _install_handler_locked(self, logger_name: str) -> None:
+ if logger_name in self._installed_handlers:
+ return
+ logger = logging.getLogger(logger_name)
+ handler = LogEmitterHandler(self)
+ handler._nitrostack_log_emitter = True # type: ignore[attr-defined]
+ logger.addHandler(handler)
+ self._installed_handlers[logger_name] = handler
+
+ def _remove_handlers_locked(self) -> None:
+ for name, handler in self._installed_handlers.items():
+ logging.getLogger(name).removeHandler(handler)
+ handler.close()
+ self._installed_handlers.clear()
+
+
+class LogEmitterHandler(logging.Handler):
+ """Logging handler that publishes structured records to a ``LogEmitter``."""
+
+ def __init__(self, emitter: LogEmitter):
+ super().__init__(logging.NOTSET)
+ self.emitter = emitter
+
+ def emit(self, record: logging.LogRecord) -> None:
+ try:
+ timestamp = datetime.fromtimestamp(record.created, timezone.utc).isoformat()
+ extra = {
+ key: value
+ for key, value in record.__dict__.items()
+ if key not in _STANDARD_RECORD_FIELDS and not key.startswith("_")
+ }
+ self.emitter._publish(
+ LogRecord(
+ level=record.levelname,
+ levelno=record.levelno,
+ message=record.getMessage(),
+ timestamp=timestamp,
+ logger_name=record.name,
+ extra=extra,
+ )
+ )
+ except Exception:
+ self.handleError(record)
+
+
+log_emitter = LogEmitter()
+
+
+def install_log_handler(logger_name: str = "nitrostack") -> None:
+ """Bridge a logger to the global emitter whenever it has subscribers.
+
+ The name is remembered, so a later ``subscribe()`` still attaches to it.
+ """
+ with log_emitter._lock:
+ log_emitter._bridged_loggers.add(logger_name)
+ if log_emitter._subscribers:
+ log_emitter._install_handler_locked(logger_name)
diff --git a/nitrostack/core/mcp_server.py b/nitrostack/core/mcp_server.py
index b383ff2..35a3dae 100644
--- a/nitrostack/core/mcp_server.py
+++ b/nitrostack/core/mcp_server.py
@@ -8,9 +8,20 @@
from typing import Any, Callable, Dict, Optional
import mcp.types as types
+from mcp import MCPError
from mcp.server.lowlevel import Server as LowLevelServer
from mcp.server.lowlevel.server import NotificationOptions
from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler
+from nitrostack.protocol.errors import JsonRpcErrorCode
+from nitrostack.protocol.deprecated import deprecated_method_message, rejects_deprecated_method
+from nitrostack.protocol.version import (
+ MODERN_PROTOCOL_VERSION,
+ ProtocolEra,
+ supports_resource_subscriptions,
+ supported_protocol_versions_for_era,
+)
+from nitrostack.protocol.meta import flatten_request_meta_object
+from nitrostack.protocol.jsonrpc import HeaderBodyMismatchError, validate_protocol_version_header_meta
class NitroStackMcpServer(LowLevelServer):
@@ -29,27 +40,63 @@ def __init__(self, name: str, version: Optional[str] = None):
name=name,
version=version or "",
on_subscriptions_listen=self.listen_handler,
+ on_ping=self._handle_ping,
)
self.has_task_support: bool = False
self.http_engine: Optional[str] = None
self.sessionful: bool = False
- self.discover_handler: Optional[Callable[[], dict[str, Any]]] = None
- self.initialize_handler: Optional[Callable[[Optional[str]], dict[str, Any]]] = None
+ self.protocol_era: Optional[ProtocolEra] = None
+ self.middleware.append(self._enforce_protocol_era)
# In-process tests still look up handlers by request type.
self.request_handlers: Dict[Any, Callable[..., Any]] = {}
self.notification_handlers: Dict[Any, Callable[..., Any]] = {}
- def handle_server_discover(self) -> dict[str, Any]:
- """Answer ``server/discover`` from this server instance."""
- if self.discover_handler is None:
- raise RuntimeError("server/discover is not configured on this server")
- return self.discover_handler()
+ async def _enforce_protocol_era(self, context, call_next):
+ """Apply era policy inside the official runner, after its JSON-RPC parsing."""
+ if (
+ context.protocol_version == MODERN_PROTOCOL_VERSION
+ and rejects_deprecated_method(context.method, "modern")
+ ):
+ raise MCPError(types.METHOD_NOT_FOUND, deprecated_method_message(context.method))
+ if self.protocol_era == "modern" and context.method in (
+ "initialize", "notifications/initialized",
+ ):
+ raise MCPError(types.METHOD_NOT_FOUND, f"Method not found: {context.method}")
+ request_headers = getattr(getattr(context, "request", None), "headers", {})
+ meta = flatten_request_meta_object(context.meta)
+ header_version = request_headers.get("mcp-protocol-version")
+ meta_version = meta.get("io.modelcontextprotocol/protocolVersion")
+ if (
+ meta_version == MODERN_PROTOCOL_VERSION
+ and context.request is not None
+ and not header_version
+ ):
+ raise MCPError(
+ int(JsonRpcErrorCode.HEADER_BODY_MISMATCH),
+ "MCP-Protocol-Version header is required",
+ )
+ try:
+ validate_protocol_version_header_meta(header_version, meta_version)
+ except HeaderBodyMismatchError as exc:
+ raise MCPError(int(exc.code), exc.message) from None
+ claimed_version = header_version or meta_version
+ # The official SDK uses a 2025-03-26 default when a legacy-compatible
+ # HTTP request omits the header. Do not reject that implicit fallback.
+ unsupported_claim = self.protocol_era is not None and claimed_version and (
+ claimed_version not in supported_protocol_versions_for_era(self.protocol_era)
+ )
+ modern_legacy_request = (
+ self.protocol_era == "modern" and context.protocol_version != MODERN_PROTOCOL_VERSION
+ )
+ if unsupported_claim or modern_legacy_request:
+ raise MCPError(int(JsonRpcErrorCode.UNSUPPORTED_PROTOCOL_VERSION), "Unsupported protocol version")
+ return await call_next(context)
- def handle_sessionless_initialize(self, requested_version: Optional[str] = None) -> dict[str, Any]:
- """Answer sessionless ``initialize`` from this server instance."""
- if self.initialize_handler is None:
- raise RuntimeError("sessionless initialize is not configured on this server")
- return self.initialize_handler(requested_version)
+ async def _handle_ping(self, _context, _params):
+ """Keep the official ping hook only for the legacy protocol era."""
+ if self.protocol_era != "legacy":
+ raise MCPError(types.METHOD_NOT_FOUND, "Method not found: ping")
+ return types.EmptyResult()
def get_capabilities(
self,
@@ -67,7 +114,7 @@ def get_capabilities(
)
if caps.resources is not None:
- caps.resources.subscribe = True
+ caps.resources.subscribe = supports_resource_subscriptions(self.protocol_era)
if self.has_task_support:
caps.tasks = types.ServerTasksCapability(
diff --git a/nitrostack/core/pipeline.py b/nitrostack/core/pipeline.py
index 6bc5091..929b6df 100644
--- a/nitrostack/core/pipeline.py
+++ b/nitrostack/core/pipeline.py
@@ -40,7 +40,7 @@ def decorator(func: Callable):
return func
return decorator
-def use_interceptors(*interceptors: Type[Interceptor]):
+def use_interceptors(*interceptors: Type[Interceptor] | Interceptor):
def decorator(func: Callable):
func._mcp_interceptors = getattr(func, "_mcp_interceptors", []) + list(interceptors)
return func
@@ -204,7 +204,7 @@ async def run_pipeline(
context: ExecutionContext,
guards: List[Type[Guard]],
middleware: List[Type[Middleware]],
- interceptors: List[Type[Interceptor]],
+ interceptors: List[Type[Interceptor] | Interceptor],
pipes: List[Type[Pipe]],
filters: List[Type[ExceptionFilter]],
param_name: str = "input",
@@ -216,6 +216,17 @@ async def run_pipeline(
container = DIContainer.get_instance()
async def execute_handler_flow():
+ if args:
+ value = args[0]
+ if hasattr(value, "model_dump"):
+ context.input = value.model_dump(mode="json", by_alias=True)
+ elif isinstance(value, dict):
+ context.input = dict(value)
+ else:
+ context.input = {"value": value}
+ else:
+ context.input = {}
+
# 1. Run Guards
for guard_cls in guards:
guard = container.resolve(guard_cls)
@@ -248,7 +259,10 @@ async def call_target():
# Middleware -> Interceptors -> Handler
current_next = call_target
for interceptor_cls in reversed(interceptors):
- interceptor = container.resolve(interceptor_cls)
+ interceptor = (
+ container.resolve(interceptor_cls)
+ if isinstance(interceptor_cls, type) else interceptor_cls
+ )
def make_interceptor_next(nxt, icpt=interceptor):
return lambda: icpt.intercept(context, nxt)
diff --git a/nitrostack/core/visibility.py b/nitrostack/core/visibility.py
new file mode 100644
index 0000000..529dfbe
--- /dev/null
+++ b/nitrostack/core/visibility.py
@@ -0,0 +1,111 @@
+"""Per-session tool visibility with bounded TTL/LRU state."""
+
+from __future__ import annotations
+
+import time
+from collections import OrderedDict
+from dataclasses import dataclass, field
+from threading import RLock
+from typing import Callable, Iterable
+
+
+@dataclass
+class _SessionVisibility:
+ expires_at: float
+ overrides: dict[str, bool] = field(default_factory=dict)
+
+
+class SessionVisibilityStore:
+ """Thread-safe TTL/LRU storage for tool visibility overrides."""
+
+ def __init__(
+ self,
+ *,
+ ttl_seconds: float = 3600,
+ max_entries: int = 10_000,
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ if ttl_seconds <= 0 or max_entries <= 0:
+ raise ValueError("ttl_seconds and max_entries must be positive")
+ self.ttl_seconds = ttl_seconds
+ self.max_entries = max_entries
+ self._clock = clock
+ self._entries: OrderedDict[tuple[str, str], _SessionVisibility] = OrderedDict()
+ self._lock = RLock()
+
+ def _expire(self, now: float) -> None:
+ for key, entry in list(self._entries.items()):
+ if entry.expires_at <= now:
+ del self._entries[key]
+
+ def _get(self, key: tuple[str, str], now: float) -> _SessionVisibility:
+ self._expire(now)
+ entry = self._entries.get(key)
+ if entry is None:
+ entry = _SessionVisibility(now + self.ttl_seconds)
+ self._entries[key] = entry
+ else:
+ self._entries.move_to_end(key)
+ entry.expires_at = now + self.ttl_seconds
+ while len(self._entries) > self.max_entries:
+ self._entries.popitem(last=False)
+ return entry
+
+ def is_visible(self, key: tuple[str, str], name: str, default: bool) -> bool:
+ with self._lock:
+ return self._get(key, self._clock()).overrides.get(name, default)
+
+ def update(self, key: tuple[str, str], names: Iterable[str], visible: bool) -> bool:
+ changed = False
+ with self._lock:
+ entry = self._get(key, self._clock())
+ for name in names:
+ if entry.overrides.get(name) != visible:
+ entry.overrides[name] = visible
+ changed = True
+ return changed
+
+
+class VisibilityTransform:
+ """Apply decorator defaults and per-session tool visibility overrides."""
+
+ def __init__(self, store: SessionVisibilityStore | None = None) -> None:
+ self.store = store or SessionVisibilityStore()
+
+ @staticmethod
+ def session_key(
+ transport_session_id: str | None,
+ verified_subject: str | None,
+ ) -> tuple[str, str] | None:
+ if not transport_session_id:
+ return None
+ return transport_session_id, verified_subject or ""
+
+ def is_visible(self, entry: object, key: tuple[str, str] | None) -> bool:
+ config = getattr(entry, "config")
+ default = config.default_visible
+ if default is None:
+ default = config.visibility == "visible"
+ if key is None:
+ return default
+ return self.store.is_visible(key, config.name, default)
+
+ def update(self, key: tuple[str, str], names: Iterable[str], visible: bool) -> bool:
+ """Update known tool names for a specific visibility key."""
+ return self.store.update(key, names, visible)
+
+ def change(self, context: object, names: Iterable[str], *, visible: bool) -> bool:
+ key = getattr(context, "_visibility_session_key", None)
+ if key is None:
+ getattr(context, "logger").warn(
+ "Tool visibility changes require a sessionful transport session"
+ )
+ return False
+ app = getattr(context, "_visibility_app")
+ valid: list[str] = []
+ for name in names:
+ if name not in app._tools:
+ getattr(context, "logger").warn(f"Unknown tool name in visibility change: {name}")
+ continue
+ valid.append(name)
+ return self.store.update(key, valid, visible) if valid else False
diff --git a/nitrostack/protocol/__init__.py b/nitrostack/protocol/__init__.py
index 86dad4b..40a02d7 100644
--- a/nitrostack/protocol/__init__.py
+++ b/nitrostack/protocol/__init__.py
@@ -14,32 +14,22 @@
from nitrostack.protocol.deprecated import deprecated_method_message, rejects_deprecated_method
from nitrostack.protocol.method_contract import (
DEPRECATED_MODERN_METHODS,
- MODERN_METHOD_CONTRACTS,
- MethodContract,
- contract_for,
- mcp_method_is_required,
- mcp_name_field,
- mcp_name_is_required,
)
from nitrostack.protocol.discovery import (
DISCOVER_RESULT_TYPE,
- INITIALIZE_METHOD,
SERVER_DISCOVER_METHOD,
build_discover_result,
- build_sessionless_initialize_result,
)
from nitrostack.protocol.errors import ERROR_CODE_MESSAGES, JsonRpcErrorCode
from nitrostack.protocol.extensions import MCPExtensionId
from nitrostack.protocol.jsonrpc import (
JsonRpcWireError,
- build_ping_response,
build_tool_error_result,
jsonrpc_error,
jsonrpc_success,
map_exception_to_jsonrpc,
parse_jsonrpc_request,
)
-from nitrostack.protocol.layers import RuntimeLayer
from nitrostack.protocol.cache_hints import (
build_list_endpoint_cache_hint_meta,
resolve_resource_cache_hint_meta,
@@ -136,7 +126,6 @@
"supported_protocol_versions_for_era",
"wire_mode_for_era",
"MCPExtensionId",
- "RuntimeLayer",
"LEGACY_SESSION_HEADER",
"MAX_CIMD_BYTES",
"MAX_SCHEMA_DEPTH",
@@ -154,19 +143,10 @@
"deprecated_method_message",
"rejects_deprecated_method",
"DEPRECATED_MODERN_METHODS",
- "MODERN_METHOD_CONTRACTS",
- "MethodContract",
- "contract_for",
- "mcp_method_is_required",
- "mcp_name_field",
- "mcp_name_is_required",
"DISCOVER_RESULT_TYPE",
- "INITIALIZE_METHOD",
"SERVER_DISCOVER_METHOD",
- "build_sessionless_initialize_result",
"build_discover_result",
"parse_jsonrpc_request",
- "build_ping_response",
"jsonrpc_success",
"jsonrpc_error",
"build_tool_error_result",
diff --git a/nitrostack/protocol/discovery.py b/nitrostack/protocol/discovery.py
index d15fc0a..2d696ae 100644
--- a/nitrostack/protocol/discovery.py
+++ b/nitrostack/protocol/discovery.py
@@ -10,19 +10,10 @@
from nitrostack.protocol.cache_hints import DEFAULT_LIST_CACHE_TTL_MS, build_list_endpoint_cache_hint_meta
from nitrostack.protocol.extensions import MCPExtensionId
-from nitrostack.protocol.version import (
- LEGACY_PROTOCOL_VERSION,
- MODERN_PROTOCOL_VERSION,
- SUPPORTED_PROTOCOL_VERSIONS,
-)
+from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS
SERVER_DISCOVER_METHOD = "server/discover"
DISCOVER_RESULT_TYPE = "complete"
-INITIALIZE_METHOD = "initialize"
-INITIALIZED_NOTIFICATION = "notifications/initialized"
-_SESSIONLESS_INITIALIZE_VERSIONS = frozenset(
- {LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION, "2025-11-25"}
-)
def build_discover_result(
@@ -31,16 +22,22 @@ def build_discover_result(
server_version: str,
protocol_version: str = MODERN_PROTOCOL_VERSION,
supported_versions: Optional[tuple[str, ...]] = None,
- advertise_tasks: bool = True,
+ advertise_tasks: bool = False,
advertise_app: bool = False,
custom_extensions: Optional[dict[str, str]] = None,
tools_list_changed: bool = True,
resources_list_changed: bool = True,
+ resources_subscribe: bool = False,
prompts_list_changed: bool = True,
ttl_ms: int = DEFAULT_LIST_CACHE_TTL_MS,
cache_scope: Literal["public", "private"] = "private",
) -> dict[str, Any]:
- """Build the ``server/discover`` result for the mounted HTTP engine."""
+ """Build the ``server/discover`` result for the mounted HTTP engine.
+
+ ``resources_subscribe`` must match ``NitroStackMcpServer.get_capabilities``
+ for the same era, so ``server/discover`` and real capability negotiation
+ never disagree on ``resources.subscribe``.
+ """
versions = list(supported_versions or SUPPORTED_PROTOCOL_VERSIONS)
extensions: dict[str, dict[str, str]] = {}
if advertise_app:
@@ -48,57 +45,30 @@ def build_discover_result(
if advertise_tasks:
extensions[MCPExtensionId.TASKS.value] = {"version": protocol_version}
for extension_id, version in (custom_extensions or {}).items():
- if extension_id and version:
+ if extension_id and version and (extension_id != MCPExtensionId.TASKS.value or advertise_tasks):
extensions[str(extension_id)] = {"version": str(version)}
capabilities: dict[str, Any] = {
"tools": {"listChanged": tools_list_changed},
- "resources": {"subscribe": False, "listChanged": resources_list_changed},
+ "resources": {"subscribe": resources_subscribe, "listChanged": resources_list_changed},
"prompts": {"listChanged": prompts_list_changed},
}
if extensions:
capabilities["extensions"] = extensions
+ server_info = {"name": server_name, "version": server_version}
+ # 2026-07-28 requires `serverInfo` on the result `_meta`; the top-level
+ # copy stays for `auto`/legacy clients that read it from the body.
+ meta = build_list_endpoint_cache_hint_meta(ttl_ms=ttl_ms, cache_scope=cache_scope)
+ meta["serverInfo"] = server_info
+
return {
"resultType": DISCOVER_RESULT_TYPE,
"protocolVersion": protocol_version,
"supportedVersions": versions,
- "serverInfo": {"name": server_name, "version": server_version},
+ "serverInfo": server_info,
"capabilities": capabilities,
"ttlMs": ttl_ms,
"cacheScope": cache_scope,
- "_meta": build_list_endpoint_cache_hint_meta(ttl_ms=ttl_ms, cache_scope=cache_scope),
- }
-
-
-def build_sessionless_initialize_result(
- *,
- server_name: str,
- server_version: str,
- requested_version: Optional[str] = None,
- protocol_version: str = MODERN_PROTOCOL_VERSION,
- advertise_tasks: bool = True,
- advertise_app: bool = False,
- custom_extensions: Optional[dict[str, str]] = None,
-) -> dict[str, Any]:
- """
- Initialize-shaped result for era ``auto`` with no session.
-
- Official v2 ``legacy: 'stateless'`` is not mounted yet. This adapter
- answers 2025 ``initialize`` on the same engine as ``server/discover``.
- """
- requested = (requested_version or "").strip()
- negotiated = requested if requested in _SESSIONLESS_INITIALIZE_VERSIONS else protocol_version
- discovered = build_discover_result(
- server_name=server_name,
- server_version=server_version,
- protocol_version=protocol_version,
- advertise_tasks=advertise_tasks,
- advertise_app=advertise_app,
- custom_extensions=custom_extensions,
- )
- return {
- "protocolVersion": negotiated,
- "capabilities": discovered["capabilities"],
- "serverInfo": discovered["serverInfo"],
+ "_meta": meta,
}
diff --git a/nitrostack/protocol/errors.py b/nitrostack/protocol/errors.py
index 09d4bb0..5429260 100644
--- a/nitrostack/protocol/errors.py
+++ b/nitrostack/protocol/errors.py
@@ -12,6 +12,7 @@ class JsonRpcErrorCode(IntEnum):
INVALID_PARAMS = -32602
INTERNAL_ERROR = -32603
HEADER_BODY_MISMATCH = -32020
+ MISSING_REQUIRED_CLIENT_CAPABILITY = -32021
UNSUPPORTED_PROTOCOL_VERSION = -32022
@@ -22,5 +23,6 @@ class JsonRpcErrorCode(IntEnum):
JsonRpcErrorCode.INVALID_PARAMS: "Invalid params",
JsonRpcErrorCode.INTERNAL_ERROR: "Internal error",
JsonRpcErrorCode.HEADER_BODY_MISMATCH: "Header/body mismatch",
+ JsonRpcErrorCode.MISSING_REQUIRED_CLIENT_CAPABILITY: "Missing required client capability",
JsonRpcErrorCode.UNSUPPORTED_PROTOCOL_VERSION: "Unsupported protocol version",
}
diff --git a/nitrostack/protocol/jsonrpc.py b/nitrostack/protocol/jsonrpc.py
index 24239e2..010f353 100644
--- a/nitrostack/protocol/jsonrpc.py
+++ b/nitrostack/protocol/jsonrpc.py
@@ -129,82 +129,6 @@ def jsonrpc_method_from_body(raw_body: Optional[bytes]) -> Optional[str]:
return None
-def validate_header_body_method(header_method: Optional[str], body_method: str) -> None:
- """SEP-2243: reject when Mcp-Method header mirrors a different JSON-RPC method."""
- if header_method is None:
- return
- if header_method != body_method:
- raise HeaderBodyMismatchError(
- f"Mcp-Method header '{header_method}' does not match body method '{body_method}'"
- )
-
-
-def validate_header_body_name(
- header_name: Optional[str],
- body_name: Optional[str],
-) -> None:
- """SEP-2243: reject when Mcp-Name header mirrors a different resource/tool name."""
- if header_name is None or body_name is None:
- return
- if header_name != body_name:
- raise HeaderBodyMismatchError(
- f"Mcp-Name header '{header_name}' does not match body name '{body_name}'"
- )
-
-
-REQUIRED_MCP_NAME_MESSAGE = "Mcp-Name header is required"
-REQUIRED_MCP_METHOD_MESSAGE = "Mcp-Method header is required"
-
-
-def validate_required_header_body(
- header_value: Optional[str],
- body_value: Optional[str],
- *,
- header_name: str,
- body_label: str,
- required_message: str,
-) -> None:
- """Require a header and match it to the JSON-RPC body field exactly."""
- header = header_value.strip() if isinstance(header_value, str) else ""
- body = body_value.strip() if isinstance(body_value, str) else ""
- if not header or not body:
- raise HeaderBodyMismatchError(required_message)
- if header != body:
- raise HeaderBodyMismatchError(
- f"{header_name} header '{header_value}' does not match body {body_label} '{body_value}'"
- )
-
-
-def validate_required_mcp_name(
- header_name: Optional[str],
- body_name: Optional[str],
- *,
- body_label: str = "name",
-) -> None:
- """Require ``Mcp-Name`` and match the body name or URI exactly."""
- validate_required_header_body(
- header_name,
- body_name,
- header_name="Mcp-Name",
- body_label=body_label,
- required_message=REQUIRED_MCP_NAME_MESSAGE,
- )
-
-
-def validate_required_mcp_method(
- header_method: Optional[str],
- body_method: Optional[str],
-) -> None:
- """Require ``Mcp-Method`` and match JSON-RPC ``method`` exactly."""
- validate_required_header_body(
- header_method,
- body_method,
- header_name="Mcp-Method",
- body_label="method",
- required_message=REQUIRED_MCP_METHOD_MESSAGE,
- )
-
-
def validate_protocol_version_header_meta(
header_version: Optional[str],
meta_version: Optional[str],
@@ -239,11 +163,6 @@ def jsonrpc_error(request_id: Any, code: int, message: str, data: Any = None) ->
return {"jsonrpc": JSONRPC_VERSION, "id": request_id, "error": error}
-def build_ping_response(request_id: Any) -> dict[str, Any]:
- """Ping fast path."""
- return jsonrpc_success(request_id, {})
-
-
def build_tool_error_result(message: str, *, text_type: str = "text") -> dict[str, Any]:
"""
Tool business failure — JSON-RPC success with isError: true.
diff --git a/nitrostack/protocol/layers.py b/nitrostack/protocol/layers.py
deleted file mode 100644
index 7f30a65..0000000
--- a/nitrostack/protocol/layers.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""Runtime layer identifiers for the MCP 2026-07-28 architecture."""
-
-from enum import Enum
-
-
-class RuntimeLayer(str, Enum):
- """Decoupled layers of the NitroStack stateless MCP runtime."""
-
- TRANSPORT_SECURITY = "transport_security"
- PROTOCOL_DISPATCHER = "protocol_dispatcher"
- REGISTRIES = "registries"
- TASK_MANAGEMENT = "task_management"
diff --git a/nitrostack/protocol/method_contract.py b/nitrostack/protocol/method_contract.py
index b9142ab..39c908c 100644
--- a/nitrostack/protocol/method_contract.py
+++ b/nitrostack/protocol/method_contract.py
@@ -1,82 +1,12 @@
-"""SEP-2243 method contracts for the 2026 method surface.
+"""Methods retired from the 2026-07-28 wire.
-Official v2 owns this table once mounted. Until then the sidecar validator
-reads one row per method: required ``Mcp-Method``, optional ``Mcp-Name`` field,
-and whether ``auto`` requires the method header.
+SEP-2243 header enforcement belongs to the official MCP transport.
+This module keeps only the shared retirement policy used by handlers.
"""
from __future__ import annotations
-from dataclasses import dataclass
-from typing import Optional
-
-from nitrostack.protocol.version import ProtocolEra, WireMode
-
-NAME_FIELD_NAME = "name"
-NAME_FIELD_URI = "uri"
-
-
-@dataclass(frozen=True)
-class MethodContract:
- """Header contract for one JSON-RPC method."""
-
- method: str
- name_field: Optional[str] = None
- # ``auto`` keeps handshake / ping / discover optional (2025 clients).
- # ``modern`` requires ``Mcp-Method`` on every JSON-RPC POST.
- requires_method_header: bool = True
-
-
-def _contract(
- method: str,
- *,
- name_field: Optional[str] = None,
- requires_method_header: bool = True,
-) -> MethodContract:
- return MethodContract(
- method=method,
- name_field=name_field,
- requires_method_header=requires_method_header,
- )
-
-
-MODERN_METHOD_CONTRACTS: tuple[MethodContract, ...] = (
- _contract("ping", requires_method_header=False),
- _contract("initialize", requires_method_header=False),
- _contract("notifications/initialized", requires_method_header=False),
- _contract("notifications/cancelled"),
- _contract("notifications/progress"),
- _contract("server/discover", requires_method_header=False),
- _contract("subscriptions/listen"),
- _contract("notifications/subscriptions/acknowledged"),
- _contract("tools/list", requires_method_header=False),
- _contract("tools/call", name_field=NAME_FIELD_NAME, requires_method_header=False),
- _contract("notifications/tools/list_changed"),
- _contract("resources/list", requires_method_header=False),
- _contract("resources/templates/list", requires_method_header=False),
- _contract("resources/read", name_field=NAME_FIELD_URI),
- _contract("resources/subscribe", name_field=NAME_FIELD_URI),
- _contract("resources/unsubscribe", name_field=NAME_FIELD_URI),
- _contract("notifications/resources/list_changed"),
- _contract("notifications/resources/updated"),
- _contract("prompts/list", requires_method_header=False),
- _contract("prompts/get", name_field=NAME_FIELD_NAME),
- _contract("notifications/prompts/list_changed"),
- _contract("completion/complete"),
- _contract("tasks/get"),
- _contract("tasks/cancel"),
- _contract("tasks/result"),
- _contract("tasks/list"),
- _contract("logging/setLevel"),
-)
-
-_CONTRACTS_BY_METHOD: dict[str, MethodContract] = {
- row.method: row for row in MODERN_METHOD_CONTRACTS
-}
-
-NAME_SCOPED_METHODS: frozenset[str] = frozenset(
- row.method for row in MODERN_METHOD_CONTRACTS if row.name_field
-)
+from nitrostack.protocol.version import ProtocolEra
# 2025 methods removed from the 2026-07-28 wire. Handshake methods
# (``initialize``, ``notifications/initialized``) are not in this table:
@@ -95,7 +25,7 @@ def _contract(
}
-def deprecated_method_message(method: str) -> Optional[str]:
+def deprecated_method_message(method: str) -> str | None:
"""Return the modern-wire rejection text when ``method`` is retired."""
return DEPRECATED_MODERN_METHODS.get(method)
@@ -103,33 +33,3 @@ def deprecated_method_message(method: str) -> Optional[str]:
def rejects_deprecated_method(method: str, era: ProtocolEra) -> bool:
"""True when era ``modern`` must answer ``method`` as not found."""
return era == "modern" and method in DEPRECATED_MODERN_METHODS
-
-
-def contract_for(method: str) -> Optional[MethodContract]:
- """Return the table row for ``method``, or ``None`` when unlisted."""
- return _CONTRACTS_BY_METHOD.get(method)
-
-
-def mcp_name_field(method: str) -> Optional[str]:
- """Body field mirrored by ``Mcp-Name``, if this method is name-scoped."""
- row = contract_for(method)
- return row.name_field if row is not None else None
-
-
-def mcp_name_is_required(method: str) -> bool:
- """``Mcp-Name`` is required on ``tools/call``, ``resources/read``, ``prompts/get``."""
- return mcp_name_field(method) is not None and method in {
- "tools/call",
- "resources/read",
- "prompts/get",
- }
-
-
-def mcp_method_is_required(method: str, wire_mode: WireMode) -> bool:
- """``modern`` requires ``Mcp-Method`` on every POST. ``auto`` follows the table."""
- if wire_mode == "reject":
- return True
- row = contract_for(method)
- if row is None:
- return False
- return row.requires_method_header
diff --git a/nitrostack/protocol/version.py b/nitrostack/protocol/version.py
index 24cf3f0..93d2828 100644
--- a/nitrostack/protocol/version.py
+++ b/nitrostack/protocol/version.py
@@ -207,6 +207,11 @@ def needs_sessionful_engine(era: ProtocolEra) -> bool:
return era == "legacy"
+def supports_resource_subscriptions(era: Optional[ProtocolEra]) -> bool:
+ """Only the legacy compatibility era serves resource subscriptions."""
+ return era == "legacy"
+
+
def http_engine_for_era(era: ProtocolEra) -> HttpEngine:
"""
Select the /mcp HTTP engine for an era.
diff --git a/nitrostack/runtime/acceptance.py b/nitrostack/runtime/acceptance.py
deleted file mode 100644
index 17992ed..0000000
--- a/nitrostack/runtime/acceptance.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""MCP 2026-07-28 feature-area and acceptance-criteria registry."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from enum import IntEnum
-from typing import Iterable
-
-from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION
-
-
-class ProtocolArea(IntEnum):
- """Major MCP 2026-07-28 implementation areas."""
-
- CORE_JSONRPC = 1
- STATELESS_HTTP = 2
- REGISTRIES_SCHEMA = 3
- ASYNC_TASKS = 4
- MULTI_TENANT = 5
- OAUTH_CIMD = 6
- MRTR_OBSERVABILITY = 7
-
-
-@dataclass(frozen=True)
-class ProtocolDeliverable:
- area: ProtocolArea
- item: str
- test_module: str
-
-
-@dataclass(frozen=True)
-class AcceptanceCriterion:
- key: str
- description: str
- test_module: str
-
-
-PROTOCOL_DELIVERABLES: tuple[ProtocolDeliverable, ...] = (
- ProtocolDeliverable(
- ProtocolArea.CORE_JSONRPC,
- "JSON-RPC error code hierarchy (-32700..-32603, -32020)",
- "tests/test_mcp20_jsonrpc_wire.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.CORE_JSONRPC,
- "SEP-2164 missing resource returns -32602",
- "tests/test_mcp20_contracts.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.CORE_JSONRPC,
- "Reject tasks/result and tasks/list on modern wire",
- "tests/test_mcp20_tasks.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.CORE_JSONRPC,
- "Deprecated methods share one policy on every modern route",
- "tests/test_mcp20_deprecated.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.CORE_JSONRPC,
- "Strip envelope keys from tool arguments before handlers",
- "tests/test_mcp20_tool_args.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.STATELESS_HTTP,
- "POST /mcp stateless ingress without Mcp-Session-Id",
- "tests/test_mcp20_stateless_http.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.STATELESS_HTTP,
- "server/discover and ping fast path",
- "tests/test_mcp20_stateless_http.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.STATELESS_HTTP,
- "CORS headers for MCP preflight",
- "tests/test_mcp20_stateless_http.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.STATELESS_HTTP,
- "GET /subscriptions/listen SSE attach on modern and auto",
- "tests/test_mcp20_subscriptions.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.STATELESS_HTTP,
- "Concurrent identical JSON-RPC ids stay isolated",
- "tests/test_mcp20_concurrency.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.STATELESS_HTTP,
- "Official mcp 2.x stdio follows the active era",
- "tests/test_mcp20_stdio.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.REGISTRIES_SCHEMA,
- "JSON Schema 2020-12 with depth bounding (max 64)",
- "tests/test_mcp20_contracts.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.REGISTRIES_SCHEMA,
- "Resource URI templates and resolution",
- "tests/test_mcp20_contracts.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.ASYNC_TASKS,
- "Task state machine and tasks/get embedded result",
- "tests/test_mcp20_tasks.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.ASYNC_TASKS,
- "Pluggable TaskStore and terminal-only TTL eviction",
- "tests/test_mcp20_task_store.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.MULTI_TENANT,
- "TaskAccessContext isolation and anti-enumeration",
- "tests/test_mcp20_task_authorization.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.OAUTH_CIMD,
- "CIMD resolver with SSRF defenses and RFC 9207 iss",
- "tests/test_mcp20_oauth_cimd.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.MRTR_OBSERVABILITY,
- "MRTR input_required elicitation helpers",
- "tests/test_mcp20_mrtr.py",
- ),
- ProtocolDeliverable(
- ProtocolArea.MRTR_OBSERVABILITY,
- "Extensions map, trace context, and cache hints",
- "tests/test_mcp20_extensions_cache_observability.py",
- ),
-)
-
-ACCEPTANCE_CRITERIA: tuple[AcceptanceCriterion, ...] = (
- AcceptanceCriterion(
- "stateless",
- "No Mcp-Session-Id emitted; stateless POST /mcp works",
- "tests/test_mcp20_blueprint.py",
- ),
- AcceptanceCriterion(
- "task_conformance",
- "Task-augmented tools/call returns immediate TaskData",
- "tests/test_mcp20_tasks.py",
- ),
- AcceptanceCriterion(
- "task_cancellation",
- "tasks/cancel marks cancelled; terminal cancel returns -32602",
- "tests/test_mcp20_tasks.py",
- ),
- AcceptanceCriterion(
- "ttl_safety",
- "Active tasks never evicted; terminal TTL from lastUpdatedAt",
- "tests/test_mcp20_task_store.py",
- ),
- AcceptanceCriterion(
- "multi_tenant",
- "Cross-tenant access returns TaskNotFoundError / -32602",
- "tests/test_mcp20_task_authorization.py",
- ),
- AcceptanceCriterion(
- "ssrf_security",
- "CIMD blocks special-use IPs and oversized payloads",
- "tests/test_mcp20_oauth_cimd.py",
- ),
- AcceptanceCriterion(
- "error_parity",
- "JSON-RPC codes match specification including SEP-2164",
- "tests/test_mcp20_jsonrpc_wire.py",
- ),
- AcceptanceCriterion(
- "automated_tests",
- "pytest suite covers all seven protocol areas",
- "tests/test_mcp20_acceptance.py",
- ),
-)
-
-MCP20_TEST_MODULES: tuple[str, ...] = tuple(
- sorted({d.test_module for d in PROTOCOL_DELIVERABLES} | {c.test_module for c in ACCEPTANCE_CRITERIA})
-)
-
-
-def deliverables_for_area(area: ProtocolArea) -> tuple[ProtocolDeliverable, ...]:
- return tuple(item for item in PROTOCOL_DELIVERABLES if item.area == area)
-
-
-def protocol_coverage_complete() -> bool:
- """True when every protocol area has at least one mapped deliverable."""
- return all(deliverables_for_area(area) for area in ProtocolArea)
-
-
-def acceptance_criteria_registered() -> bool:
- return len(ACCEPTANCE_CRITERIA) >= 8
-
-
-def modern_protocol_target() -> str:
- return MODERN_PROTOCOL_VERSION
-
-
-def iter_area_summary() -> Iterable[str]:
- for area in ProtocolArea:
- items = deliverables_for_area(area)
- yield f"Area {area.value}: {len(items)} deliverable(s)"
diff --git a/nitrostack/runtime/caller.py b/nitrostack/runtime/caller.py
new file mode 100644
index 0000000..5e2e043
--- /dev/null
+++ b/nitrostack/runtime/caller.py
@@ -0,0 +1,63 @@
+"""One place that decides who is calling.
+
+Transforms, task access and guards must agree on the caller's identity, so the
+rules live here instead of being re-derived per feature.
+
+* ``subject`` is the ``sub`` of a verified bearer token. Unsigned ``userId``
+ fields and ``_meta`` claims are never identity.
+* ``session_id`` only means something on the sessionful (``legacy``) wire.
+ Sessionless eras mint no durable session, so none is reported there.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional, Tuple
+
+from nitrostack.auth.request import authorization_token_from_request, verify_bearer_payload
+from nitrostack.protocol.constants import LEGACY_SESSION_HEADER
+from nitrostack.protocol.version import wire_mode_for_era
+
+
+def session_id_from_request_context(rc: Any) -> Optional[str]:
+ direct = getattr(rc, "session_id", None)
+ if direct:
+ return str(direct)
+ session = getattr(rc, "session", None)
+ session_id = getattr(session, "id", None) or getattr(session, "session_id", None)
+ if session_id:
+ return str(session_id)
+ # The session manager only routes a request whose Mcp-Session-Id names a
+ # live session it issued, so on the sessionful wire the header is the id.
+ headers = getattr(rc, "headers", None) or getattr(getattr(rc, "request", None), "headers", None)
+ if headers is not None:
+ try:
+ header = headers.get(LEGACY_SESSION_HEADER) or headers.get(LEGACY_SESSION_HEADER.lower())
+ except Exception:
+ header = None
+ if header:
+ return str(header)
+ return None
+
+
+def verified_claims(rc: Any) -> Optional[dict]:
+ """Claims of the verified bearer token, ``None`` if absent or invalid."""
+ if rc is None:
+ return None
+ token = authorization_token_from_request(rc)
+ if not token:
+ return None
+ return verify_bearer_payload(token)
+
+
+def caller_identity(rc: Any, era: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:
+ """Return ``(session_id, subject)`` for the request in ``rc``."""
+ if rc is None:
+ return None, None
+ session_id = session_id_from_request_context(rc)
+ if era is not None and wire_mode_for_era(era) != "sessionful":
+ session_id = None
+ claims = verified_claims(rc)
+ subject = claims.get("sub") if claims else None
+ if not (isinstance(subject, str) and subject.strip()):
+ subject = None
+ return session_id, subject
diff --git a/nitrostack/runtime/conformance.py b/nitrostack/runtime/conformance.py
deleted file mode 100644
index dc352b0..0000000
--- a/nitrostack/runtime/conformance.py
+++ /dev/null
@@ -1,98 +0,0 @@
-"""MCP 2026-07-28 implementation blueprint conformance registry."""
-
-from __future__ import annotations
-
-from enum import Enum
-from importlib import import_module
-from pathlib import Path
-from typing import Iterable
-
-from nitrostack.protocol.errors import JsonRpcErrorCode
-from nitrostack.protocol.method_contract import DEPRECATED_MODERN_METHODS as _DEPRECATED_MESSAGES
-from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION
-
-_PACKAGE_ROOT = Path(__file__).resolve().parent.parent
-
-
-class ConformanceArea(str, Enum):
- """Five verification areas for the MCP 2026-07-28 blueprint."""
-
- STATELESS_HTTP = "stateless_http"
- JSONRPC = "jsonrpc"
- TASKS = "tasks"
- MULTI_TENANT = "multi_tenant"
- CIMD_SSRF = "cimd_ssrf"
-
-
-BLUEPRINT_CONFORMANCE_AREAS: dict[ConformanceArea, str] = {
- ConformanceArea.STATELESS_HTTP: (
- "Stateless POST /mcp, server/discover on 2026-07-28, no Mcp-Session-Id, CORS"
- ),
- ConformanceArea.JSONRPC: (
- "Standard JSON-RPC error codes; deprecated methods rejected on modern wire"
- ),
- ConformanceArea.TASKS: (
- "Task-augmented tools/call, tasks/get lifecycle, cancel, terminal-only TTL eviction"
- ),
- ConformanceArea.MULTI_TENANT: (
- "Cross-tenant task access raises TaskNotFoundError without enumeration"
- ),
- ConformanceArea.CIMD_SSRF: (
- "CIMD fetch blocks special-use IPs, redirects, and payloads over 5 KiB"
- ),
-}
-
-# Canonical module paths implementing the recommended package layout.
-REQUIRED_BLUEPRINT_MODULES: tuple[str, ...] = (
- "nitrostack.core.app",
- "nitrostack.core.context",
- "nitrostack.core.decorators",
- "nitrostack.core.errors",
- "nitrostack.core.task",
- "nitrostack.protocol.version",
- "nitrostack.protocol.schema",
- "nitrostack.protocol.mrtr",
- "nitrostack.protocol.cache_hints",
- "nitrostack.protocol.observability",
- "nitrostack.tasks.store",
- "nitrostack.tasks.memory",
- "nitrostack.auth.cimd",
- "nitrostack.auth.oauth",
- "nitrostack.transports.http",
- "nitrostack.transports.sse",
- "nitrostack.transports.stdio",
-)
-
-MODERN_JSONRPC_ERROR_CODES: frozenset[int] = frozenset(
- {
- JsonRpcErrorCode.PARSE_ERROR,
- JsonRpcErrorCode.INVALID_REQUEST,
- JsonRpcErrorCode.METHOD_NOT_FOUND,
- JsonRpcErrorCode.INVALID_PARAMS,
- JsonRpcErrorCode.INTERNAL_ERROR,
- }
-)
-
-DEPRECATED_MODERN_METHODS: frozenset[str] = frozenset(_DEPRECATED_MESSAGES)
-
-
-def verify_package_layout(modules: Iterable[str] | None = None) -> list[str]:
- """Return import errors for any required blueprint module that cannot load."""
- missing: list[str] = []
- for module_path in modules or REQUIRED_BLUEPRINT_MODULES:
- try:
- import_module(module_path)
- except Exception as exc: # pragma: no cover - surfaced by tests
- missing.append(f"{module_path}: {exc}")
- return missing
-
-
-def assert_blueprint_layout() -> None:
- """Raise ``ImportError`` when a required blueprint module is unavailable."""
- errors = verify_package_layout()
- if errors:
- raise ImportError("Blueprint package layout incomplete:\n" + "\n".join(errors))
-
-
-def protocol_version_matches_blueprint() -> bool:
- return MODERN_PROTOCOL_VERSION == "2026-07-28"
diff --git a/nitrostack/runtime/request_ctx.py b/nitrostack/runtime/request_ctx.py
index 485e849..99f2207 100644
--- a/nitrostack/runtime/request_ctx.py
+++ b/nitrostack/runtime/request_ctx.py
@@ -7,6 +7,10 @@
from typing import Any, Mapping, Optional
request_ctx: ContextVar[Any] = ContextVar("nitrostack_request_ctx", default=None)
+# Set by the stdio adapter for one live stream pair, never by client metadata.
+stdio_connection_id: ContextVar[Optional[str]] = ContextVar(
+ "nitrostack_stdio_connection_id", default=None
+)
@dataclass
diff --git a/nitrostack/runtime/stateless.py b/nitrostack/runtime/stateless.py
index cb849db..16fbcef 100644
--- a/nitrostack/runtime/stateless.py
+++ b/nitrostack/runtime/stateless.py
@@ -47,7 +47,8 @@ def request_protocol_version(
The header wins when present. Otherwise ``_meta.mcp.protocolVersion`` is
used. When neither is present the request proceeds (legacy default). The
- header is not required on ``modern`` in this sidecar.
+ HTTP's modern mount requires the header before entering the official
+ transport; this pure helper also serves legacy/auto compatibility callers.
"""
for raw in (header_version, envelope_version):
if isinstance(raw, str) and raw.strip():
diff --git a/nitrostack/tasks/authorization.py b/nitrostack/tasks/authorization.py
index e16cd29..cf164ee 100644
--- a/nitrostack/tasks/authorization.py
+++ b/nitrostack/tasks/authorization.py
@@ -10,6 +10,7 @@
verify_bearer_payload,
)
from nitrostack.core.errors import TaskNotFoundError
+from nitrostack.runtime.caller import caller_identity, session_id_from_request_context
from nitrostack.tasks.types import TaskAccessContext, TaskEntry, TaskWireData
@@ -91,16 +92,10 @@ def _authorization_from_request_context(rc: Any) -> Optional[str]:
def _session_id_from_request_context(rc: Any) -> Optional[str]:
- session = getattr(rc, "session", None)
- if session is None:
- return None
- session_id = getattr(session, "id", None) or getattr(session, "session_id", None)
- if session_id is None:
- return None
- return str(session_id)
+ return session_id_from_request_context(rc)
-def extract_task_access_context(rc: Any) -> Optional[TaskAccessContext]:
+def extract_task_access_context(rc: Any, era: Optional[str] = None) -> Optional[TaskAccessContext]:
"""
Build ``TaskAccessContext`` from an MCP request context.
@@ -117,7 +112,9 @@ def extract_task_access_context(rc: Any) -> Optional[TaskAccessContext]:
user_id: Optional[str] = None
tenant_id: Optional[str] = None
- session_id = _session_id_from_request_context(rc)
+ session_id = (
+ caller_identity(rc, era)[0] if era is not None else _session_id_from_request_context(rc)
+ )
token = _authorization_from_request_context(rc)
if token:
diff --git a/nitrostack/tasks/notify.py b/nitrostack/tasks/notify.py
deleted file mode 100644
index fc81677..0000000
--- a/nitrostack/tasks/notify.py
+++ /dev/null
@@ -1,194 +0,0 @@
-"""Fan-out for ``notifications/tasks/status`` across live transports."""
-
-from __future__ import annotations
-
-import logging
-from typing import Any, Callable, Optional, Protocol
-
-from nitrostack.tasks.authorization import entry_matches_access_context
-from nitrostack.tasks.types import TaskAccessContext, TaskEntry
-
-logger = logging.getLogger(__name__)
-
-TASK_STATUS_METHOD = "notifications/tasks/status"
-
-
-def build_task_status_notification(
- task_id: str,
- status: str,
- *,
- status_message: Optional[str] = None,
-) -> dict[str, Any]:
- """Wire notification for a task status or progress change."""
- params: dict[str, Any] = {"taskId": task_id, "status": status}
- if status_message is not None:
- params["statusMessage"] = status_message
- return {"method": TASK_STATUS_METHOD, "params": params}
-
-
-class TaskStatusSink(Protocol):
- """One connected transport that can receive task status."""
-
- access: Optional[TaskAccessContext]
- session_id: Optional[str]
- task_id: Optional[str]
-
- async def send(self, notification: dict[str, Any]) -> None:
- """Deliver one status notification. Must not raise to the router."""
- ...
-
-
-class CallbackTaskSink:
- """Test and in-process sink that records or forwards notifications."""
-
- def __init__(
- self,
- callback: Callable[[dict[str, Any]], Any],
- *,
- access: Optional[TaskAccessContext] = None,
- session_id: Optional[str] = None,
- task_id: Optional[str] = None,
- ) -> None:
- self._callback = callback
- self.access = access
- self.session_id = session_id
- self.task_id = task_id
-
- async def send(self, notification: dict[str, Any]) -> None:
- result = self._callback(notification)
- if hasattr(result, "__await__"):
- await result
-
-
-class QueueTaskSink:
- """Push notifications onto an asyncio queue (listen / SSE attach)."""
-
- def __init__(
- self,
- put: Callable[[dict[str, Any]], None],
- *,
- access: Optional[TaskAccessContext] = None,
- session_id: Optional[str] = None,
- task_id: Optional[str] = None,
- ) -> None:
- self._put = put
- self.access = access
- self.session_id = session_id
- self.task_id = task_id
-
- async def send(self, notification: dict[str, Any]) -> None:
- self._put(notification)
-
-
-class StreamTaskSink:
- """Write a JSON-RPC notification onto an official stream write side."""
-
- def __init__(
- self,
- write_stream: Any,
- *,
- access: Optional[TaskAccessContext] = None,
- session_id: Optional[str] = None,
- task_id: Optional[str] = None,
- ) -> None:
- self._write_stream = write_stream
- self.access = access
- self.session_id = session_id
- self.task_id = task_id
-
- async def send(self, notification: dict[str, Any]) -> None:
- from mcp.shared.message import SessionMessage
- from mcp_types import jsonrpc_message_adapter
-
- message = jsonrpc_message_adapter.validate_python(
- {
- "jsonrpc": "2.0",
- "method": notification["method"],
- "params": notification.get("params") or {},
- }
- )
- await self._write_stream.send(SessionMessage(message))
-
-
-class SessionTaskSink:
- """Notify the originating MCP session (stdio or legacy SSE)."""
-
- def __init__(
- self,
- session: Any,
- *,
- access: Optional[TaskAccessContext] = None,
- session_id: Optional[str] = None,
- task_id: Optional[str] = None,
- ) -> None:
- self._session = session
- self.access = access
- self.session_id = session_id
- self.task_id = task_id
-
- async def send(self, notification: dict[str, Any]) -> None:
- session = self._session
- if session is None:
- return
- method = notification["method"]
- params = notification.get("params") or {}
- sender = getattr(session, "send_notification", None)
- if sender is not None:
- await sender(method, params)
- return
- outbound = getattr(session, "outbound", None)
- notify = getattr(outbound, "notify", None) if outbound is not None else None
- if notify is not None:
- await notify(method, params)
-
-
-def _sink_accepts(sink: TaskStatusSink, entry: TaskEntry) -> bool:
- task_id = getattr(sink, "task_id", None)
- if task_id is not None and task_id != entry.task_id:
- return False
- session_id = getattr(sink, "session_id", None)
- if session_id is not None and entry.session_id and session_id != entry.session_id:
- return False
- access = getattr(sink, "access", None)
- if access is not None and not entry_matches_access_context(entry, access):
- return False
- return True
-
-
-class TaskStatusRouter:
- """Deliver task status to every live channel. A failed send is ignored."""
-
- def __init__(self) -> None:
- self._sinks: dict[object, TaskStatusSink] = {}
-
- def register(self, sink: TaskStatusSink) -> Callable[[], None]:
- token = object()
- self._sinks[token] = sink
-
- def unsubscribe() -> None:
- self._sinks.pop(token, None)
-
- return unsubscribe
-
- async def notify_task_status(
- self,
- entry: TaskEntry,
- *,
- status: Optional[str] = None,
- status_message: Optional[str] = None,
- ) -> None:
- """Fan out one status change. Never raises to the task lifecycle."""
- notification = build_task_status_notification(
- entry.task_id,
- status if status is not None else entry.status,
- status_message=status_message
- if status_message is not None
- else entry.data.status_message,
- )
- for sink in list(self._sinks.values()):
- if not _sink_accepts(sink, entry):
- continue
- try:
- await sink.send(notification)
- except Exception:
- logger.exception("task status notify failed; continuing")
diff --git a/nitrostack/templates/code-mode/.env.example b/nitrostack/templates/code-mode/.env.example
new file mode 100644
index 0000000..43dc223
--- /dev/null
+++ b/nitrostack/templates/code-mode/.env.example
@@ -0,0 +1,3 @@
+PORT=3000
+# Default transport is stdio. Set MCP_TRANSPORT_TYPE=http to serve /mcp.
+# No credentials are needed: all tools use local demonstration data.
diff --git a/nitrostack/templates/code-mode/.gitignore b/nitrostack/templates/code-mode/.gitignore
new file mode 100644
index 0000000..56dc8d5
--- /dev/null
+++ b/nitrostack/templates/code-mode/.gitignore
@@ -0,0 +1,7 @@
+.env
+.venv/
+__pycache__/
+*.pyc
+*.egg-info/
+build/
+dist/
diff --git a/nitrostack/templates/code-mode/.python-version b/nitrostack/templates/code-mode/.python-version
new file mode 100644
index 0000000..e4fba21
--- /dev/null
+++ b/nitrostack/templates/code-mode/.python-version
@@ -0,0 +1 @@
+3.12
diff --git a/nitrostack/templates/code-mode/README.md b/nitrostack/templates/code-mode/README.md
new file mode 100644
index 0000000..5290bf6
--- /dev/null
+++ b/nitrostack/templates/code-mode/README.md
@@ -0,0 +1,83 @@
+# Code mode
+
+Compose several Python tool calls in one JavaScript workflow using native
+QuickJS inside isolated worker processes. This Python implementation does not
+use WebAssembly.
+## Run the generated project
+
+```sh
+nitrostack-py install
+nitrostack-py validate
+python main.py
+```
+
+`python main.py` serves MCP over stdio: connect it to an MCP client rather than
+expecting a browser page. For HTTP set `MCP_TRANSPORT_TYPE=http` in your shell,
+then run `python main.py` and connect to `http://localhost:3000/mcp`.
+On PowerShell use `$env:MCP_TRANSPORT_TYPE="http"`; on a POSIX shell use
+`MCP_TRANSPORT_TYPE=http python main.py`. Do not expose this unauthenticated demo
+on a public interface. No credentials or external services are required.
+
+The CLI creates `.env` from `.env.example`; adjust it for optional configuration.
+Every finance, inventory and support record is fixed demonstration data.
+The code supports Python 3.10+; `.python-version` selects 3.12 for uv.
+
+## Discover and execute
+
+The exposed catalog is `search`, `get_schema`, and `execute`. The seven underlying
+read-only finance, inventory, support and numeric tools remain discoverable.
+
+1. Call `search` with `{ "query": "inventory" }` (or an empty query to browse).
+2. Call `get_schema` with `{ "name": "inventory_check_stock" }`.
+3. Read `scripts/sample-batch.js` and pass its text as the `code` argument to
+ `execute`. The script checks two SKUs and sums their quantities:
+
+```javascript
+const stock = ["keyboard", "monitor"].map(sku =>
+ tools.call("inventory_check_stock", {sku})
+);
+const summary = tools.call("data_aggregate_sum", {values: stock.map(item => item.quantity)});
+return {stock, total_units: summary.total};
+```
+
+The successful execution result has `success: true`, `value.total_units: 18`,
+and `toolCallCount: 3`. `tools.call` is synchronous. Scripts are function bodies
+and may use `return`; Node.js modules, `fetch`, browser APIs and top-level `await`
+are unavailable. Python handles each tool invocation through the SDK pipeline.
+
+## Installation and limits
+
+Both dependency files declare `nitrostack` and `quickjs>=1.19.4`. Install the
+project dependencies before executing scripts. Native QuickJS wheel availability
+varies by Python/platform; a source install may require a C build toolchain.
+If your Windows environment cannot build it, use a supported Linux/WSL environment.
+Generation, import, discovery and validation do not create workers; the first
+`execute` initializes the pool lazily.
+
+`main.py` sets a 15-second timeout, 100 MiB guest memory limit, 20 tool calls,
+one worker process and `allow_destructive=False`. Tools explicitly declare
+read-only annotations. Execution is bounded by the SDK, but these process and
+runtime limits are not a complete security boundary for arbitrary hostile code.
+Run only trusted demonstration workflows. Resource limits do not replace tool
+permissions or authentication.
+
+The entry point awaits `CODE_MODE.dispose()` in `finally`, including failed
+startup, so workers are stopped on graceful shutdown. If embedding this app,
+retain that cleanup. Do not construct a pool at import time.
+
+## Extend and distribute
+
+Register additional tools in `app_module.py`. Keep destructive operations disabled
+unless your application deliberately adds authorization and a reviewed policy.
+
+```sh
+nitrostack-py upgrade --version
+nitrostack-py validate
+nitrostack-py pack
+```
+
+`upgrade` edits dependency requirements; run `nitrostack-py install` afterward.
+The standalone QuickJS requirement remains in place across SDK upgrades.
+`pack` includes the application modules and packaged JavaScript example.
+Generation vendors the running SDK under `vendor/nitrostack`; uv resolves that
+copy through `[tool.uv.sources]`.
diff --git a/nitrostack/templates/code-mode/app_module.py b/nitrostack/templates/code-mode/app_module.py
new file mode 100644
index 0000000..36c2bcb
--- /dev/null
+++ b/nitrostack/templates/code-mode/app_module.py
@@ -0,0 +1,14 @@
+from nitrostack import ConfigModule, module
+from modules.finance import FinanceTools
+from modules.inventory import InventoryTools
+from modules.support import SupportTools
+from modules.data import DataTools
+
+
+@module(
+ name="app",
+ imports=[ConfigModule.for_root(env_file_path=".env", defaults={"PORT": "3000"})],
+ controllers=[FinanceTools, InventoryTools, SupportTools, DataTools],
+)
+class AppModule:
+ pass
diff --git a/nitrostack/templates/code-mode/main.py b/nitrostack/templates/code-mode/main.py
new file mode 100644
index 0000000..29bf8df
--- /dev/null
+++ b/nitrostack/templates/code-mode/main.py
@@ -0,0 +1,30 @@
+"""Code-mode server; importing this module never starts workers or transports."""
+import asyncio
+from nitrostack import McpApplicationFactory, ServerConfig, mcp_app
+from nitrostack.transforms.code_mode import CodeModeTransform
+from app_module import AppModule
+
+CODE_MODE = CodeModeTransform(
+ timeout_ms=15000,
+ memory_limit_mb=100,
+ max_tool_calls=20,
+ worker_pool_size=1,
+ allow_destructive=False,
+)
+
+
+@mcp_app(module=AppModule, server=ServerConfig(name="code-mode"), transforms=[CODE_MODE])
+class Application:
+ pass
+
+
+async def main():
+ try:
+ app = await McpApplicationFactory.create(Application)
+ await app.start()
+ finally:
+ await CODE_MODE.dispose()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/nitrostack/templates/code-mode/modules/__init__.py b/nitrostack/templates/code-mode/modules/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/nitrostack/templates/code-mode/modules/data.py b/nitrostack/templates/code-mode/modules/data.py
new file mode 100644
index 0000000..666d716
--- /dev/null
+++ b/nitrostack/templates/code-mode/modules/data.py
@@ -0,0 +1,15 @@
+"""One numerical micro-tool for composing a multi-tool script."""
+from nitrostack import ExecutionContext, injectable, tool
+from pydantic import BaseModel, Field, FiniteFloat
+from modules.models import READ_ONLY
+
+
+class SumInput(BaseModel):
+ values: list[FiniteFloat] = Field(description="Finite numbers to sum", max_length=1000)
+
+
+@injectable()
+class DataTools:
+ @tool(name="data_aggregate_sum", description="Sum a list of numeric values from earlier tool results", input_schema=SumInput, annotations=READ_ONLY)
+ async def aggregate_sum(self, input: SumInput, context: ExecutionContext) -> dict:
+ return {"total": sum(input.values)}
diff --git a/nitrostack/templates/code-mode/modules/finance.py b/nitrostack/templates/code-mode/modules/finance.py
new file mode 100644
index 0000000..d7a1630
--- /dev/null
+++ b/nitrostack/templates/code-mode/modules/finance.py
@@ -0,0 +1,24 @@
+"""Fixed demonstration invoices; no banking or payment integration."""
+from nitrostack import ExecutionContext, injectable, tool
+from pydantic import BaseModel, Field
+from modules.models import EmptyInput, READ_ONLY
+
+INVOICES = (
+ {"id": "INV-001", "customer": "Acme", "amount": 1200, "overdue": True},
+ {"id": "INV-002", "customer": "Example Co", "amount": 800, "overdue": False},
+)
+
+
+class InvoiceInput(BaseModel):
+ overdue_only: bool = Field(default=False, description="Return only overdue unpaid invoices")
+
+
+@injectable()
+class FinanceTools:
+ @tool(name="finance_get_financial_summary", description="Summarize demonstration revenue and invoice totals", input_schema=EmptyInput, annotations=READ_ONLY)
+ async def summary(self, input: EmptyInput, context: ExecutionContext) -> dict:
+ return {"invoice_count": len(INVOICES), "total_amount": sum(row["amount"] for row in INVOICES)}
+
+ @tool(name="finance_list_invoices", description="Find unpaid invoices, including overdue customer invoices", input_schema=InvoiceInput, annotations=READ_ONLY)
+ async def invoices(self, input: InvoiceInput, context: ExecutionContext) -> dict:
+ return {"invoices": [dict(row) for row in INVOICES if not input.overdue_only or row["overdue"]]}
diff --git a/nitrostack/templates/code-mode/modules/inventory.py b/nitrostack/templates/code-mode/modules/inventory.py
new file mode 100644
index 0000000..7310a9f
--- /dev/null
+++ b/nitrostack/templates/code-mode/modules/inventory.py
@@ -0,0 +1,23 @@
+"""Deterministic sample inventory, shared by discovery and orchestration examples."""
+from nitrostack import ExecutionContext, injectable, tool
+from pydantic import BaseModel, Field
+from modules.models import EmptyInput, READ_ONLY
+
+STOCK = {"keyboard": 12, "monitor": 6}
+
+
+class StockInput(BaseModel):
+ sku: str = Field(description="Product SKU: keyboard or monitor")
+
+
+@injectable()
+class InventoryTools:
+ @tool(name="inventory_check_stock", description="Look up available stock quantity for a product SKU", input_schema=StockInput, annotations=READ_ONLY)
+ async def check_stock(self, input: StockInput, context: ExecutionContext) -> dict:
+ if input.sku not in STOCK:
+ raise ValueError("Unknown demonstration SKU; use keyboard or monitor")
+ return {"sku": input.sku, "quantity": STOCK[input.sku]}
+
+ @tool(name="inventory_report", description="Report all demonstration warehouse inventory quantities", input_schema=EmptyInput, annotations=READ_ONLY)
+ async def report(self, input: EmptyInput, context: ExecutionContext) -> dict:
+ return {"stock": dict(STOCK)}
diff --git a/nitrostack/templates/code-mode/modules/models.py b/nitrostack/templates/code-mode/modules/models.py
new file mode 100644
index 0000000..0600160
--- /dev/null
+++ b/nitrostack/templates/code-mode/modules/models.py
@@ -0,0 +1,9 @@
+"""Shared schemas and read-only annotations for the demonstration tools."""
+from nitrostack import ToolAnnotations
+from pydantic import BaseModel
+
+READ_ONLY = ToolAnnotations(read_only_hint=True, destructive_hint=False, open_world_hint=False)
+
+
+class EmptyInput(BaseModel):
+ pass
diff --git a/nitrostack/templates/code-mode/modules/support.py b/nitrostack/templates/code-mode/modules/support.py
new file mode 100644
index 0000000..4baac16
--- /dev/null
+++ b/nitrostack/templates/code-mode/modules/support.py
@@ -0,0 +1,24 @@
+"""Local sample support tickets; no authentication or ticketing service."""
+from nitrostack import ExecutionContext, injectable, tool
+from pydantic import BaseModel, Field
+from modules.models import EmptyInput, READ_ONLY
+
+TICKETS = (
+ {"id": "T-001", "title": "Keyboard delivery delayed", "status": "open"},
+ {"id": "T-002", "title": "Monitor setup question", "status": "resolved"},
+)
+
+
+class TicketInput(BaseModel):
+ query: str = Field(default="", description="Words to find in a support ticket title")
+
+
+@injectable()
+class SupportTools:
+ @tool(name="support_get_system_status", description="Check demonstration customer support system health", input_schema=EmptyInput, annotations=READ_ONLY)
+ async def status(self, input: EmptyInput, context: ExecutionContext) -> dict:
+ return {"status": "ok", "demo": True}
+
+ @tool(name="support_search_tickets", description="Search customer support tickets about deliveries and product setup", input_schema=TicketInput, annotations=READ_ONLY)
+ async def tickets(self, input: TicketInput, context: ExecutionContext) -> dict:
+ return {"tickets": [dict(row) for row in TICKETS if input.query.casefold() in row["title"].casefold()]}
diff --git a/nitrostack/templates/code-mode/pyproject.toml b/nitrostack/templates/code-mode/pyproject.toml
new file mode 100644
index 0000000..eb61367
--- /dev/null
+++ b/nitrostack/templates/code-mode/pyproject.toml
@@ -0,0 +1,20 @@
+[build-system]
+requires = ["setuptools>=61.0.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "nitrostack-code-mode"
+version = "0.1.0"
+description = "NitroStack code-mode demonstration server"
+requires-python = ">=3.10"
+dependencies = ["nitrostack", "quickjs>=1.19.4"]
+
+[tool.setuptools]
+py-modules = ["main", "app_module"]
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["modules*", "scripts*"]
+
+[tool.setuptools.package-data]
+scripts = ["*.js"]
diff --git a/nitrostack/templates/code-mode/requirements.txt b/nitrostack/templates/code-mode/requirements.txt
new file mode 100644
index 0000000..06cc154
--- /dev/null
+++ b/nitrostack/templates/code-mode/requirements.txt
@@ -0,0 +1,2 @@
+nitrostack
+quickjs>=1.19.4
diff --git a/nitrostack/templates/code-mode/scripts/__init__.py b/nitrostack/templates/code-mode/scripts/__init__.py
new file mode 100644
index 0000000..715d0ce
--- /dev/null
+++ b/nitrostack/templates/code-mode/scripts/__init__.py
@@ -0,0 +1 @@
+"""Packaged JavaScript examples for the code-mode server."""
diff --git a/nitrostack/templates/code-mode/scripts/sample-batch.js b/nitrostack/templates/code-mode/scripts/sample-batch.js
new file mode 100644
index 0000000..abc31ab
--- /dev/null
+++ b/nitrostack/templates/code-mode/scripts/sample-batch.js
@@ -0,0 +1,6 @@
+// Calls are synchronous; no Node.js, fetch(), imports, or browser APIs are available.
+const stock = ["keyboard", "monitor"].map(sku =>
+ tools.call("inventory_check_stock", {sku})
+);
+const summary = tools.call("data_aggregate_sum", {values: stock.map(item => item.quantity)});
+return {stock, total_units: summary.total};
diff --git a/nitrostack/templates/code-mode/uv.toml b/nitrostack/templates/code-mode/uv.toml
new file mode 100644
index 0000000..39128ea
--- /dev/null
+++ b/nitrostack/templates/code-mode/uv.toml
@@ -0,0 +1 @@
+python-preference = "managed"
diff --git a/nitrostack/templates/enterprise-search/.env.example b/nitrostack/templates/enterprise-search/.env.example
new file mode 100644
index 0000000..43dc223
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/.env.example
@@ -0,0 +1,3 @@
+PORT=3000
+# Default transport is stdio. Set MCP_TRANSPORT_TYPE=http to serve /mcp.
+# No credentials are needed: all tools use local demonstration data.
diff --git a/nitrostack/templates/enterprise-search/.gitignore b/nitrostack/templates/enterprise-search/.gitignore
new file mode 100644
index 0000000..56dc8d5
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/.gitignore
@@ -0,0 +1,7 @@
+.env
+.venv/
+__pycache__/
+*.pyc
+*.egg-info/
+build/
+dist/
diff --git a/nitrostack/templates/enterprise-search/.python-version b/nitrostack/templates/enterprise-search/.python-version
new file mode 100644
index 0000000..e4fba21
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/.python-version
@@ -0,0 +1 @@
+3.12
diff --git a/nitrostack/templates/enterprise-search/README.md b/nitrostack/templates/enterprise-search/README.md
new file mode 100644
index 0000000..4cdd812
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/README.md
@@ -0,0 +1,60 @@
+# Enterprise search
+
+A small MCP service demonstrating BM25-ranked progressive tool discovery.
+## Run the generated project
+
+```sh
+nitrostack-py install
+nitrostack-py validate
+python main.py
+```
+
+`python main.py` serves MCP over stdio: connect it to an MCP client rather than
+expecting a browser page. For HTTP set `MCP_TRANSPORT_TYPE=http` in your shell,
+then run `python main.py` and connect to `http://localhost:3000/mcp`.
+On PowerShell use `$env:MCP_TRANSPORT_TYPE="http"`; on a POSIX shell use
+`MCP_TRANSPORT_TYPE=http python main.py`. Do not expose this unauthenticated demo
+on a public interface. No credentials or external services are required.
+
+The CLI creates `.env` from `.env.example`; adjust it for optional configuration.
+Every finance, inventory and support record is fixed demonstration data.
+The code supports Python 3.10+; `.python-version` selects 3.12 for uv.
+
+## Discover, then call
+
+The initial tool list contains `search_tools`, `call_tool`, and three anchors:
+`finance_get_financial_summary`, `inventory_report`, `support_get_system_status`.
+The full six-tool catalog is available through progressive discovery.
+BM25 ranks tool descriptions and schemas; it does not search an external
+enterprise document database.
+
+In an MCP client's tool-call interface:
+
+1. Call `search_tools` with `{ "query": "" }` to browse the catalog.
+2. Call `search_tools` with `{ "query": "overdue invoices" }`. The invoice tool
+ appears first, with its input schema. A query with no matches returns no tools.
+3. Call `call_tool` with:
+
+```json
+{"name": "finance_list_invoices", "arguments": {"overdue_only": true}}
+```
+
+The result contains `INV-001`, the overdue Acme invoice. Tool arguments use
+schema fields directly; do not add an `input` wrapper.
+
+## Extend and distribute
+
+Add decorated read-only tools under `modules/`, register their classes in
+`app_module.py`, and keep searchable names and descriptions specific.
+`main.py` configures `Bm25SearchTransform` and the always-visible anchors.
+Each read returns new containers so a client cannot mutate the sample records.
+
+```sh
+nitrostack-py upgrade --version
+nitrostack-py validate
+nitrostack-py pack
+```
+
+`upgrade` edits dependency requirements; run `nitrostack-py install` afterward.
+`pack` writes a wheel under `dist/`. Generation vendors the running SDK under
+`vendor/nitrostack`; uv resolves that local copy through `[tool.uv.sources]`.
diff --git a/nitrostack/templates/enterprise-search/app_module.py b/nitrostack/templates/enterprise-search/app_module.py
new file mode 100644
index 0000000..6a0acbb
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/app_module.py
@@ -0,0 +1,13 @@
+from nitrostack import ConfigModule, module
+from modules.finance import FinanceTools
+from modules.inventory import InventoryTools
+from modules.support import SupportTools
+
+
+@module(
+ name="app",
+ imports=[ConfigModule.for_root(env_file_path=".env", defaults={"PORT": "3000"})],
+ controllers=[FinanceTools, InventoryTools, SupportTools],
+)
+class AppModule:
+ pass
diff --git a/nitrostack/templates/enterprise-search/main.py b/nitrostack/templates/enterprise-search/main.py
new file mode 100644
index 0000000..6aacb0b
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/main.py
@@ -0,0 +1,25 @@
+"""BM25 progressive-discovery server with local sample tools."""
+import asyncio
+from nitrostack import McpApplicationFactory, ServerConfig, mcp_app
+from nitrostack.transforms.search import Bm25SearchTransform
+from app_module import AppModule
+
+
+@mcp_app(
+ module=AppModule,
+ server=ServerConfig(name="enterprise-search"),
+ transforms=[Bm25SearchTransform(always_visible=[
+ "finance_get_financial_summary", "inventory_report", "support_get_system_status",
+ ])],
+)
+class Application:
+ pass
+
+
+async def main():
+ app = await McpApplicationFactory.create(Application)
+ await app.start()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/nitrostack/templates/enterprise-search/modules/__init__.py b/nitrostack/templates/enterprise-search/modules/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/nitrostack/templates/enterprise-search/modules/finance.py b/nitrostack/templates/enterprise-search/modules/finance.py
new file mode 100644
index 0000000..d7a1630
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/modules/finance.py
@@ -0,0 +1,24 @@
+"""Fixed demonstration invoices; no banking or payment integration."""
+from nitrostack import ExecutionContext, injectable, tool
+from pydantic import BaseModel, Field
+from modules.models import EmptyInput, READ_ONLY
+
+INVOICES = (
+ {"id": "INV-001", "customer": "Acme", "amount": 1200, "overdue": True},
+ {"id": "INV-002", "customer": "Example Co", "amount": 800, "overdue": False},
+)
+
+
+class InvoiceInput(BaseModel):
+ overdue_only: bool = Field(default=False, description="Return only overdue unpaid invoices")
+
+
+@injectable()
+class FinanceTools:
+ @tool(name="finance_get_financial_summary", description="Summarize demonstration revenue and invoice totals", input_schema=EmptyInput, annotations=READ_ONLY)
+ async def summary(self, input: EmptyInput, context: ExecutionContext) -> dict:
+ return {"invoice_count": len(INVOICES), "total_amount": sum(row["amount"] for row in INVOICES)}
+
+ @tool(name="finance_list_invoices", description="Find unpaid invoices, including overdue customer invoices", input_schema=InvoiceInput, annotations=READ_ONLY)
+ async def invoices(self, input: InvoiceInput, context: ExecutionContext) -> dict:
+ return {"invoices": [dict(row) for row in INVOICES if not input.overdue_only or row["overdue"]]}
diff --git a/nitrostack/templates/enterprise-search/modules/inventory.py b/nitrostack/templates/enterprise-search/modules/inventory.py
new file mode 100644
index 0000000..7310a9f
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/modules/inventory.py
@@ -0,0 +1,23 @@
+"""Deterministic sample inventory, shared by discovery and orchestration examples."""
+from nitrostack import ExecutionContext, injectable, tool
+from pydantic import BaseModel, Field
+from modules.models import EmptyInput, READ_ONLY
+
+STOCK = {"keyboard": 12, "monitor": 6}
+
+
+class StockInput(BaseModel):
+ sku: str = Field(description="Product SKU: keyboard or monitor")
+
+
+@injectable()
+class InventoryTools:
+ @tool(name="inventory_check_stock", description="Look up available stock quantity for a product SKU", input_schema=StockInput, annotations=READ_ONLY)
+ async def check_stock(self, input: StockInput, context: ExecutionContext) -> dict:
+ if input.sku not in STOCK:
+ raise ValueError("Unknown demonstration SKU; use keyboard or monitor")
+ return {"sku": input.sku, "quantity": STOCK[input.sku]}
+
+ @tool(name="inventory_report", description="Report all demonstration warehouse inventory quantities", input_schema=EmptyInput, annotations=READ_ONLY)
+ async def report(self, input: EmptyInput, context: ExecutionContext) -> dict:
+ return {"stock": dict(STOCK)}
diff --git a/nitrostack/templates/enterprise-search/modules/models.py b/nitrostack/templates/enterprise-search/modules/models.py
new file mode 100644
index 0000000..0600160
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/modules/models.py
@@ -0,0 +1,9 @@
+"""Shared schemas and read-only annotations for the demonstration tools."""
+from nitrostack import ToolAnnotations
+from pydantic import BaseModel
+
+READ_ONLY = ToolAnnotations(read_only_hint=True, destructive_hint=False, open_world_hint=False)
+
+
+class EmptyInput(BaseModel):
+ pass
diff --git a/nitrostack/templates/enterprise-search/modules/support.py b/nitrostack/templates/enterprise-search/modules/support.py
new file mode 100644
index 0000000..4baac16
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/modules/support.py
@@ -0,0 +1,24 @@
+"""Local sample support tickets; no authentication or ticketing service."""
+from nitrostack import ExecutionContext, injectable, tool
+from pydantic import BaseModel, Field
+from modules.models import EmptyInput, READ_ONLY
+
+TICKETS = (
+ {"id": "T-001", "title": "Keyboard delivery delayed", "status": "open"},
+ {"id": "T-002", "title": "Monitor setup question", "status": "resolved"},
+)
+
+
+class TicketInput(BaseModel):
+ query: str = Field(default="", description="Words to find in a support ticket title")
+
+
+@injectable()
+class SupportTools:
+ @tool(name="support_get_system_status", description="Check demonstration customer support system health", input_schema=EmptyInput, annotations=READ_ONLY)
+ async def status(self, input: EmptyInput, context: ExecutionContext) -> dict:
+ return {"status": "ok", "demo": True}
+
+ @tool(name="support_search_tickets", description="Search customer support tickets about deliveries and product setup", input_schema=TicketInput, annotations=READ_ONLY)
+ async def tickets(self, input: TicketInput, context: ExecutionContext) -> dict:
+ return {"tickets": [dict(row) for row in TICKETS if input.query.casefold() in row["title"].casefold()]}
diff --git a/nitrostack/templates/enterprise-search/pyproject.toml b/nitrostack/templates/enterprise-search/pyproject.toml
new file mode 100644
index 0000000..40c9ff5
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/pyproject.toml
@@ -0,0 +1,17 @@
+[build-system]
+requires = ["setuptools>=61.0.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "nitrostack-enterprise-search"
+version = "0.1.0"
+description = "NitroStack enterprise-search demonstration server"
+requires-python = ">=3.10"
+dependencies = ["nitrostack"]
+
+[tool.setuptools]
+py-modules = ["main", "app_module"]
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["modules*", "scripts*"]
diff --git a/nitrostack/templates/enterprise-search/requirements.txt b/nitrostack/templates/enterprise-search/requirements.txt
new file mode 100644
index 0000000..9e875ce
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/requirements.txt
@@ -0,0 +1 @@
+nitrostack
diff --git a/nitrostack/templates/enterprise-search/uv.toml b/nitrostack/templates/enterprise-search/uv.toml
new file mode 100644
index 0000000..39128ea
--- /dev/null
+++ b/nitrostack/templates/enterprise-search/uv.toml
@@ -0,0 +1 @@
+python-preference = "managed"
diff --git a/nitrostack/templates/flight-booking/.env.example b/nitrostack/templates/flight-booking/.env.example
index e4a2b46..e53f573 100644
--- a/nitrostack/templates/flight-booking/.env.example
+++ b/nitrostack/templates/flight-booking/.env.example
@@ -5,7 +5,11 @@ TOKEN_ISSUER=https://dev-5dt0utuk315713tjm.us.auth0.com
DUFFEL_API_KEY=your-duffel-api-key
PORT=3000
NODE_ENV=development
-NITROSTACK_APP_MODE=universal
+NITROSTACK_APP_MODE=openai
# Unset by default so Studio can call tools without a token (TS default).
# Set to true only when testing real OAuth enforcement.
# OAUTH_REQUIRED=true
+# OAuth Discovery Settings (Optional)
+# OAUTH_DISCOVERY_PORT=3005
+# OAUTH_DISCOVERY_AUTO_RETRY=true
+# OAUTH_DISCOVERY_MAX_RETRIES=50
diff --git a/nitrostack/templates/flight-booking/OAUTH_SETUP.md b/nitrostack/templates/flight-booking/OAUTH_SETUP.md
index 1b6ed26..d66d7c2 100644
--- a/nitrostack/templates/flight-booking/OAUTH_SETUP.md
+++ b/nitrostack/templates/flight-booking/OAUTH_SETUP.md
@@ -52,6 +52,8 @@ TOKEN_ISSUER=https://your-tenant.us.auth0.com/
# OAUTH_TOKEN_CACHE_SECONDS=300
# Port for the .well-known discovery server (default 3005).
# OAUTH_DISCOVERY_PORT=3005
+# OAUTH_DISCOVERY_AUTO_RETRY=true
+# OAUTH_DISCOVERY_MAX_RETRIES=50
```
## 2. Protected Routes
diff --git a/nitrostack/templates/flight-booking/pyproject.toml b/nitrostack/templates/flight-booking/pyproject.toml
index 55b1451..176e01e 100644
--- a/nitrostack/templates/flight-booking/pyproject.toml
+++ b/nitrostack/templates/flight-booking/pyproject.toml
@@ -11,6 +11,9 @@ dependencies = [
"nitrostack",
]
+[tool.setuptools]
+py-modules = ["main", "app_module"]
+
[tool.setuptools.packages.find]
where = ["."]
namespaces = true
diff --git a/nitrostack/templates/pizzaz/.env.example b/nitrostack/templates/pizzaz/.env.example
index b922b01..6f8208b 100644
--- a/nitrostack/templates/pizzaz/.env.example
+++ b/nitrostack/templates/pizzaz/.env.example
@@ -1,5 +1,5 @@
PORT=3000
-NITROSTACK_APP_MODE=universal
+NITROSTACK_APP_MODE=openai
# Mapbox public token for the pizza-map widget (same as TS NEXT_PUBLIC_MAPBOX_TOKEN).
# Get a free key at https://www.mapbox.com/ — or leave unset to use the TS demo token.
diff --git a/nitrostack/templates/pizzaz/pyproject.toml b/nitrostack/templates/pizzaz/pyproject.toml
index 39f3512..37c597b 100644
--- a/nitrostack/templates/pizzaz/pyproject.toml
+++ b/nitrostack/templates/pizzaz/pyproject.toml
@@ -11,6 +11,9 @@ dependencies = [
"nitrostack",
]
+[tool.setuptools]
+py-modules = ["main", "app_module"]
+
[tool.setuptools.packages.find]
where = ["."]
namespaces = true
diff --git a/nitrostack/templates/starter/modules/calculator/calculator_tools.py b/nitrostack/templates/starter/modules/calculator/calculator_tools.py
index aeb988f..a815d5f 100644
--- a/nitrostack/templates/starter/modules/calculator/calculator_tools.py
+++ b/nitrostack/templates/starter/modules/calculator/calculator_tools.py
@@ -1,6 +1,10 @@
+import base64
+import math
+import re
+from typing import Literal, Optional
+
from nitrostack import injectable, tool, widget, ExecutionContext
-from pydantic import BaseModel, Field
-from typing import Literal
+from pydantic import BaseModel, Field, field_validator
class CalculateInput(BaseModel):
@@ -8,11 +12,44 @@ class CalculateInput(BaseModel):
a: float = Field(description="First number")
b: float = Field(description="Second number")
+ @field_validator("a", "b")
+ @classmethod
+ def _finite(cls, value: float) -> float:
+ if not math.isfinite(value):
+ raise ValueError("must be a finite number")
+ return value
+
class ConvertTemperatureInput(BaseModel):
- value: float = Field(description="Temperature value to convert")
- from_unit: Literal["celsius", "fahrenheit", "kelvin"] = Field(description="Unit to convert from")
- to_unit: Literal["celsius", "fahrenheit", "kelvin"] = Field(description="Unit to convert to")
+ file_name: Optional[str] = Field(
+ default=None,
+ max_length=100,
+ pattern=r"^[a-zA-Z0-9._-]+$",
+ description="Optional input file name (alphanumeric, dot, underscore, hyphen)",
+ )
+ file_type: Optional[Literal["text/plain", "text/csv", "application/json"]] = Field(
+ default=None,
+ description="MIME type of optional uploaded file content",
+ )
+ file_content: Optional[str] = Field(
+ default=None,
+ max_length=2 * 1024 * 1024,
+ description="Optional base64-encoded file payload (max 2MB)",
+ )
+ value: Optional[float] = Field(default=None, description="Temperature value to convert")
+ from_unit: Optional[Literal["celsius", "fahrenheit", "kelvin"]] = Field(
+ default=None, description="Unit to convert from",
+ )
+ to_unit: Optional[Literal["celsius", "fahrenheit", "kelvin"]] = Field(
+ default=None, description="Unit to convert to",
+ )
+
+ @field_validator("value")
+ @classmethod
+ def _finite_value(cls, value: Optional[float]) -> Optional[float]:
+ if value is not None and not math.isfinite(value):
+ raise ValueError("must be a finite number")
+ return value
class CalculateOutput(BaseModel):
@@ -39,6 +76,20 @@ def _from_celsius(celsius: float, to_unit: str) -> float:
return celsius + 273.15
+def _safe_file_name(name: Optional[str]) -> Optional[str]:
+ if not name:
+ return None
+ base = name.split("/")[-1].split("\\")[-1]
+ cleaned = re.sub(r"[^a-zA-Z0-9._-]", "_", base)
+ return cleaned[:100] or None
+
+
+def _decode_file_payload(content: str) -> str:
+ data_url = re.match(r"^data:[A-Za-z0-9+/.-]+;base64,(.+)$", content)
+ raw = data_url.group(1) if data_url else content
+ return base64.b64decode(raw, validate=True).decode("utf-8", errors="replace")
+
+
@injectable()
class CalculatorTools:
@tool(
@@ -74,26 +125,56 @@ async def calculate(self, input: CalculateInput, context: ExecutionContext) -> d
"a": input.a,
"b": input.b,
"result": result,
- "expression": f"{input.a} {symbol} {input.b} = {result}"
+ "expression": f"{input.a} {symbol} {input.b} = {result}",
}
@tool(
name="convert_temperature",
title="Convert Temperature",
- description="Convert a temperature from one unit to another (celsius, fahrenheit, kelvin)",
- input_schema=ConvertTemperatureInput
+ description="Convert temperature from file content or direct input (celsius, fahrenheit, kelvin)",
+ input_schema=ConvertTemperatureInput,
)
async def convert_temperature(self, input: ConvertTemperatureInput, context: ExecutionContext) -> dict:
+ safe_name = _safe_file_name(input.file_name)
context.logger.info(
- f"Converting temperature: {input.value} from {input.from_unit} to {input.to_unit}"
+ "Converting temperature",
+ meta={
+ "file_name": safe_name,
+ "file_type": input.file_type,
+ "value": input.value,
+ "from_unit": input.from_unit,
+ "to_unit": input.to_unit,
+ },
)
- celsius = _to_celsius(input.value, input.from_unit)
- result = round(_from_celsius(celsius, input.to_unit), 2)
+
+ value = input.value
+ from_unit = input.from_unit
+ to_unit = input.to_unit
+
+ if input.file_content:
+ try:
+ decoded = _decode_file_payload(input.file_content)
+ if value is None:
+ match = re.search(r"-?\d+(?:\.\d+)?", decoded)
+ if match:
+ value = float(match.group(0))
+ context.logger.info(
+ "Processed file payload in-memory",
+ meta={"file_name": safe_name, "size_bytes": len(input.file_content)},
+ )
+ except (ValueError, UnicodeDecodeError) as exc:
+ context.logger.warn(f"Failed to parse file content: {exc}")
+
+ if value is None or from_unit is None or to_unit is None:
+ raise ValueError("value, from_unit, and to_unit are required for conversion")
+
+ celsius = _to_celsius(value, from_unit)
+ result = round(_from_celsius(celsius, to_unit), 2)
return {
"result": result,
- "unit": input.to_unit,
- "original_value": input.value,
- "from_unit": input.from_unit,
- "to_unit": input.to_unit,
- "expression": f"{input.value}°{input.from_unit} = {result}°{input.to_unit}",
- }
+ "unit": to_unit,
+ "original_value": value,
+ "from_unit": from_unit,
+ "to_unit": to_unit,
+ "expression": f"{value}°{from_unit} = {result}°{to_unit}",
+ }
\ No newline at end of file
diff --git a/nitrostack/templates/starter/pyproject.toml b/nitrostack/templates/starter/pyproject.toml
index efcd53e..293aa60 100644
--- a/nitrostack/templates/starter/pyproject.toml
+++ b/nitrostack/templates/starter/pyproject.toml
@@ -11,6 +11,9 @@ dependencies = [
"nitrostack",
]
+[tool.setuptools]
+py-modules = ["main", "app_module"]
+
[tool.setuptools.packages.find]
where = ["."]
namespaces = true
diff --git a/nitrostack/testing/__init__.py b/nitrostack/testing/__init__.py
index 0db12b6..a45d688 100644
--- a/nitrostack/testing/__init__.py
+++ b/nitrostack/testing/__init__.py
@@ -1,9 +1,20 @@
+import inspect
import json
-from typing import Type, Any, Dict, Optional
+from typing import Type, Any, Dict, Optional, List, Tuple
import mcp.types as types
+from unittest.mock import NonCallableMock
from nitrostack.core.app import mcp_app, McpApplicationFactory, ServerConfig, McpApplication
+from nitrostack.core.di import DIContainer
+from nitrostack.testing.mocks import MockLogger, create_mock_context, flush_tasks
+
+__all__ = ["NitroTestingModule", "MockLogger", "create_mock_context", "flush_tasks"]
+
+
+def _is_factory(value: Any) -> bool:
+ # Classes and plain functions are factories; anything else is used as the instance.
+ return inspect.isclass(value) or inspect.isroutine(value)
class NitroTestingModule:
@@ -14,18 +25,152 @@ class NitroTestingModule:
Dispatches through the owned low-level `mcp.server.lowlevel.Server`
`request_handlers` (the same dict the real stdio/HTTP transports use).
"""
+ def __init__(
+ self,
+ app: McpApplication,
+ _container: Optional[DIContainer] = None,
+ _snapshot: Optional[Tuple[Dict[Any, Any], Dict[Any, Any]]] = None,
+ _overrides: Optional[List[Any]] = None,
+ ):
+ self.app = app
+ self._container = _container
+ self._snapshot = _snapshot
+ self._overrides = _overrides or []
+ self._closed = False
+
@classmethod
- async def create(cls, app_module: Type) -> "NitroTestingModule":
- # Construct a dummy App class decorated with @mcp_app
- @mcp_app(module=app_module, server=ServerConfig(name="test-server"))
- class TestApp:
- pass
+ async def create(
+ cls,
+ app_module: Type,
+ *,
+ protocol_era: Optional[str] = None,
+ transforms: Optional[list] = None,
+ overrides: Optional[Dict[Any, Any]] = None,
+ ) -> "NitroTestingModule":
+ """Build the app in-process.
+
+ ``overrides`` maps a provider token (class or string) to the instance tools should
+ receive. A class or plain function is called with no arguments instead (it may be
+ ``async``). The original provider is never constructed. Call ``close()`` (or use
+ ``async with``) to put the DI container back as it was before ``create()``.
+ """
+ container = DIContainer.get_instance()
+ snapshot = (dict(container._instances), dict(container._registry))
+ override_values: List[Any] = []
+ try:
+ for token, override in (overrides or {}).items():
+ value = override() if _is_factory(override) else override
+ if inspect.isawaitable(value):
+ value = await value
+ container.register_value(token, value)
+ override_values.append(value)
+ cls._evict_dependents(container, list((overrides or {})))
+
+ server_config = ServerConfig(
+ name="test-server",
+ protocol_era=protocol_era,
+ )
+
+ @mcp_app(
+ module=app_module,
+ server=server_config,
+ transforms=transforms,
+ )
+ class TestApp:
+ pass
+
+ app = await McpApplicationFactory.create(TestApp)
+ except BaseException:
+ cls._restore_container(container, snapshot)
+ raise
+ return cls(app, container, snapshot, override_values)
- app = await McpApplicationFactory.create(TestApp)
- return cls(app)
+ @staticmethod
+ def _evict_dependents(container: DIContainer, overridden: List[Any]) -> None:
+ """Drop cached consumers of an overridden token so they are rebuilt with the override.
+
+ A service built before ``create()`` still holds the real dependency. Evicting it (and
+ anything that depends on it) makes the container construct it again inside the
+ harness. The snapshot taken first puts the original instances back on ``close()``.
+ """
+ stale = set(overridden)
+ changed = True
+ while changed:
+ changed = False
+ for token, instance in list(container._instances.items()):
+ if token in stale:
+ continue
+ deps = getattr(type(instance), "_mcp_deps", None) or []
+ if any(dep in stale for dep in deps):
+ stale.add(token)
+ del container._instances[token]
+ changed = True
- def __init__(self, app: McpApplication):
- self.app = app
+ @staticmethod
+ def _restore_container(
+ container: DIContainer, snapshot: Tuple[Dict[Any, Any], Dict[Any, Any]]
+ ) -> None:
+ # Undo everything create() added: overrides and every provider built from them,
+ # so a later harness never reuses a service that still holds an old fake.
+ for store, saved in zip((container._instances, container._registry), snapshot):
+ store.clear()
+ store.update(saved)
+
+ def _created_instances(self) -> List[Any]:
+ """Overrides first, then every provider this harness built, dependencies before consumers."""
+ if self._container is None or self._snapshot is None:
+ return list(self._overrides)
+ # Compare by identity, not token: a consumer evicted by create() and rebuilt has the
+ # same token as the original, but it is a new object this harness must tear down.
+ original_ids = {id(value) for value in self._snapshot[0].values()}
+ built = [
+ value for value in self._container._instances.values()
+ if id(value) not in original_ids
+ ]
+ ordered: List[Any] = []
+ seen = set()
+ for value in [*self._overrides, *built]:
+ if id(value) not in seen:
+ seen.add(id(value))
+ ordered.append(value)
+ return ordered
+
+ async def close(self) -> None:
+ """Run each provider's ``on_module_destroy`` hook once, then restore the container.
+
+ Safe to call more than once. Providers are destroyed in reverse creation order, so
+ a consumer is destroyed before the dependencies it was built with, including
+ indirect ones. Hooks may be sync or async, and every hook runs even if one fails
+ (the first error is raised after).
+ """
+ if self._closed:
+ return
+ self._closed = True
+ errors: List[BaseException] = []
+ try:
+ for instance in reversed(self._created_instances()):
+ if isinstance(instance, NonCallableMock):
+ continue
+ hook = getattr(instance, "on_module_destroy", None)
+ if not callable(hook):
+ continue
+ try:
+ result = hook()
+ if inspect.isawaitable(result):
+ await result
+ except Exception as exc: # noqa: BLE001 - run the remaining hooks first
+ errors.append(exc)
+ finally:
+ if self._container is not None and self._snapshot is not None:
+ self._restore_container(self._container, self._snapshot)
+ if errors:
+ raise errors[0]
+
+ async def __aenter__(self) -> "NitroTestingModule":
+ return self
+
+ async def __aexit__(self, *exc_info: Any) -> None:
+ await self.close()
@staticmethod
def _extract_text(text_val: Optional[str]) -> Any:
diff --git a/nitrostack/testing/mocks.py b/nitrostack/testing/mocks.py
new file mode 100644
index 0000000..fce5ce7
--- /dev/null
+++ b/nitrostack/testing/mocks.py
@@ -0,0 +1,51 @@
+"""Small test helpers: a recording logger, a mock context and a task flusher."""
+
+import asyncio
+from typing import Any, Dict, List, Optional, Tuple
+
+from nitrostack.core.context import ExecutionContext
+
+
+class MockLogger:
+ """A ``Logger`` that records calls instead of writing them anywhere."""
+
+ def __init__(self) -> None:
+ self.logs: List[Tuple[str, str, Optional[dict]]] = []
+
+ def _record(self, level: str, message: str, meta: Optional[dict] = None) -> None:
+ self.logs.append((level, message, meta))
+
+ def debug(self, message: str, meta: Optional[dict] = None) -> None:
+ self._record("debug", message, meta)
+
+ def info(self, message: str, meta: Optional[dict] = None) -> None:
+ self._record("info", message, meta)
+
+ def warn(self, message: str, meta: Optional[dict] = None) -> None:
+ self._record("warn", message, meta)
+
+ warning = warn
+
+ def error(self, message: str, meta: Optional[dict] = None) -> None:
+ self._record("error", message, meta)
+
+ def has_log(self, level: str, message: str) -> bool:
+ """True when a ``level`` log contains ``message`` as a substring."""
+ level = "warn" if level == "warning" else level
+ return any(lvl == level and message in text for lvl, text, _ in self.logs)
+
+ def clear(self) -> None:
+ self.logs.clear()
+
+
+def create_mock_context(**overrides: Any) -> ExecutionContext:
+ """An ``ExecutionContext`` with test defaults and a ``MockLogger``; any field can be overridden."""
+ values: Dict[str, Any] = {"request_id": "test-request", "logger": MockLogger()}
+ values.update(overrides)
+ return ExecutionContext(**values)
+
+
+async def flush_tasks(rounds: int = 10) -> None:
+ """Yield to the event loop ``rounds`` times so ready tasks (and tasks they start) run."""
+ for _ in range(rounds):
+ await asyncio.sleep(0)
diff --git a/nitrostack/testing/pytest_plugin.py b/nitrostack/testing/pytest_plugin.py
new file mode 100644
index 0000000..1f5a651
--- /dev/null
+++ b/nitrostack/testing/pytest_plugin.py
@@ -0,0 +1,30 @@
+"""Optional pytest fixtures. Enable with ``pytest_plugins = ["nitrostack.testing.pytest_plugin"]``.
+
+``nitro_client`` builds a harness for the module given by a ``nitro_app`` fixture or the
+``@pytest.mark.nitro_app(module=RootModule)`` marker, and closes it after the test.
+"""
+
+import pytest
+import pytest_asyncio
+
+from nitrostack.testing import NitroTestingModule
+
+
+def pytest_configure(config):
+ config.addinivalue_line("markers", "nitro_app(module=RootModule): root module for the nitro_client fixture")
+
+
+@pytest_asyncio.fixture
+async def nitro_client(request):
+ marker = request.node.get_closest_marker("nitro_app")
+ if marker and "module" in marker.kwargs:
+ app_module = marker.kwargs["module"]
+ else:
+ try:
+ app_module = request.getfixturevalue("nitro_app")
+ except pytest.FixtureLookupError:
+ raise RuntimeError(
+ "nitro_client needs a 'nitro_app' fixture or @pytest.mark.nitro_app(module=RootModule)."
+ ) from None
+ async with await NitroTestingModule.create(app_module) as harness:
+ yield harness
diff --git a/nitrostack/transforms/__init__.py b/nitrostack/transforms/__init__.py
new file mode 100644
index 0000000..54e764d
--- /dev/null
+++ b/nitrostack/transforms/__init__.py
@@ -0,0 +1,23 @@
+from nitrostack.transforms.transform import (
+ CatalogTransform,
+ McpTransform,
+ McpTransformBase,
+ TransformContext,
+ active_bypass,
+ bypassing,
+)
+from nitrostack.transforms.pipeline import (
+ TransformError,
+ TransformPipeline,
+ TransformRegistry,
+)
+from nitrostack.transforms.validation import ToolArgumentError, validate_tool_arguments
+from nitrostack.transforms.synthetic import SyntheticTool
+from nitrostack.transforms.code_mode import CodeModeTransform
+
+__all__ = [
+ "CatalogTransform", "McpTransform", "McpTransformBase", "TransformContext",
+ "TransformError", "TransformPipeline", "TransformRegistry",
+ "ToolArgumentError", "validate_tool_arguments", "active_bypass", "bypassing", "SyntheticTool",
+ "CodeModeTransform",
+]
\ No newline at end of file
diff --git a/nitrostack/transforms/code_mode/__init__.py b/nitrostack/transforms/code_mode/__init__.py
new file mode 100644
index 0000000..6d45e45
--- /dev/null
+++ b/nitrostack/transforms/code_mode/__init__.py
@@ -0,0 +1,35 @@
+"""Code Mode transform for NitroStack."""
+from __future__ import annotations
+
+from nitrostack.transforms.code_mode.destructive_guard import (
+ DestructiveToolError,
+ assert_tool_allowed,
+ is_destructive_tool,
+)
+from nitrostack.transforms.code_mode.legible_error import format_legible_error
+from nitrostack.transforms.code_mode.sandbox_interface import SandboxProtocol, ToolsApi
+from nitrostack.transforms.code_mode.transform import CodeModeTransform
+from nitrostack.transforms.code_mode.types import (
+ CodeModeLimits,
+ ExecuteScriptInput,
+ GetSchemaInput,
+ SandboxExecutionResult,
+ SearchToolsInput,
+)
+from nitrostack.transforms.code_mode.worker_pool import WorkerPool
+
+__all__ = [
+ "CodeModeTransform",
+ "CodeModeLimits",
+ "SandboxExecutionResult",
+ "SandboxProtocol",
+ "ToolsApi",
+ "WorkerPool",
+ "is_destructive_tool",
+ "assert_tool_allowed",
+ "DestructiveToolError",
+ "format_legible_error",
+ "SearchToolsInput",
+ "GetSchemaInput",
+ "ExecuteScriptInput",
+]
diff --git a/nitrostack/transforms/code_mode/destructive_guard.py b/nitrostack/transforms/code_mode/destructive_guard.py
new file mode 100644
index 0000000..7db9d9e
--- /dev/null
+++ b/nitrostack/transforms/code_mode/destructive_guard.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+class DestructiveToolError(Exception):
+ """Raised when a destructive tool is called while allowDestructive is false."""
+ pass
+
+
+def _get_annotation(annotations: Any, *keys: str) -> Optional[bool]:
+ if annotations is None:
+ return None
+ for k in keys:
+ if isinstance(annotations, dict):
+ if k in annotations:
+ return annotations[k]
+ elif hasattr(annotations, k):
+ return getattr(annotations, k)
+ return None
+
+
+def is_destructive_tool(tool: Any) -> bool:
+ """A tool is destructive unless readOnlyHint is true or destructiveHint is explicitly false."""
+ annotations = getattr(tool, "annotations", None)
+ if annotations is None and hasattr(tool, "config"):
+ annotations = getattr(tool.config, "annotations", None)
+
+ read_only = _get_annotation(annotations, "readOnlyHint", "read_only_hint", "read_only")
+ if read_only is True:
+ return False
+
+ destructive = _get_annotation(annotations, "destructiveHint", "destructive_hint")
+ if destructive is False:
+ return False
+
+ return True
+
+
+def assert_tool_allowed(tool: Any, allow_destructive: bool) -> None:
+ """Reject tool if destructive and allow_destructive is False."""
+ if not allow_destructive and is_destructive_tool(tool):
+ name = getattr(tool, "name", str(tool))
+ raise DestructiveToolError(
+ f"Tool '{name}' is destructive and cannot be executed in code-mode when allowDestructive is false."
+ )
diff --git a/nitrostack/transforms/code_mode/guest_evaluator.py b/nitrostack/transforms/code_mode/guest_evaluator.py
new file mode 100644
index 0000000..8ef57db
--- /dev/null
+++ b/nitrostack/transforms/code_mode/guest_evaluator.py
@@ -0,0 +1,190 @@
+from __future__ import annotations
+
+import json
+import logging
+import time
+from typing import Any, Dict, List, Optional
+from multiprocessing.connection import Connection
+
+from nitrostack.transforms.code_mode.legible_error import format_legible_error
+from nitrostack.transforms.code_mode.types import CodeModeLimits, SandboxExecutionResult
+
+logger = logging.getLogger(__name__)
+
+JS_PRELUDE = """
+const console = {
+ log: (...args) => { __nitrostack_log('info', __formatArgs(args)); },
+ info: (...args) => { __nitrostack_log('info', __formatArgs(args)); },
+ warn: (...args) => { __nitrostack_log('warn', __formatArgs(args)); },
+ error: (...args) => { __nitrostack_log('error', __formatArgs(args)); }
+};
+
+function __formatArgs(args) {
+ return args.map(a => {
+ if (typeof a === 'object' && a !== null) {
+ try { return JSON.stringify(a); } catch(e) { return String(a); }
+ }
+ return String(a);
+ }).join(' ');
+}
+
+const tools = new Proxy({
+ call(name, args) {
+ const payload = JSON.stringify(args || {});
+ const resStr = __nitrostack_call_tool(String(name), payload);
+ const parsed = JSON.parse(resStr);
+ if (parsed && parsed.__nitrostack_error) {
+ const err = new Error(parsed.__nitrostack_error);
+ err.name = parsed.__nitrostack_error_type || 'Error';
+ throw err;
+ }
+ return parsed.__nitrostack_value;
+ }
+}, {
+ get(target, prop) {
+ if (prop in target) return target[prop];
+ return function(args) {
+ return target.call(prop, args);
+ };
+ }
+});
+
+const call_tool = (name, args) => tools.call(name, args);
+const call = (name, args) => tools.call(name, args);
+"""
+
+
+def get_quickjs_module():
+ try:
+ import quickjs
+ return quickjs
+ except ImportError as exc:
+ raise RuntimeError(
+ "The 'quickjs' package is required for Code Mode. "
+ "Install it with: pip install 'nitrostack[code-mode]'"
+ ) from exc
+
+
+def worker_process_main(conn: Connection) -> None:
+ """Main loop for isolated worker process."""
+ quickjs = get_quickjs_module()
+ conn.send({"type": "ready"})
+
+ while True:
+ try:
+ if not conn.poll(None):
+ break
+ msg = conn.recv()
+ except (EOFError, KeyboardInterrupt):
+ break
+
+ cmd = msg.get("cmd")
+ if cmd == "shutdown":
+ break
+
+ if cmd == "run":
+ code = msg["code"]
+ limits_dict = msg["limits"]
+ memory_limit_mb = limits_dict.get("memory_limit_mb", 100)
+
+ ctx = quickjs.Context()
+ memory_limit_bytes = int(memory_limit_mb * 1024 * 1024)
+ ctx.set_memory_limit(memory_limit_bytes)
+
+ logs: List[str] = []
+ tool_call_count = 0
+
+ def log_bridge(level: str, message: str) -> None:
+ logs.append(f"[{level}] {message}")
+
+ def tool_call_bridge(name: str, args_json: str) -> str:
+ nonlocal tool_call_count
+ tool_call_count += 1
+ try:
+ conn.send({
+ "type": "tool_call",
+ "name": name,
+ "args_json": args_json,
+ "call_index": tool_call_count,
+ })
+ response = conn.recv()
+ if response.get("status") == "error":
+ return json.dumps({
+ "__nitrostack_error": response.get("error", "Tool execution error"),
+ "__nitrostack_error_type": response.get("error_type", "Error"),
+ })
+ return json.dumps({
+ "__nitrostack_value": response.get("value")
+ })
+ except Exception as e:
+ return json.dumps({
+ "__nitrostack_error": format_legible_error(e),
+ "__nitrostack_error_type": type(e).__name__,
+ })
+
+ ctx.add_callable("__nitrostack_log", log_bridge)
+ ctx.add_callable("__nitrostack_call_tool", tool_call_bridge)
+
+ # Evaluate prelude
+ ctx.eval(JS_PRELUDE)
+
+ start_time = time.perf_counter()
+ success = False
+ value = None
+ error = None
+
+ try:
+ try:
+ raw_result = ctx.eval(code)
+ except quickjs.JSException as exc:
+ if "return not in a function" in str(exc):
+ wrapped = "(function() {\n" + code + "\n})()"
+ raw_result = ctx.eval(wrapped)
+ else:
+ raise
+
+ if hasattr(raw_result, "json"):
+ try:
+ value = json.loads(raw_result.json())
+ except Exception:
+ value = str(raw_result)
+ else:
+ value = raw_result
+
+ success = True
+ except quickjs.JSException as exc:
+ err_str = str(exc)
+ if "out of memory" in err_str:
+ error = f"MemoryLimitExceededError: Script exceeded memory limit of {memory_limit_mb}MB."
+ else:
+ error = format_legible_error(exc)
+ except Exception as exc:
+ error = format_legible_error(exc)
+ finally:
+ duration_ms = (time.perf_counter() - start_time) * 1000.0
+ memory_used_mb = 0.0
+ try:
+ mem_info = ctx.memory()
+ if isinstance(mem_info, dict):
+ used_bytes = mem_info.get("memory_used_size", 0)
+ else:
+ used_bytes = getattr(mem_info, "memory_used_size", 0)
+ memory_used_mb = used_bytes / (1024 * 1024)
+ except Exception:
+ pass
+
+ try:
+ ctx.gc()
+ except Exception:
+ pass
+
+ conn.send({
+ "type": "run_result",
+ "success": success,
+ "value": value,
+ "error": error,
+ "logs": logs,
+ "tool_call_count": tool_call_count,
+ "duration_ms": duration_ms,
+ "memory_used_mb": memory_used_mb,
+ })
diff --git a/nitrostack/transforms/code_mode/legible_error.py b/nitrostack/transforms/code_mode/legible_error.py
new file mode 100644
index 0000000..903bbe5
--- /dev/null
+++ b/nitrostack/transforms/code_mode/legible_error.py
@@ -0,0 +1,43 @@
+"""Format legible error messages for models without leaking host paths or stack frames."""
+from __future__ import annotations
+
+import re
+
+_HOST_PATH_RE = re.compile(
+ r"(?:/[a-zA-Z0-9_\-\.]+)+|(?:[a-zA-Z]:\\[a-zA-Z0-9_\-\.\\]+)"
+)
+
+# Match Python traceback line patterns
+_PY_TRACEBACK_LINE_RE = re.compile(
+ r"^\s*File\s+\".*?\",\s+line\s+\d+.*$",
+ re.MULTILINE
+)
+
+
+def format_legible_error(exc: BaseException | str) -> str:
+ """Format an error message so it is readable (message and location) and leaks no host paths or stack frames."""
+ raw = str(exc)
+
+ # Clean up input markers
+ raw = raw.replace("", "
-""".strip()
-
-
-def _pizza_map_js() -> str:
- import json
-
- from nitrostack.widgets.html_util import get_mapbox_token
-
- token = json.dumps(get_mapbox_token())
- return f"""
-window.__NITRO_MAPBOX_TOKEN = {token};
-window.__nitroWidgetRender = function(data) {{
- const meta = document.getElementById("meta");
- const mapEl = document.getElementById("map-live") || document.getElementById("map");
- const cards = document.getElementById("cards");
- const staticEl = document.getElementById("static-map");
- if (!mapEl) return;
- if (!data || !Array.isArray(data.shops) || !data.shops.length) {{
- if (meta) meta.textContent = "Waiting for show_pizza_map result.";
- return;
- }}
- const shops = data.shops.filter(function(s) {{ return Array.isArray(s.coords) && s.coords.length === 2; }});
- const sig = (data.filter || "all") + "|" + shops.map(function(s) {{
- return (s.id || "") + ":" + s.coords[0] + "," + s.coords[1];
- }}).join(";");
- if (window.__nitroMapSig === sig && window.__nitroMap) return;
- if (meta) meta.textContent = (data.totalShops ?? data.shops.length) + " shops · filter: " + (data.filter || "all");
- if (cards && !cards.querySelector(".map-card")) {{
- data.shops.forEach(function(shop) {{
- const card = document.createElement("article");
- card.className = "map-card ns-card";
- card.setAttribute("data-shop-id", shop.id || "");
- card.setAttribute("data-call-tool", "show_pizza_shop");
- card.setAttribute("data-args", JSON.stringify({{ shopId: shop.id || "" }}));
- card.setAttribute("role", "button");
- card.tabIndex = 0;
- card.innerHTML = '';
- card.querySelector(".name").textContent = shop.name || shop.id || "Shop";
- card.querySelector(".muted").textContent = shop.address || "";
- card.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : "";
- cards.appendChild(card);
- }});
- }}
- function revealLive() {{
- if (staticEl) staticEl.classList.add("is-ready");
- }}
- function mountMap(attempt) {{
- if (window.__nitroMapSig === sig && window.__nitroMap) return;
- if (!window.__NITRO_MAPBOX_TOKEN) {{
- if (meta) meta.textContent = "Set MAPBOX_TOKEN in .env to load the map.";
- if (mapEl) {{
- mapEl.innerHTML = '
Set MAPBOX_TOKEN in .env (Mapbox public pk. token) to load the map.
'
- ''
- )
-
-
-def _pizza_map_card(shop: dict) -> str:
- name = shop.get("name") or shop.get("id") or "Shop"
- shop_id = shop.get("id") or ""
- rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else ""
- return (
- f''
- f'
{esc(name)}
'
- f'
{esc(shop.get("address"))}
'
- f'
{rating}
'
- )
-
-
-def pizza_map_body(data: Any | None) -> str:
- payload = as_dict(data)
- shops = as_list(payload.get("shops"))
- static = ""
- if data is None or not shops:
- meta = "Waiting for show_pizza_map result."
- cards = ""
- else:
- filt = payload.get("filter") or "all"
- total = payload.get("totalShops")
- if total is None:
- total = len(shops)
- meta = f"{total} shops · filter: {filt}"
- cards = "".join(_pizza_map_card(as_dict(shop)) for shop in shops)
- static_src = mapbox_static_url(shops)
- static = (
- f''
- if static_src
- else ""
- )
- return (
- f'
{esc(meta)}
'
- f'
'
- f'{static}
'
- f'
{cards}
'
- ''
- )
-
-
-def pizza_shop_body(data: Any | None) -> str:
- payload = as_dict(data)
- shop = as_dict(payload.get("shop") or payload if data is not None else {})
- if data is None or not shop.get("name"):
- return (
- '
'
- ''
- '
Pizza shop
'
- ''
- '
Waiting for show_pizza_shop result.
'
- ''
- ''
- ''
- ''
- ''
- "
"
- ''
- )
- img = ""
- if shop.get("image"):
- img = f''
- else:
- img = ''
- rating = ""
- if shop.get("rating") is not None:
- rating = f"★ {esc(shop.get('rating'))} ({esc(shop.get('reviews') or 0)} reviews)"
- hours = as_dict(shop.get("hours"))
- hours_text = ""
- if hours.get("open") or hours.get("close"):
- hours_text = f"Hours: {esc(hours.get('open'))} – {esc(hours.get('close'))}"
- chips = "".join(
- f'{esc(item)}' for item in as_list(shop.get("specialties"))
- )
- actions = action_row(maps=maps_url(shop), phone=str(shop.get("phone") or ""), website=str(shop.get("website") or ""))
- return (
- '
'
- f"{img}"
- f'
{esc(shop.get("name"))}
'
- f'
{rating}
'
- f'
{esc(shop.get("description"))}
'
- f'
{esc(shop.get("address"))}
'
- f'
{hours_text}
'
- f'
{esc(shop.get("phone"))}
'
- f'
{chips}
'
- f"{actions}"
- "
"
- ''
- )
-
-
-def calculator_result_body(data: Any | None) -> str:
- payload = as_dict(data)
- expr = payload.get("expression") or "—"
- result = payload.get("result")
- if result is None:
- result = payload.get("value")
- result_text = "—" if result is None else str(result)
- return (
- '
'
- f'
{esc(expr)}
'
- f'
{esc(result_text)}
'
- "
"
- ''
- ''
- )
-
-
-def card_body(data: Any | None) -> str:
- payload = as_dict(data)
- name = payload.get("name") or "—"
- price = payload.get("price")
- price_text = f"${float(price):.2f}" if isinstance(price, (int, float)) else (str(price) if price else "—")
- desc = payload.get("description") or ""
- return (
- '
'
- f'
{esc(name)}
'
- f'
{esc(price_text)}
'
- f'
{esc(desc)}
'
- "
"
- )
-
-
-def table_body(data: Any | None) -> str:
- payload = as_dict(data)
- rows = as_list(payload.get("rows"))
- cols = as_list(payload.get("columns"))
- if not cols and rows:
- cols = list(as_dict(rows[0]).keys())
- header = "".join(f"
{esc(c)}
" for c in cols)
- body_rows = []
- for row in rows:
- row = as_dict(row)
- cells = "".join(f"
{esc(row.get(c, ''))}
" for c in cols)
- body_rows.append(f"
{cells}
")
- return (
- "
"
- f'
{header}
'
- f'{"".join(body_rows)}'
- "
"
- )
-
-
-def chart_body(data: Any | None) -> str:
- payload = as_dict(data)
- title = payload.get("title") or "Chart"
- items = as_list(payload.get("items"))
- values = [_safe_float(as_dict(i).get("value"), 0.0) for i in items]
- max_v = max(values or [1], default=1) or 1
- bars = []
- for item, value in zip(items, values):
- item = as_dict(item)
- height = (value / max_v) * 140
- bars.append(
- '
'
- f''
- f'
{esc(item.get("label"))}
'
- "
"
- )
- return f'
{esc(title)}
{"".join(bars)}
'
-
-
-def _offer_slice_html(sl: dict) -> str:
- origin = place_code(sl.get("origin"))
- dest = place_code(sl.get("destination"))
- duration = format_duration(sl.get("duration"))
- segs = as_list(sl.get("segments"))
- first = as_dict(segs[0] if segs else {})
- last = as_dict(segs[-1] if segs else first)
- dep = pick(first, "departing_at", "departingAt", "departureTime", default="") or pick(
- sl, "departing_at", "departingAt", "departureTime", default=""
- )
- arr = pick(last, "arriving_at", "arrivingAt", "arrivalTime", default="") or pick(
- sl, "arriving_at", "arrivingAt", "arrivalTime", default=""
- )
- carrier = first.get("marketing_carrier") or first.get("airline") or sl.get("airline")
- if isinstance(carrier, str):
- airline = carrier
- flight_no = pick(first, "marketing_carrier_flight_number", "flightNumber", default="") or pick(
- sl, "flightNumber", "marketing_carrier_flight_number", default=""
- )
- else:
- carrier = as_dict(carrier)
- airline = pick(carrier, "name", default="") or pick(first, "airline", default="") or pick(sl, "airline", default="")
- flight_no = pick(carrier, "flight_number", "flightNumber", default="") or pick(
- first, "marketing_carrier_flight_number", "flightNumber", default=""
- ) or pick(sl, "flightNumber", default="")
- return (
- f'
{esc(origin)} → {esc(dest)}'
- f'
{esc(dep)} – {esc(arr)} · {esc(duration)}
'
- f'
{esc(airline)} {esc(flight_no)}
'
- )
-
-
-def _offer_itinerary_html(offer: dict) -> str:
- slices = as_list(offer.get("slices"))
- if slices:
- return "".join(_offer_slice_html(as_dict(s)) for s in slices)
- parts = []
- outbound = offer.get("outbound")
- if outbound:
- parts.append(_offer_slice_html(as_dict(outbound)))
- ret = offer.get("return")
- if ret:
- parts.append(_offer_slice_html(as_dict(ret)))
- return "".join(parts) or _offer_slice_html(offer)
-
-
-def flight_search_results_body(data: Any | None) -> str:
- payload = as_dict(data)
- offers = as_list(payload.get("offers") or payload.get("results"))
- if data is None:
- return (
- "
Flight search
"
- '
Waiting for search_flights result.
'
- ''
- )
- params = as_dict(payload.get("searchParams"))
- total = payload.get("totalOffers")
- if total is None:
- total = len(offers)
- if params.get("origin") and params.get("destination"):
- meta = f"{params.get('origin')} → {params.get('destination')} · {total} offer" + ("" if total == 1 else "s")
- else:
- meta = f"{total} offer" + ("" if total == 1 else "s")
- cards = []
- for offer in offers:
- offer = as_dict(offer)
- amount = pick(offer, "total_amount", "totalAmount", default="")
- currency = pick(offer, "total_currency", "totalCurrency", default="")
- slice_html = _offer_itinerary_html(offer)
- offer_id = offer.get("id") or ""
- cards.append(
- f''
- f'
'
- )
-
-
-def airport_search_body(data: Any | None) -> str:
- payload = as_dict(data)
- results = as_list(payload.get("results") or payload.get("airports") or payload.get("places"))
- query = payload.get("query") or ""
- if data is None:
- return (
- "
Airport search
"
- '
Waiting for search_airports result.
'
- ''
- )
- rows = []
- for item in results:
- item = as_dict(item)
- code = pick(item, "iata_code", "iataCode", default="")
- name = pick(item, "name", default="")
- city = pick(item, "city_name", "cityName", "city", default="")
- kind = pick(item, "type", default="airport")
- rows.append(
- f'
{esc(code)}'
- f'
{esc(name)}
'
- f'
{esc(city)} · {esc(kind)}
'
- )
- if not rows:
- rows.append('
No airports found.
')
- return (
- "
Airport search
"
- f'
Query: {esc(query)} · {len(results)} result(s)
'
- f'
{"".join(rows)}
'
- )
-
-
-def order_summary_body(data: Any | None) -> str:
- payload = as_dict(data)
- if data is None or not payload:
- return (
- "
Order summary
"
- '
Waiting for order result.
'
- ''
- )
- status = str(pick(payload, "status", default="held"))
- ref = pick(payload, "booking_reference", "bookingReference", default="")
- amount = pick(payload, "total_amount", "totalAmount", default="")
- currency = pick(payload, "total_currency", "totalCurrency", default="")
- passengers = as_list(payload.get("passengers"))
- pax = []
- for p in passengers:
- p = as_dict(p)
- name = pick(p, "name", default="") or " ".join(
- str(x) for x in (p.get("given_name") or p.get("givenName"), p.get("family_name") or p.get("familyName")) if x
- )
- pax.append(f'
{esc(name or p.get("id"))}
')
- slices = "".join(_offer_slice_html(as_dict(s)) for s in as_list(payload.get("slices")))
- order_id = payload.get("id") or payload.get("orderId") or ""
- cancel = ""
- if order_id and status.lower() not in {"cancelled", "canceled"}:
- cancel = (
- f''
- )
- return (
- '
'
- f'
Order {esc(status)}
'
- f'
Ref {esc(ref)} · {esc(order_id)}
'
- f'
{esc(money(amount, currency))}
'
- f'
Passengers
{"".join(pax) or "
None listed
"}'
- f'
Itinerary
{slices}'
- f"{cancel}"
- "
"
- ''
- )
-
-
-def _seat_cells(cabin: dict) -> str:
- rows_html = []
- rows = as_list(cabin.get("rows"))
- if rows:
- for row in rows:
- row = as_dict(row)
- seats = as_list(row.get("seats") or row.get("elements"))
- if not seats:
- for section in as_list(row.get("sections")):
- seats.extend(as_list(as_dict(section).get("elements")))
- cells = []
- for seat in seats:
- seat = as_dict(seat)
- if seat.get("type") and seat.get("type") != "seat":
- continue
- designator = pick(seat, "designator", "id", "column", default="")
- available = seat.get("available")
- if available is None:
- available = bool(seat.get("available_services") is not None)
- cls = "seat ok" if available else "seat no"
- cells.append(f'{esc(designator)}')
- rows_html.append(
- f'
{esc(row.get("row_number") or row.get("rowNumber") or "")}'
- f"{''.join(cells)}
"
- )
- return "".join(rows_html)
-
-
-def seat_selection_body(data: Any | None) -> str:
- payload = as_dict(data)
- cabins = as_list(payload.get("cabins"))
- if data is None:
- return (
- "
Seat map
"
- '
Waiting for get_seat_map result.
'
- ''
- )
- blocks = []
- for cabin in cabins:
- cabin = as_dict(cabin)
- klass = pick(cabin, "cabin_class", "cabinClass", default="cabin")
- blocks.append(f'
{esc(klass)}
{_seat_cells(cabin)}')
- if not blocks:
- blocks.append('
No seat map data.
')
- return (
- "
Seat map
"
- f'
Offer {esc(payload.get("offerId") or payload.get("offer_id"))}
'
- f'
{"".join(blocks)}
'
- )
-
-
-def order_cancellation_body(data: Any | None) -> str:
- payload = as_dict(data)
- if data is None or not payload:
- return (
- "
'
+ )
+
+
+def airport_search_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ results = as_list(payload.get("results") or payload.get("airports") or payload.get("places"))
+ query = payload.get("query") or ""
+ if data is None:
+ return (
+ "
Airport search
"
+ '
Waiting for search_airports result.
'
+ ''
+ )
+ rows = []
+ for item in results:
+ item = as_dict(item)
+ code = pick(item, "iata_code", "iataCode", default="")
+ name = pick(item, "name", default="")
+ city = pick(item, "city_name", "cityName", "city", default="")
+ kind = pick(item, "type", default="airport")
+ rows.append(
+ f'
{esc(code)}'
+ f'
{esc(name)}
'
+ f'
{esc(city)} · {esc(kind)}
'
+ )
+ if not rows:
+ rows.append('
No airports found.
')
+ return (
+ "
Airport search
"
+ f'
Query: {esc(query)} · {len(results)} result(s)
'
+ f'
{"".join(rows)}
'
+ )
+
+
+def order_summary_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ if data is None or not payload:
+ return (
+ "
Order summary
"
+ '
Waiting for order result.
'
+ ''
+ )
+ status = str(pick(payload, "status", default="held"))
+ ref = pick(payload, "booking_reference", "bookingReference", default="")
+ amount = pick(payload, "total_amount", "totalAmount", default="")
+ currency = pick(payload, "total_currency", "totalCurrency", default="")
+ passengers = as_list(payload.get("passengers"))
+ pax = []
+ for p in passengers:
+ p = as_dict(p)
+ name = pick(p, "name", default="") or " ".join(
+ str(x) for x in (p.get("given_name") or p.get("givenName"), p.get("family_name") or p.get("familyName")) if x
+ )
+ pax.append(f'
{esc(name or p.get("id"))}
')
+ slices = "".join(_offer_slice_html(as_dict(s)) for s in as_list(payload.get("slices")))
+ order_id = payload.get("id") or payload.get("orderId") or ""
+ cancel = ""
+ if order_id and status.lower() not in {"cancelled", "canceled"}:
+ cancel = (
+ f''
+ )
+ return (
+ '
'
+ f'
Order {esc(status)}
'
+ f'
Ref {esc(ref)} · {esc(order_id)}
'
+ f'
{esc(money(amount, currency))}
'
+ f'
Passengers
{"".join(pax) or "
None listed
"}'
+ f'
Itinerary
{slices}'
+ f"{cancel}"
+ "
"
+ ''
+ )
+
+
+def _seat_cells(cabin: dict) -> str:
+ rows_html = []
+ rows = as_list(cabin.get("rows"))
+ if rows:
+ for row in rows:
+ row = as_dict(row)
+ seats = as_list(row.get("seats") or row.get("elements"))
+ if not seats:
+ for section in as_list(row.get("sections")):
+ seats.extend(as_list(as_dict(section).get("elements")))
+ cells = []
+ for seat in seats:
+ seat = as_dict(seat)
+ if seat.get("type") and seat.get("type") != "seat":
+ continue
+ designator = pick(seat, "designator", "id", "column", default="")
+ available = seat.get("available")
+ if available is None:
+ available = bool(seat.get("available_services") is not None)
+ cls = "seat ok" if available else "seat no"
+ cells.append(f'{esc(designator)}')
+ rows_html.append(
+ f'
{esc(row.get("row_number") or row.get("rowNumber") or "")}'
+ f"{''.join(cells)}
"
+ )
+ return "".join(rows_html)
+
+
+def seat_selection_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ cabins = as_list(payload.get("cabins"))
+ if data is None:
+ return (
+ "
Seat map
"
+ '
Waiting for get_seat_map result.
'
+ ''
+ )
+ blocks = []
+ for cabin in cabins:
+ cabin = as_dict(cabin)
+ klass = pick(cabin, "cabin_class", "cabinClass", default="cabin")
+ blocks.append(f'
{esc(klass)}
{_seat_cells(cabin)}')
+ if not blocks:
+ blocks.append('
No seat map data.
')
+ return (
+ "
Seat map
"
+ f'
Offer {esc(payload.get("offerId") or payload.get("offer_id"))}
'
+ f'
{"".join(blocks)}
'
+ )
+
+
+def order_cancellation_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ if data is None or not payload:
+ return (
+ "
'
+ ''
+ )
+
+
+def _pizza_map_card(shop: dict) -> str:
+ name = shop.get("name") or shop.get("id") or "Shop"
+ shop_id = shop.get("id") or ""
+ rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else ""
+ return (
+ f''
+ f'
{esc(name)}
'
+ f'
{esc(shop.get("address"))}
'
+ f'
{rating}
'
+ )
+
+
+def pizza_map_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ shops = as_list(payload.get("shops"))
+ static = ""
+ if data is None or not shops:
+ meta = "Waiting for show_pizza_map result."
+ cards = ""
+ else:
+ filt = payload.get("filter") or "all"
+ total = payload.get("totalShops")
+ if total is None:
+ total = len(shops)
+ meta = f"{total} shops · filter: {filt}"
+ cards = "".join(_pizza_map_card(as_dict(shop)) for shop in shops)
+ static_src = mapbox_static_url(shops)
+ static = (
+ f''
+ if static_src
+ else ""
+ )
+ return (
+ f'
{esc(meta)}
'
+ f'
'
+ f'{static}
'
+ f'
{cards}
'
+ ''
+ )
+
+
+def pizza_shop_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ shop = as_dict(payload.get("shop") or payload if data is not None else {})
+ if data is None or not shop.get("name"):
+ return (
+ '
'
+ ''
+ '
Pizza shop
'
+ ''
+ '
Waiting for show_pizza_shop result.
'
+ ''
+ ''
+ ''
+ ''
+ ''
+ "
"
+ ''
+ )
+ img = ""
+ if shop.get("image"):
+ img = f''
+ else:
+ img = ''
+ rating = ""
+ if shop.get("rating") is not None:
+ rating = f"★ {esc(shop.get('rating'))} ({esc(shop.get('reviews') or 0)} reviews)"
+ hours = as_dict(shop.get("hours"))
+ hours_text = ""
+ if hours.get("open") or hours.get("close"):
+ hours_text = f"Hours: {esc(hours.get('open'))} – {esc(hours.get('close'))}"
+ chips = "".join(
+ f'{esc(item)}' for item in as_list(shop.get("specialties"))
+ )
+ actions = action_row(maps=maps_url(shop), phone=str(shop.get("phone") or ""), website=str(shop.get("website") or ""))
+ return (
+ '
'
+ f"{img}"
+ f'
{esc(shop.get("name"))}
'
+ f'
{rating}
'
+ f'
{esc(shop.get("description"))}
'
+ f'
{esc(shop.get("address"))}
'
+ f'
{hours_text}
'
+ f'
{esc(shop.get("phone"))}
'
+ f'
{chips}
'
+ f"{actions}"
+ "
"
+ ''
+ )
diff --git a/pyproject.toml b/pyproject.toml
index 59850ac..9739a17 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "nitrostack"
-version = "0.4.2"
+version = "0.5.0"
description = "NitroStack Python SDK — A Python-idiomatic port of the NitroStack MCP framework"
readme = "README.md"
requires-python = ">=3.10"
@@ -16,13 +16,23 @@ dependencies = [
"watchfiles>=0.18.0",
"anyio>=4.0.0",
"packaging>=23.0.0",
+ "certifi>=2026.10.19",
"tomli>=2.0.0; python_version < '3.11'",
+ "posthog>=3,<5",
]
[project.optional-dependencies]
+token-encryption = ["cryptography>=41"]
+code-mode = [
+ "quickjs>=1.19.4",
+]
dev = [
- "pytest>=7.4.0",
+ "cryptography>=41",
+ "setuptools>=70.1",
+ "quickjs>=1.19.4",
"pytest-cov>=4.1.0",
+ "pytest>=8",
+ "pytest-asyncio>=0.23",
"pytest-timeout>=2.3.0",
"httpx>=0.27.0",
"tox>=4.0.0",
@@ -35,7 +45,7 @@ Repository = "https://github.com/nitrocloudofficial/nitrostack-python-sdk"
Issues = "https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues"
[project.scripts]
-nitrostack-py = "nitrostack.cli.main:main"
+nitrostack-py = "nitrostack.cli.entry:main"
[tool.setuptools.packages.find]
include = ["nitrostack*"]
diff --git a/requirements.txt b/requirements.txt
index ebe86ba..982a4e3 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -5,4 +5,5 @@ uvicorn>=0.20.0
watchfiles>=0.18.0
anyio>=4.0.0
packaging>=23.0.0
+certifi>=2026.10.19
tomli>=2.0.0; python_version < "3.11"
diff --git a/scripts/capture_tools_baseline.py b/scripts/capture_tools_baseline.py
new file mode 100644
index 0000000..50b52a2
--- /dev/null
+++ b/scripts/capture_tools_baseline.py
@@ -0,0 +1,56 @@
+
+"""Capture real tools/list responses from the unmodified base SDK."""
+import asyncio
+import json
+import pathlib
+import sys
+
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+import mcp.types as types
+
+from nitrostack.testing import NitroTestingModule
+from tests._baseline_catalog import ERAS, M
+
+OUT = ROOT / "tests" / "fixtures" / "tools_list_baseline.json"
+
+
+async def list_tools(era: str) -> str:
+ harness = await NitroTestingModule.create(M, protocol_era=era)
+ server = harness.app.mcp_server
+
+ response = (
+ await server.request_handlers[types.ListToolsRequest](
+ types.ListToolsRequest(method="tools/list")
+ )
+ ).root
+
+ return response.model_dump_json(
+ by_alias=True,
+ exclude_none=True,
+ )
+
+
+async def main() -> None:
+ baseline = {}
+
+ for era in ERAS:
+ serialized = await list_tools(era)
+ baseline[era] = serialized
+ names = [
+ item["name"]
+ for item in json.loads(serialized)["tools"]
+ ]
+ print(f"{era}: {names}")
+
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ OUT.write_text(
+ json.dumps(baseline, indent=2),
+ encoding="utf-8",
+ )
+ print(f"Wrote {OUT} ({OUT.stat().st_size} bytes)")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/scripts/check_file_lengths.py b/scripts/check_file_lengths.py
new file mode 100755
index 0000000..8f13f6f
--- /dev/null
+++ b/scripts/check_file_lengths.py
@@ -0,0 +1,229 @@
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Dict, List, NamedTuple, Optional, Tuple
+
+DEFAULT_MAX_LINES = 500
+SCOPED_DIRECTORIES = ("nitrostack", "tests", "examples", "scripts")
+REPO_ROOT = Path(__file__).resolve().parents[1]
+DEFAULT_BASELINE_FILE = REPO_ROOT / ".file_length_baseline.json"
+
+
+class Violation(NamedTuple):
+ path: str
+ count: int
+ allowed: int
+ violation_type: str # 'new_file', 'baseline_growth', or 'stale_baseline'
+ message: str
+
+
+def count_physical_lines(file_path: Path | str) -> int:
+ """Count physical lines in a file, matching (Get-Content file).Count semantics.
+
+ Includes blank lines, comments, docstrings, and lines inside multiline strings.
+ A trailing newline does not add a phantom line.
+ """
+ path = Path(file_path)
+ if not path.is_file():
+ return 0
+ with open(path, "rb") as f:
+ content = f.read()
+ return len(content.splitlines())
+
+
+def get_tracked_python_files(
+ repo_root: Path,
+ scoped_dirs: Tuple[str, ...] = SCOPED_DIRECTORIES,
+) -> List[str]:
+ """Return relative POSIX paths of tracked Python files under scoped directories."""
+ try:
+ result = subprocess.run(
+ ["git", "ls-files"],
+ cwd=repo_root,
+ capture_output=True,
+ check=True,
+ text=True,
+ )
+ files = result.stdout.splitlines()
+ except (subprocess.SubprocessError, FileNotFoundError):
+ files = []
+ for d in scoped_dirs:
+ dir_path = repo_root / d
+ if dir_path.is_dir():
+ for root, _, filenames in os.walk(dir_path):
+ for filename in filenames:
+ rel = Path(root, filename).relative_to(repo_root).as_posix()
+ files.append(rel)
+
+ matched = []
+ for f in files:
+ if not f.endswith(".py"):
+ continue
+ # Check if the file is within one of the scoped directories
+ parts = Path(f).parts
+ if parts and parts[0] in scoped_dirs:
+ matched.append(Path(f).as_posix())
+
+ return sorted(matched)
+
+
+def load_baseline(baseline_path: Path) -> Dict[str, int]:
+ """Load baseline mapping of file path -> allowed line count."""
+ if not baseline_path.exists():
+ return {}
+ with open(baseline_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ # Ensure all paths are normalized POSIX strings
+ return {Path(k).as_posix(): int(v) for k, v in data.items()}
+
+
+def save_baseline(baseline_path: Path, baseline: Dict[str, int]) -> None:
+ """Save baseline mapping to JSON sorted alphabetically."""
+ sorted_baseline = {k: baseline[k] for k in sorted(baseline.keys())}
+ with open(baseline_path, "w", encoding="utf-8") as f:
+ json.dump(sorted_baseline, f, indent=2)
+ f.write("\n")
+
+
+def check_files(
+ repo_root: Path,
+ tracked_files: List[str],
+ baseline: Dict[str, int],
+ max_lines: int = DEFAULT_MAX_LINES,
+) -> Tuple[List[Violation], Dict[str, int]]:
+ """Check tracked files against the maximum line limit and ratchet baseline.
+
+ Returns:
+ (violations, new_ratcheted_baseline)
+ """
+ violations: List[Violation] = []
+ ratcheted_baseline: Dict[str, int] = dict(baseline)
+
+ # Track files currently present
+ checked_paths = set(tracked_files)
+
+ for rel_path in tracked_files:
+ full_path = repo_root / rel_path
+ if not full_path.is_file():
+ continue
+
+ count = count_physical_lines(full_path)
+ allowed = baseline.get(rel_path, max_lines)
+
+ if count > allowed:
+ if rel_path in baseline:
+ vtype = "baseline_growth"
+ msg = (
+ f"File grew above baseline: {rel_path} has {count} lines "
+ f"(allowed baseline: {allowed})"
+ )
+ else:
+ vtype = "new_file"
+ msg = (
+ f"File exceeds line limit: {rel_path} has {count} lines "
+ f"(allowed maximum: {allowed})"
+ )
+ violations.append(
+ Violation(
+ path=rel_path,
+ count=count,
+ allowed=allowed,
+ violation_type=vtype,
+ message=msg,
+ )
+ )
+ elif rel_path in baseline:
+ # Ratchet mechanism: file shrank below baseline!
+ if count <= max_lines:
+ # File reached or dropped below standard threshold -> remove from baseline
+ del ratcheted_baseline[rel_path]
+ elif count < allowed:
+ # File shrank, lower the baseline
+ ratcheted_baseline[rel_path] = count
+
+ # Also clean up any baseline entries for files that no longer exist
+ for baseline_file in list(ratcheted_baseline.keys()):
+ if baseline_file not in checked_paths:
+ del ratcheted_baseline[baseline_file]
+
+ return violations, ratcheted_baseline
+
+
+def run_check(
+ repo_root: Path,
+ baseline_path: Path,
+ max_lines: int = DEFAULT_MAX_LINES,
+ update_baseline: bool = False,
+) -> int:
+ """Run checker and report results.
+
+ Returns exit code (0 for success, 1 for violations).
+ """
+ tracked = get_tracked_python_files(repo_root)
+ baseline = load_baseline(baseline_path)
+ violations, ratcheted_baseline = check_files(
+ repo_root=repo_root,
+ tracked_files=tracked,
+ baseline=baseline,
+ max_lines=max_lines,
+ )
+
+ ratchet_needed = ratcheted_baseline != baseline
+
+ if violations:
+ print(f"FAILED: Found {len(violations)} Python file-length violation(s):")
+ for v in violations:
+ print(f" [{v.violation_type}] {v.path}: count={v.count}, allowed={v.allowed}")
+ print(f" -> {v.message}")
+
+ if ratchet_needed:
+ if update_baseline:
+ save_baseline(baseline_path, ratcheted_baseline)
+ print(f"Updated baseline file at {baseline_path} with ratcheted counts.")
+ else:
+ print("\nNOTE: Baseline ratchet improvement detected:")
+ for k, old_count in baseline.items():
+ new_count = ratcheted_baseline.get(k)
+ if new_count is None:
+ print(f" {k}: was {old_count}, now <= {max_lines} (entry removed from baseline)")
+ elif new_count < old_count:
+ print(f" {k}: was {old_count}, lowered to {new_count}")
+ print("Run with --update-baseline to update the baseline file.")
+
+ if violations:
+ return 1
+
+ print(
+ f"SUCCESS: All {len(tracked)} tracked Python files in scope satisfy file-length limits "
+ f"(max {max_lines} lines or within baseline ratchet)."
+ )
+ return 0
+
+
+def main(argv: Optional[List[str]] = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Check Python file lengths against limit (500 lines) and baseline ratchet."
+ )
+ parser.add_argument(
+ "--update-baseline",
+ action="store_true",
+ help="Update the baseline file if files have shrunk or reached <= 500 lines",
+ )
+
+ args = parser.parse_args(argv)
+
+ return run_check(
+ repo_root=REPO_ROOT,
+ baseline_path=DEFAULT_BASELINE_FILE,
+ max_lines=DEFAULT_MAX_LINES,
+ update_baseline=args.update_baseline,
+ )
+
+
+if __name__ == "__main__":
+ sys.exit(main())
\ No newline at end of file
diff --git a/scripts/probe_discovery_port.py b/scripts/probe_discovery_port.py
new file mode 100644
index 0000000..45c842f
--- /dev/null
+++ b/scripts/probe_discovery_port.py
@@ -0,0 +1,64 @@
+"""Does the Python OAuth discovery server survive a busy preferred port?"""
+import os
+import socket
+import time
+import urllib.request
+
+from nitrostack.auth.oauth import OAuthModule, OAuthService
+from nitrostack.core.di import DIContainer
+
+
+def free_port() -> int:
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+port = free_port()
+os.environ.pop("OAUTH_DISCOVERY_PORT", None) # test discovery_port alone
+
+blockers = []
+for host in ("127.0.0.1", "0.0.0.0"):
+ b = socket.socket()
+ try:
+ b.bind((host, port))
+ b.listen(1)
+ blockers.append(b)
+ except OSError as exc:
+ print(f"blocker could not bind {host}:{port}: {exc}")
+ b.close()
+print("busy port:", port)
+
+DIContainer.reset()
+OAuthModule.for_root(
+ resource_uri="https://api.example.com",
+ authorization_servers=["https://idp.example.com"],
+ scopes_supported=["read"],
+ discovery_port=port,
+)
+service = DIContainer.get_instance().resolve(OAuthService)
+try:
+ service.start_discovery_server()
+ time.sleep(1.0) # in case it binds in a background thread
+ server = getattr(service, "_server", None)
+ print("server object:", server)
+ print("bound to:", getattr(server, "server_address", None))
+ bound_port = getattr(service, "bound_port", None)
+ print("reported bound_port:", bound_port)
+ target_port = bound_port or port
+ try:
+ url = f"http://127.0.0.1:{target_port}/.well-known/oauth-protected-resource"
+ with urllib.request.urlopen(url, timeout=2) as resp:
+ print("GET", url, "->", resp.status)
+ except Exception as exc:
+ print("GET failed:", type(exc).__name__, exc)
+except OSError as exc:
+ print("FAILED on busy port:", type(exc).__name__, exc)
+finally:
+ try:
+ service.stop_discovery_server()
+ except Exception as exc:
+ print("stop skipped:", type(exc).__name__, exc)
+ for b in blockers:
+ b.close()
+ DIContainer.reset()
\ No newline at end of file
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/_baseline_catalog.py b/tests/_baseline_catalog.py
new file mode 100644
index 0000000..3092d9f
--- /dev/null
+++ b/tests/_baseline_catalog.py
@@ -0,0 +1,26 @@
+"""Catalog used by both the baseline capture script and the parity test."""
+from pydantic import BaseModel
+
+from nitrostack import ExecutionContext, injectable, module, tool
+
+ERAS = ("legacy", "auto", "modern")
+
+
+class In(BaseModel):
+ q: str = ""
+
+
+@injectable()
+class C:
+ @tool(name="alpha", description="first", input_schema=In)
+ async def alpha(self, input: In, context: ExecutionContext) -> str:
+ return "a"
+
+ @tool(name="beta", description="second", input_schema=In)
+ async def beta(self, input: In, context: ExecutionContext) -> str:
+ return "b"
+
+
+@module(name="m", controllers=[C])
+class M:
+ pass
\ No newline at end of file
diff --git a/tests/conftest.py b/tests/conftest.py
index 66494b0..d0c21c8 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -2,6 +2,8 @@
import pytest
+pytest_plugins = ["nitrostack.testing.pytest_plugin"]
+
from nitrostack.cli.skills import SkillsCloneError
diff --git a/tests/fixtures/tools_list_baseline.json b/tests/fixtures/tools_list_baseline.json
new file mode 100644
index 0000000..e0e9a20
--- /dev/null
+++ b/tests/fixtures/tools_list_baseline.json
@@ -0,0 +1,5 @@
+{
+ "legacy": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}",
+ "auto": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}",
+ "modern": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}"
+}
\ No newline at end of file
diff --git a/tests/http_probe.py b/tests/http_probe.py
new file mode 100644
index 0000000..8679f19
--- /dev/null
+++ b/tests/http_probe.py
@@ -0,0 +1,106 @@
+"""Shared probes of the actual official MCP HTTP mount (no sidecar doubles)."""
+
+import asyncio
+import json
+import os
+from contextlib import contextmanager
+from unittest.mock import patch
+
+from mcp_types import PROTOCOL_VERSION_META_KEY
+from pydantic import BaseModel
+from starlette.testclient import TestClient
+
+from nitrostack import DIContainer, module, resource, tool
+from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app
+from nitrostack.protocol.version import LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION
+
+
+class EchoInput(BaseModel):
+ value: str = "ok"
+
+
+def make_app(era="auto"):
+ """Resolve era deterministically without leaking process environment or DI."""
+ DIContainer.reset()
+
+ class ProbeTools:
+ @tool(name="echo", description="Echo and expose verified context", input_schema=EchoInput,
+ task_support="optional")
+ async def echo(self, input, context):
+ return {"value": input.value, "user": context.user,
+ "protocol_version": context.protocol_version,
+ "mirrored": context.mcp_param_headers}
+
+ @resource(uri="probe://info", name="Probe", description="Readable probe")
+ async def info(self, context):
+ return "probe resource"
+
+ @module(name="http-probe", providers=[ProbeTools])
+ class ProbeModule:
+ pass
+
+ @mcp_app(module=ProbeModule, server=ServerConfig(name="http-probe", protocol_era=era))
+ class ProbeApp:
+ pass
+
+ with patch.dict(os.environ, {"NITRO_MCP_PROTOCOL_VERSION": era, "MCP_STATELESS": ""}):
+ return asyncio.run(McpApplicationFactory.create(ProbeApp))
+
+
+def envelope(method="tools/list", params=None, *, version=MODERN_PROTOCOL_VERSION, modern=True):
+ params = dict(params or {})
+ if modern:
+ params["_meta"] = {
+ PROTOCOL_VERSION_META_KEY: version,
+ "io.modelcontextprotocol/clientInfo": {"name": "http-probe", "version": "1"},
+ "io.modelcontextprotocol/clientCapabilities": {},
+ **params.get("_meta", {}),
+ }
+ return {"jsonrpc": "2.0", "id": "probe", "method": method, "params": params}
+
+
+def headers(method="tools/list", *, name=None, version=MODERN_PROTOCOL_VERSION):
+ result = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
+ "MCP-Protocol-Version": version, "Mcp-Method": method}
+ if name is not None:
+ result["Mcp-Name"] = name
+ return result
+
+
+def decode(response):
+ """Handle JSON or a completed request's SSE response explicitly."""
+ if "text/event-stream" in response.headers.get("content-type", ""):
+ messages = [json.loads(line[5:].strip()) for line in response.text.splitlines()
+ if line.startswith("data:")]
+ return next(message for message in messages if "id" in message)
+ return response.json()
+
+
+def post(client, method="tools/list", params=None, *, modern=True, extra_headers=None,
+ version=MODERN_PROTOCOL_VERSION):
+ return client.post("/mcp", json=envelope(method, params, modern=modern, version=version),
+ headers={**headers(method, name=(params or {}).get("name") or (params or {}).get("uri"),
+ version=version), **(extra_headers or {})})
+
+
+@contextmanager
+def http_client(era="auto", *, app=None, json_response=True, **options):
+ app = app or make_app(era)
+ http = app.get_combined_app(json_response=json_response, **options)
+ try:
+ with TestClient(http) as client:
+ if era == "legacy":
+ response = post(client, "initialize", {
+ "protocolVersion": LEGACY_PROTOCOL_VERSION, "capabilities": {},
+ "clientInfo": {"name": "legacy-probe", "version": "1"},
+ }, modern=False, version=LEGACY_PROTOCOL_VERSION)
+ assert response.status_code == 200, response.text
+ assert "result" in decode(response), response.text
+ session = response.headers.get("mcp-session-id")
+ assert session
+ client.headers["mcp-session-id"] = session
+ client.post("/mcp", json={"jsonrpc": "2.0", "method": "notifications/initialized"},
+ headers=headers("notifications/initialized", version=LEGACY_PROTOCOL_VERSION))
+ yield app, http, client
+ finally:
+ DIContainer.reset()
diff --git a/tests/output_schema_stdio_server.py b/tests/output_schema_stdio_server.py
new file mode 100644
index 0000000..a572276
--- /dev/null
+++ b/tests/output_schema_stdio_server.py
@@ -0,0 +1,46 @@
+"""Tiny stdio server used by tests/test_tool_output_schema.py (run as a subprocess)."""
+
+import asyncio
+from typing import Optional
+
+from pydantic import BaseModel
+
+from nitrostack import ServerConfig, mcp_app, module, tool
+from nitrostack.core.app import McpApplication
+
+
+class Empty(BaseModel):
+ pass
+
+
+class Profile(BaseModel):
+ nickname: Optional[str] = None
+ age: Optional[int] = None
+ name: str = "ada"
+
+
+class Tools:
+ @tool("profile", "Return a profile with empty optional fields", Empty, output_schema=Profile)
+ async def profile(self, input, context):
+ return Profile()
+
+
+@module(name="schema-wire", providers=[Tools])
+class Root:
+ pass
+
+
+@mcp_app(module=Root, server=ServerConfig(name="schema-wire", protocol_era="auto"))
+class App:
+ pass
+
+
+async def main():
+ from nitrostack.transports.stdio import run_stdio, safe_stdio_transport
+
+ with safe_stdio_transport():
+ await run_stdio(McpApplication(App).mcp_server, "auto")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/tests/spillover_transport_support.py b/tests/spillover_transport_support.py
new file mode 100644
index 0000000..86b5278
--- /dev/null
+++ b/tests/spillover_transport_support.py
@@ -0,0 +1,136 @@
+"""Real application and protocol clients for spillover transport regressions."""
+
+import asyncio
+from contextlib import contextmanager
+import json
+from pathlib import Path
+import sys
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from pydantic import BaseModel
+from starlette.testclient import TestClient
+
+from nitrostack import (
+ DataSpilloverInterceptor, FileSpilloverStore, MemorySpilloverStore,
+ module, tool, use_interceptors,
+)
+from nitrostack.core.app import McpApplication, ServerConfig, mcp_app
+
+MODERN_META = {
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
+ "io.modelcontextprotocol/clientInfo": {"name": "spillover-client", "version": "1"},
+ "io.modelcontextprotocol/clientCapabilities": {},
+}
+
+
+class PayloadInput(BaseModel):
+ value: Any = None
+ case: str | None = None
+
+
+def large_value(case):
+ if case == "threshold":
+ return "x" * 65536
+ if case == "threshold-plus-one":
+ return "x" * 65537
+ if case.endswith("MiB"):
+ return "x" * (int(case[:-3]) * 1024 * 1024)
+ if case == "unicode":
+ return "é🚀" * 200000
+ if case == "escaped":
+ return '\\"\n\t' * 100000
+ if case == "rows":
+ return [{"row": i, "value": "row"} for i in range(100000)]
+ if case == "dictionary":
+ return {str(i): i for i in range(50000)}
+ if case == "nested":
+ return [{"chunks": ["x" * (1024 * 1024)] * 6}]
+ return "x" * (10 * 1024 * 1024 + 1)
+
+
+def build_app(backend, root, era="legacy", threshold=64 * 1024,
+ prefix="resource://data-spillover/"):
+ options = dict(max_bytes=10 * 1024 * 1024, max_total_bytes=64 * 1024 * 1024)
+ store = MemorySpilloverStore(**options) if backend == "memory" else FileSpilloverStore(root, **options)
+ interceptor = DataSpilloverInterceptor(threshold, store, prefix)
+
+ class Tools:
+ @tool("payload", "Return a payload", PayloadInput, task_support="optional")
+ @use_interceptors(interceptor)
+ async def payload(self, input, context):
+ return large_value(input.case) if input.case is not None else input.value
+
+ @module(name="spillover-wire", providers=[Tools])
+ class Root:
+ pass
+
+ @mcp_app(module=Root, server=ServerConfig(name="spillover-wire", protocol_era=era))
+ class App:
+ pass
+
+ return McpApplication(App)
+
+
+class HttpPeer:
+ def __init__(self, client, era="legacy", token=None):
+ self.client, self.era = client, era
+ self.headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
+ if token:
+ self.headers["Authorization"] = "Bearer " + token
+ self.next_id = 1
+ if era == "legacy":
+ response = self.rpc("initialize", {
+ "protocolVersion": "2025-06-18", "capabilities": {},
+ "clientInfo": {"name": "spillover-client", "version": "1"},
+ })
+ assert "result" in response
+ self.headers["mcp-session-id"] = self.last_response.headers["mcp-session-id"]
+ initialized = client.post("/mcp", headers=self.headers, json={
+ "jsonrpc": "2.0", "method": "notifications/initialized",
+ })
+ assert initialized.status_code == 202
+ else:
+ self.headers["MCP-Protocol-Version"] = "2026-07-28"
+
+ def rpc(self, method, params):
+ params = dict(params)
+ headers = {**self.headers, "Mcp-Method": method}
+ if method == "tools/call":
+ headers["Mcp-Name"] = params["name"]
+ elif method == "resources/read":
+ headers["Mcp-Name"] = params["uri"]
+ if self.era != "legacy":
+ params["_meta"] = {**params.get("_meta", {}), **MODERN_META}
+ self.last_response = self.client.post("/mcp", headers=headers, json={
+ "jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params,
+ })
+ self.next_id += 1
+ assert self.last_response.status_code == 200, self.last_response.text
+ return self.last_response.json()
+
+ def call(self, value, **extra):
+ return self.rpc("tools/call", {"name": "payload", "arguments": {"value": value}, **extra})
+
+ def read(self, uri):
+ return self.rpc("resources/read", {"uri": uri})
+
+
+@contextmanager
+def http_app(backend, root, **options):
+ app = build_app(backend, root, **options)
+ with TestClient(app.get_combined_app(json_response=True)) as client:
+ yield client
+
+
+async def stdio_main():
+ from nitrostack.transports.stdio import run_stdio, safe_stdio_transport
+
+ with safe_stdio_transport():
+ app = build_app(sys.argv[1], sys.argv[2], era="auto", threshold=16)
+ await run_stdio(app.mcp_server, "auto")
+
+
+if __name__ == "__main__":
+ asyncio.run(stdio_main())
diff --git a/tests/support/oauth_client.py b/tests/support/oauth_client.py
new file mode 100644
index 0000000..3cd949a
--- /dev/null
+++ b/tests/support/oauth_client.py
@@ -0,0 +1,39 @@
+"""Shared OAuth client fixtures without network access."""
+
+import json
+from unittest.mock import AsyncMock
+
+from nitrostack import OAuth2Client, StoredToken
+from nitrostack.auth.client import _Response
+
+ACCESS = "ACCESS_SENTINEL_NEVER_LOG"
+REFRESH = "REFRESH_SENTINEL_NEVER_LOG"
+SECRET = "CLIENT_SENTINEL_NEVER_LOG: with spaces"
+ENDPOINT = "https://issuer.example/token"
+
+
+def response(value=None, *, status=200, headers=None, raw=None):
+ body = raw if raw is not None else json.dumps(value if value is not None else {"access_token": ACCESS}).encode()
+ return _Response(status, headers or {}, body)
+
+
+def client(**overrides):
+ return OAuth2Client({"client_id": "client:id", "client_secret": SECRET,
+ "issuer": "https://issuer.example", "redirect_uri": "http://127.0.0.1/callback",
+ "authorization_endpoint": "https://issuer.example/authorize?audience=api&state=old&scope=old",
+ "token_endpoint": ENDPOINT, "revocation_endpoint": "https://issuer.example/revoke",
+ "registration_endpoint": "https://issuer.example/register", **overrides})
+
+
+def install_transport(monkeypatch, oauth, *responses):
+ send = AsyncMock(side_effect=list(responses) if responses else None)
+ if not responses:
+ send.return_value = response()
+ monkeypatch.setattr(oauth, "_send", send)
+ return send
+
+
+async def saved(oauth, key="alice", refresh=REFRESH):
+ token = StoredToken(ACCESS, "Bearer", 1, refresh, "read", "https://resource.example")
+ await oauth.store.save_token(key, token)
+ return token
diff --git a/tests/support/project_templates_probe.py b/tests/support/project_templates_probe.py
new file mode 100644
index 0000000..510ca0e
--- /dev/null
+++ b/tests/support/project_templates_probe.py
@@ -0,0 +1,112 @@
+"""Subprocess entry points for generated projects; never contacts external services."""
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import json
+import multiprocessing
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock, patch
+
+
+def cli(args):
+ from nitrostack.cli import skills, upgrade
+ from nitrostack.cli.main import main
+
+ def offline():
+ raise skills.SkillsCloneError("offline template test")
+
+ skills.clone_skills_repo = offline
+ upgrade.verify_nitrostack_version = lambda *args, **kwargs: None
+ upgrade.fetch_latest_nitrostack_version = lambda *args, **kwargs: "0.3.2"
+ sys.argv = ["nitrostack-py", *args]
+ main()
+
+
+async def behavior(kind):
+ sys.path.insert(0, str(Path.cwd()))
+ # Import/bootstrap must not start transports or sandbox workers.
+ from nitrostack.transforms.code_mode.worker_pool import WorkerPool
+ with patch.object(WorkerPool, "__init__", side_effect=AssertionError("eager worker")):
+ import main as project
+ from nitrostack import McpApplicationFactory
+ app = await McpApplicationFactory.create(project.Application)
+ assert multiprocessing.active_children() == []
+ import mcp.types as types
+ from nitrostack.testing import NitroTestingModule
+ harness = NitroTestingModule(app)
+ listed = await app.mcp_server.request_handlers[types.ListToolsRequest](types.ListToolsRequest(method="tools/list"))
+ names = {t.name for t in listed.root.tools}
+ if kind == "enterprise-search":
+ assert names == {"search_tools", "call_tool", "finance_get_financial_summary", "inventory_report", "support_get_system_status"}
+ browse = await harness.call_tool("search_tools", {"query": ""})
+ assert browse["total_tools"] == 6
+ ranked = await harness.call_tool("search_tools", {"query": "overdue invoices"})
+ assert ranked["results"][0]["name"] == "finance_list_invoices"
+ assert ranked == await harness.call_tool("search_tools", {"query": "overdue invoices"})
+ assert (await harness.call_tool("search_tools", {"query": "zzzznothingmatches"}))["results"] == []
+ result = await harness.call_tool("call_tool", {"name": "finance_list_invoices", "arguments": {"overdue_only": True}})
+ assert [row["id"] for row in result["invoices"]] == ["INV-001"]
+ result["invoices"][0]["amount"] = 0
+ result = await harness.call_tool("call_tool", {"name": "finance_list_invoices", "arguments": {"overdue_only": True}})
+ assert result["invoices"][0]["amount"] == 1200
+ else:
+ assert names == {"search", "get_schema", "execute"}
+ search = await harness.call_tool("search", {"query": "inventory"})
+ assert search["total_tools"] == 7
+ assert {tool["name"] for tool in search["tools"]} == {"inventory_check_stock", "inventory_report"}
+ schema = await harness.call_tool("get_schema", {"name": "inventory_check_stock"})
+ stock_schema = schema["schemas"]["inventory_check_stock"]["inputSchema"]
+ assert stock_schema["properties"]["sku"]["type"] == "string"
+ assert "sku" in stock_schema["required"]
+ assert project.CODE_MODE._sandbox is None
+ try:
+ if sys.platform == "win32" and importlib.util.find_spec("quickjs") is None:
+ # Exercise the documented unavailable-binding error, never pretend a fake is QuickJS.
+ result = await harness.call_tool("execute", {"code": "return 1;"})
+ assert "required for Code Mode" in json.dumps(result)
+ print("NATIVE_QUICKJS_UNAVAILABLE: verified diagnostic; real execution runs on Linux")
+ else:
+ result = await harness.call_tool("execute", {"code": Path("scripts/sample-batch.js").read_text()})
+ assert result["success"] is True, result
+ assert result["value"]["total_units"] == 18
+ assert result["toolCallCount"] == 3
+ pool = project.CODE_MODE.sandbox
+ workers = [slot.process for slot in pool._all_slots]
+ project.CODE_MODE.limits.timeout_ms = 200
+ failure = await harness.call_tool("execute", {"code": "while (true) {}"})
+ assert failure["success"] is False, failure
+ await project.CODE_MODE.dispose()
+ assert all(not worker.is_alive() for worker in workers)
+ assert multiprocessing.active_children() == []
+ finally:
+ await project.CODE_MODE.dispose()
+ print("BEHAVIOR_OK", kind)
+
+
+async def cleanup():
+ sys.path.insert(0, str(Path.cwd()))
+ import main as project
+ from types import SimpleNamespace
+ for fail_creation in (True, False):
+ create = AsyncMock(side_effect=RuntimeError("startup failed")) if fail_creation else AsyncMock(return_value=SimpleNamespace(start=AsyncMock(side_effect=RuntimeError("startup failed"))))
+ with patch.object(project.McpApplicationFactory, "create", create), patch.object(project.CODE_MODE, "dispose", new_callable=AsyncMock) as dispose:
+ try:
+ await project.main()
+ except RuntimeError as exc:
+ assert str(exc) == "startup failed"
+ else:
+ raise AssertionError("expected startup failure")
+ dispose.assert_awaited_once()
+ print("CLEANUP_OK")
+
+
+if __name__ == "__main__":
+ action = sys.argv[1]
+ if action == "cli":
+ cli(sys.argv[2:])
+ elif action == "cleanup":
+ asyncio.run(cleanup())
+ else:
+ asyncio.run(behavior(action))
diff --git a/tests/support/widget_registry_probe.py b/tests/support/widget_registry_probe.py
new file mode 100644
index 0000000..ab39527
--- /dev/null
+++ b/tests/support/widget_registry_probe.py
@@ -0,0 +1,61 @@
+"""Isolated template bootstrap and real stdio server for registry integration tests."""
+
+import asyncio
+import json
+import os
+from pathlib import Path
+import socket
+import sys
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+
+def template_manifest(template):
+ # Fail if bootstrap accidentally tries to contact any external service.
+ def no_network(*args, **kwargs):
+ raise AssertionError("Template bootstrap must not make network requests")
+
+ socket.socket.connect = no_network
+ socket.create_connection = no_network
+ socket.getaddrinfo = no_network
+ os.environ["DUFFEL_API_KEY"] = "test"
+ path = ROOT / "nitrostack" / "templates" / template
+ sys.path.insert(0, str(path))
+ os.chdir(path)
+ from app_module import AppModule
+ from nitrostack.core.app import McpApplication
+
+ app = McpApplication(AppModule)
+ return app.widget_registry.get_manifest().to_dict()
+
+
+async def stdio_server():
+ from pydantic import BaseModel
+ from nitrostack import ExecutionContext, WidgetOptions, module, tool, widget
+ from nitrostack.core.app import McpApplication
+ from nitrostack.transports.stdio import run_stdio, safe_stdio_transport
+
+ class Empty(BaseModel):
+ pass
+
+ class Tools:
+ @tool("example", "Example", Empty)
+ @widget(WidgetOptions(route="stdio-example", html="