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 @@ NitroStack - Build, test, and deploy MCP servers in one place | Product Hunt -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.
'; - }} - return; - }} - if (typeof mapboxgl === "undefined") {{ - if ((attempt || 0) < 80) {{ - setTimeout(function() {{ mountMap((attempt || 0) + 1); }}, 50); - }} - return; - }} - window.__nitroMapSig = sig; - if (window.__nitroMap) {{ - window.__nitroMap.remove(); - window.__nitroMap = null; - }} - mapboxgl.accessToken = window.__NITRO_MAPBOX_TOKEN; - const first = (shops[0] && shops[0].coords) || [-122.4194, 37.7749]; - const map = new mapboxgl.Map({{ - container: mapEl, - style: "mapbox://styles/mapbox/streets-v12", - center: first, - zoom: 12, - cooperativeGestures: false, - fadeDuration: 0 - }}); - map.addControl(new mapboxgl.NavigationControl({{ showCompass: false }}), "top-right"); - map.addControl(new mapboxgl.FullscreenControl(), "top-right"); - shops.forEach(function(shop) {{ - const el = document.createElement("div"); - el.style.backgroundImage = "url(https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png)"; - el.style.width = "30px"; - el.style.height = "40px"; - el.style.backgroundSize = "100%"; - el.style.cursor = "pointer"; - el.title = shop.name || shop.id || ""; - el.addEventListener("click", function() {{ - if (window.nitrostack) window.nitrostack.callTool("show_pizza_shop", {{ shopId: shop.id || "" }}); - }}); - new mapboxgl.Marker(el).setLngLat(shop.coords).addTo(map); - }}); - if (shops.length > 1) {{ - const bounds = new mapboxgl.LngLatBounds(); - shops.forEach(function(s) {{ bounds.extend(s.coords); }}); - map.fitBounds(bounds, {{ padding: 60, maxZoom: 14, duration: 0 }}); - }} - map.once("idle", function() {{ - try {{ map.resize(); }} catch (e) {{}} - revealLive(); - }}); - window.__nitroMap = map; - }} - mountMap(0); -}}; -""".strip() - -_PIZZA_SHOP_JS = """ -window.__nitroWidgetRender = function(data) { - const shop = data && (data.shop || data); - const hero = document.getElementById("hero"); - if (!shop || !shop.name) { - const desc = document.getElementById("desc"); - if (desc) desc.textContent = "Waiting for show_pizza_shop result."; - return; - } - if (shop.image && hero) { - hero.src = shop.image; - hero.style.display = "block"; - } else if (hero) { - hero.style.display = "none"; - } - document.getElementById("name").textContent = shop.name; - document.getElementById("rating").textContent = - shop.rating != null ? "★ " + shop.rating + " (" + (shop.reviews || 0) + " reviews)" : ""; - document.getElementById("desc").textContent = shop.description || ""; - document.getElementById("addr").textContent = shop.address || ""; - const hours = shop.hours ? (shop.hours.open + " – " + shop.hours.close) : ""; - document.getElementById("hours").textContent = hours ? "Hours: " + hours : ""; - document.getElementById("phone").textContent = shop.phone || ""; - const chips = document.getElementById("chips"); - chips.innerHTML = ""; - (shop.specialties || []).forEach(function(item) { - const chip = document.createElement("span"); - chip.className = "chip"; - chip.textContent = item; - chips.appendChild(chip); - }); - const actions = document.getElementById("actions"); - if (actions) { - actions.innerHTML = ""; - function addLink(label, url, primary) { - if (!url) return; - const a = document.createElement("a"); - a.className = primary ? "ns-btn ns-btn-primary" : "ns-btn"; - a.setAttribute("data-open-link", url); - a.href = url; - a.textContent = label; - actions.appendChild(a); - } - let maps = ""; - if (Array.isArray(shop.coords) && shop.coords.length === 2) { - maps = "https://www.google.com/maps/search/?api=1&query=" + shop.coords[1] + "," + shop.coords[0]; - } else if (shop.address) { - maps = "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(shop.address); - } - addLink("Maps", maps, false); - if (shop.phone) { - const tel = String(shop.phone).replace(/[^0-9+]/g, ""); - if (tel) addLink("Call", "tel:" + tel, false); - } - addLink("Website", shop.website || "", true); - } -}; -""".strip() - -_CALC_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data) return; - const expr = document.getElementById("expr"); - const result = document.getElementById("result"); - if (data.expression) expr.textContent = data.expression; - if (data.result != null) result.textContent = String(data.result); - else if (data.value != null) result.textContent = String(data.value); -}; -""".strip() - -_CARD_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data) return; - const name = document.getElementById("name"); - const price = document.getElementById("price"); - const desc = document.getElementById("desc"); - if (name) name.textContent = data.name || "—"; - if (price) price.textContent = data.price != null ? "$" + Number(data.price).toFixed(2) : "—"; - if (desc) desc.textContent = data.description || ""; -}; -""".strip() - -_TABLE_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data || !Array.isArray(data.rows)) return; - const cols = data.columns || Object.keys(data.rows[0] || {}); - const header = document.getElementById("header"); - const body = document.getElementById("body"); - if (!header || !body) return; - header.innerHTML = ""; - body.innerHTML = ""; - cols.forEach(function(c) { - const th = document.createElement("th"); - th.textContent = c; - header.appendChild(th); - }); - data.rows.forEach(function(row) { - const tr = document.createElement("tr"); - cols.forEach(function(c) { - const td = document.createElement("td"); - td.textContent = row[c] ?? ""; - tr.appendChild(td); - }); - body.appendChild(tr); - }); -}; -""".strip() - -_CHART_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data) return; - const title = document.getElementById("title"); - const chart = document.getElementById("chart"); - if (title) title.textContent = data.title || "Chart"; - if (!chart) return; - chart.innerHTML = ""; - const items = data.items || []; - const max = Math.max.apply(null, items.map(function(i) { return i.value || 0; }).concat([1])); - items.forEach(function(item) { - const wrap = document.createElement("div"); - wrap.className = "bar-wrap"; - const bar = document.createElement("div"); - bar.className = "bar"; - bar.style.height = (((item.value || 0) / max) * 140) + "px"; - const label = document.createElement("div"); - label.className = "label"; - label.textContent = item.label || ""; - wrap.appendChild(bar); - wrap.appendChild(label); - chart.appendChild(wrap); - }); -}; -""".strip() - - -_FLIGHT_SEARCH_JS = """ -window.__nitroWidgetRender = function(data) { - const list = document.getElementById("list"); - const meta = document.getElementById("meta"); - if (!list) return; - const offers = (data && (data.offers || data.results)) || []; - const params = (data && data.searchParams) || {}; - const total = (data && data.totalOffers != null) ? data.totalOffers : offers.length; - if (meta) { - meta.textContent = (params.origin && params.destination) - ? (params.origin + " → " + params.destination + " · " + total + " offer" + (total === 1 ? "" : "s")) - : (total + " offer" + (total === 1 ? "" : "s")); - } - list.innerHTML = ""; - if (!offers.length) { - list.innerHTML = '
No flight offers.
'; - return; - } - function code(p) { - if (!p) return ""; - if (typeof p === "string") return p; - return p.iata_code || p.iataCode || p.code || ""; - } - function legs(offer) { - if (offer.slices && offer.slices.length) return offer.slices; - const out = []; - if (offer.outbound) out.push(offer.outbound); - if (offer.return) out.push(offer.return); - return out; - } - offers.forEach(function(offer) { - const el = document.createElement("article"); - el.className = "offer ns-card"; - el.setAttribute("data-call-tool", "get_flight_details"); - el.setAttribute("data-args", JSON.stringify({ offerId: offer.id || "" })); - el.setAttribute("role", "button"); - el.tabIndex = 0; - const amount = offer.total_amount || offer.totalAmount || ""; - const currency = offer.total_currency || offer.totalCurrency || ""; - el.innerHTML = '
'; - el.querySelector(".price").textContent = amount + (currency ? " " + currency : ""); - el.querySelector(".id").textContent = offer.id || ""; - legs(offer).forEach(function(sl) { - const s = document.createElement("div"); - s.className = "slice"; - s.textContent = code(sl.origin) + " → " + code(sl.destination) + " · " + (sl.duration || ""); - el.appendChild(s); - }); - list.appendChild(el); - }); -}; -""".strip() - -_AIRPORT_JS = """ -window.__nitroWidgetRender = function(data) { - const list = document.getElementById("list"); - const meta = document.getElementById("meta"); - if (!list) return; - const results = (data && (data.results || data.airports || data.places)) || []; - if (meta) meta.textContent = "Query: " + ((data && data.query) || "") + " · " + results.length + " result(s)"; - list.innerHTML = ""; - if (!results.length) { - list.innerHTML = '
No airports found.
'; - return; - } - results.forEach(function(item) { - const el = document.createElement("div"); - el.className = "row"; - el.innerHTML = '
'; - el.querySelector(".code").textContent = item.iata_code || item.iataCode || ""; - el.querySelector(".name").textContent = item.name || ""; - el.querySelector(".muted").textContent = (item.city_name || item.cityName || item.city || "") + " · " + (item.type || "airport"); - list.appendChild(el); - }); -}; -""".strip() - - -def _place_code_js() -> str: - return """ - function code(p) { - if (!p) return ""; - if (typeof p === "string") return p; - return p.iata_code || p.iataCode || p.code || ""; - } - function money(amount, currency) { - if (amount == null || amount === "") return ""; - return String(amount) + (currency ? " " + currency : ""); - } - function sliceHtml(sl) { - const origin = code(sl.origin); - const dest = code(sl.destination); - const wrap = document.createElement("div"); - wrap.className = "slice"; - const title = document.createElement("strong"); - title.textContent = origin + " → " + dest; - const times = document.createElement("div"); - times.className = "muted"; - times.textContent = (sl.departing_at || sl.departingAt || sl.departureTime || "") + - " – " + (sl.arriving_at || sl.arrivingAt || sl.arrivalTime || "") + - " · " + (sl.duration || ""); - wrap.appendChild(title); - wrap.appendChild(times); - return wrap; - } -""".strip() - - -_FLIGHT_DETAILS_JS = f""" -window.__nitroWidgetRender = function(data) {{ - const meta = document.getElementById("meta"); - const root = document.getElementById("root"); - if (!root) return; - if (!data) {{ - if (meta) meta.textContent = "Waiting for get_flight_details result."; - return; - }} -{_place_code_js()} - const amount = data.total_amount || data.totalAmount || ""; - const currency = data.total_currency || data.totalCurrency || ""; - if (meta) meta.textContent = "Offer " + (data.id || "") + " · " + money(amount, currency); - root.innerHTML = ""; - (data.slices || []).forEach(function(sl) {{ root.appendChild(sliceHtml(sl)); }}); - if (data.id) {{ - const actions = document.createElement("div"); - actions.className = "ns-actions"; - const btn = document.createElement("button"); - btn.type = "button"; - btn.className = "ns-btn ns-btn-primary"; - btn.setAttribute("data-call-tool", "get_seat_map"); - btn.setAttribute("data-args", JSON.stringify({{ offerId: data.id }})); - btn.textContent = "Seat map"; - actions.appendChild(btn); - root.appendChild(actions); - }} -}}; -""".strip() - -_ORDER_SUMMARY_JS = f""" -window.__nitroWidgetRender = function(data) {{ - const root = document.getElementById("root"); - const card = document.querySelector(".card"); - if (!data) return; -{_place_code_js()} - const status = data.status || "held"; - const ref = data.booking_reference || data.bookingReference || ""; - const orderId = data.id || data.orderId || ""; - const amount = data.total_amount || data.totalAmount || ""; - const currency = data.total_currency || data.totalCurrency || ""; - const host = card || root; - if (!host) return; - host.innerHTML = ""; - const h1 = document.createElement("h1"); - h1.textContent = "Order " + status; - const meta = document.createElement("div"); - meta.className = "meta"; - meta.textContent = "Ref " + ref + " · " + orderId; - const price = document.createElement("div"); - price.className = "price"; - price.textContent = money(amount, currency); - host.appendChild(h1); - host.appendChild(meta); - host.appendChild(price); - const paxTitle = document.createElement("h2"); - paxTitle.textContent = "Passengers"; - host.appendChild(paxTitle); - const passengers = data.passengers || []; - if (!passengers.length) {{ - const empty = document.createElement("div"); - empty.className = "muted"; - empty.textContent = "None listed"; - host.appendChild(empty); - }} - passengers.forEach(function(p) {{ - const line = document.createElement("div"); - line.className = "muted"; - line.textContent = p.name || [p.given_name || p.givenName, p.family_name || p.familyName].filter(Boolean).join(" ") || p.id || ""; - host.appendChild(line); - }}); - const itin = document.createElement("h2"); - itin.textContent = "Itinerary"; - host.appendChild(itin); - (data.slices || []).forEach(function(sl) {{ host.appendChild(sliceHtml(sl)); }}); - if (orderId && String(status).toLowerCase().indexOf("cancel") < 0) {{ - const actions = document.createElement("div"); - actions.className = "ns-actions"; - const btn = document.createElement("button"); - btn.type = "button"; - btn.className = "ns-btn"; - btn.setAttribute("data-call-tool", "cancel_order"); - btn.setAttribute("data-args", JSON.stringify({{ orderId: orderId }})); - btn.textContent = "Cancel order"; - actions.appendChild(btn); - host.appendChild(actions); - }} -}}; -""".strip() - -_SEAT_JS = """ -window.__nitroWidgetRender = function(data) { - const meta = document.getElementById("meta"); - const root = document.getElementById("root"); - if (!root) return; - if (!data) { - if (meta) meta.textContent = "Waiting for get_seat_map result."; - return; - } - if (meta) meta.textContent = "Offer " + (data.offerId || data.offer_id || ""); - root.innerHTML = ""; - const cabins = data.cabins || []; - if (!cabins.length) { - root.innerHTML = '
No seat map data.
'; - return; - } - cabins.forEach(function(cabin) { - const h2 = document.createElement("h2"); - h2.textContent = cabin.cabin_class || cabin.cabinClass || "cabin"; - root.appendChild(h2); - (cabin.rows || []).forEach(function(row) { - const line = document.createElement("div"); - line.className = "seat-row"; - const rn = document.createElement("span"); - rn.className = "rn"; - rn.textContent = row.row_number || row.rowNumber || ""; - line.appendChild(rn); - let seats = row.seats || row.elements || []; - if (!seats.length) { - (row.sections || []).forEach(function(section) { - seats = seats.concat(section.elements || []); - }); - } - seats.forEach(function(seat) { - if (seat.type && seat.type !== "seat") return; - const cell = document.createElement("span"); - const available = seat.available != null ? seat.available : (seat.available_services != null); - cell.className = available ? "seat ok" : "seat no"; - cell.textContent = seat.designator || seat.id || seat.column || ""; - line.appendChild(cell); - }); - root.appendChild(line); - }); - }); -}; -""".strip() - -_CANCEL_JS = """ -window.__nitroWidgetRender = function(data) { - const card = document.querySelector(".card"); - if (!card || !data) return; - const status = data.status || "cancelled"; - const cid = data.id || data.cancellationId || ""; - const refund = data.refund_amount || data.refundAmount || ""; - const currency = data.refund_currency || data.refundCurrency || ""; - card.innerHTML = ""; - const h1 = document.createElement("h1"); - h1.textContent = "Booking cancelled"; - const meta = document.createElement("div"); - meta.className = "meta"; - meta.textContent = status + " · " + cid; - const p = document.createElement("p"); - p.textContent = data.message || "Booking cancelled."; - const price = document.createElement("div"); - price.className = "price"; - price.textContent = "Refund " + (refund ? (refund + (currency ? " " + currency : "")) : "n/a"); - card.appendChild(h1); - card.appendChild(meta); - card.appendChild(p); - card.appendChild(price); -}; -""".strip() - - -def _page( - title: str, - styles: str, - body: str, - render_js: str, - data: Any | None, - extra_head: str = "", - flush: bool = False, - chrome: bool = True, -) -> str: - return wrap_widget_page( - title=title, - styles=styles, - body=body, - render_js=render_js, - data=data, - extra_head=extra_head, - flush=flush, - chrome=chrome, - ) - - -def build_generic_widget(route: str, data: Any | None = None) -> str: - return _page(route, _GENERIC_CSS, render_body(route, data), _generic_render_js(), data) - - -def build_missing_widget(route: str, data: Any | None = None) -> str: - return _page( - f"Missing widget: {route}", - _MISSING_CSS, - missing_body(route), - _generic_render_js(), - data, - ) - - -def build_pizza_list_widget(data: Any | None = None) -> str: - return _page("Pizza shops", _PIZZA_LIST_CSS, render_body("pizza-list", data), _PIZZA_LIST_JS, data) - - -def build_pizza_map_widget(data: Any | None = None) -> str: - return _page( - "Pizza map", - _PIZZA_MAP_CSS, - render_body("pizza-map", data), - _pizza_map_js(), - data, - extra_head=_MAPBOX_HEAD, - flush=True, - ) - - -def build_pizza_shop_widget(data: Any | None = None) -> str: - return _page("Pizza shop", _PIZZA_SHOP_CSS, render_body("pizza-shop", data), _PIZZA_SHOP_JS, data) - - -def build_calculator_result_widget(data: Any | None = None) -> str: - return _page( - "Calculator result", - _CALC_CSS, - render_body("calculator-result", data), - _CALC_JS, - data, - ) - - -def build_card_widget(data: Any | None = None) -> str: - return _page("Product Card", _CARD_CSS, render_body("card", data), _CARD_JS, data) - - -def build_table_widget(data: Any | None = None) -> str: - return _page("Data Table", _TABLE_CSS, render_body("table", data), _TABLE_JS, data) - - -def build_chart_widget(data: Any | None = None) -> str: - return _page("Bar Chart", _CHART_CSS, render_body("chart", data), _CHART_JS, data) - - -def build_flight_search_results_widget(data: Any | None = None) -> str: - return _page( - "Flight search", - _FLIGHT_CSS, - render_body("flight-search-results", data), - _FLIGHT_SEARCH_JS, - data, - ) - - -def build_flight_details_widget(data: Any | None = None) -> str: - return _page( - "Flight details", - _FLIGHT_CSS, - render_body("flight-details", data), - _FLIGHT_DETAILS_JS, - data, - ) - - -def build_airport_search_widget(data: Any | None = None) -> str: - return _page( - "Airport search", - _FLIGHT_CSS, - render_body("airport-search", data), - _AIRPORT_JS, - data, - ) - - -def build_order_summary_widget(data: Any | None = None) -> str: - return _page( - "Order summary", - _FLIGHT_CSS, - render_body("order-summary", data), - _ORDER_SUMMARY_JS, - data, - ) - - -def build_seat_selection_widget(data: Any | None = None) -> str: - return _page( - "Seat map", - _FLIGHT_CSS, - render_body("seat-selection", data), - _SEAT_JS, - data, - ) +from __future__ import annotations +from typing import Any, Callable, Dict, Optional -def build_order_cancellation_widget(data: Any | None = None) -> str: - return _page( - "Cancellation", - _FLIGHT_CSS, - render_body("order-cancellation", data), - _CANCEL_JS, - data, - ) +from nitrostack.widgets.host_bridge import wrap_widget_page # noqa: F401 +from nitrostack.widgets.views import missing_body, render_body # noqa: F401 +from nitrostack.widgets.route_templates_generic import ( # noqa: F401 + _generic_render_js, + _CALC_CSS, + _CARD_CSS, + _TABLE_CSS, + _CHART_CSS, + _GENERIC_CSS, + _MISSING_CSS, + _CALC_JS, + _CARD_JS, + _TABLE_JS, + _CHART_JS, + _page, + build_generic_widget, + build_missing_widget, + build_calculator_result_widget, + build_card_widget, + build_table_widget, + build_chart_widget, +) +from nitrostack.widgets.route_templates_pizza import ( # noqa: F401 + _PIZZA_LIST_CSS, + _PIZZA_MAP_CSS, + _PIZZA_SHOP_CSS, + _PIZZA_LIST_JS, + _MAPBOX_HEAD, + _pizza_map_js, + _PIZZA_SHOP_JS, + build_pizza_list_widget, + build_pizza_map_widget, + build_pizza_shop_widget, +) +from nitrostack.widgets.route_templates_flight import ( # noqa: F401 + _FLIGHT_CSS, + _FLIGHT_SEARCH_JS, + _AIRPORT_JS, + _place_code_js, + _FLIGHT_DETAILS_JS, + _ORDER_SUMMARY_JS, + _SEAT_JS, + _CANCEL_JS, + build_flight_search_results_widget, + build_flight_details_widget, + build_airport_search_widget, + build_order_summary_widget, + build_seat_selection_widget, + build_order_cancellation_widget, +) _ROUTE_BUILDERS: Dict[str, Callable[[Any | None], str]] = { diff --git a/nitrostack/widgets/route_templates_flight.py b/nitrostack/widgets/route_templates_flight.py new file mode 100644 index 0000000..8736783 --- /dev/null +++ b/nitrostack/widgets/route_templates_flight.py @@ -0,0 +1,357 @@ +"""Flight and order widget templates (CSS and render JS).""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.route_templates_generic import _page +from nitrostack.widgets.views import render_body + + +_FLIGHT_CSS = """ + :root { --ns-accent: #0369a1; --ns-accent-soft: #e0f2fe; } + .offer, .card, #list .row { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 12px; margin-bottom: 10px; } + .row { display: flex; gap: 12px; align-items: center; } + .id { font-size: 0.8rem; color: var(--ns-muted); } + .code { font-size: 1.1rem; font-weight: 800; min-width: 3rem; } + .slice { margin-top: 8px; } + .seat-row { display: flex; gap: 6px; align-items: center; margin: 4px 0; } + .rn { width: 2rem; font-size: 0.8rem; color: var(--ns-muted); } + .seat { display: inline-block; min-width: 2.4rem; text-align: center; padding: 4px; border-radius: 6px; font-size: 0.75rem; } +""" + + +_FLIGHT_SEARCH_JS = """ +window.__nitroWidgetRender = function(data) { + const list = document.getElementById("list"); + const meta = document.getElementById("meta"); + if (!list) return; + const offers = (data && (data.offers || data.results)) || []; + const params = (data && data.searchParams) || {}; + const total = (data && data.totalOffers != null) ? data.totalOffers : offers.length; + if (meta) { + meta.textContent = (params.origin && params.destination) + ? (params.origin + " → " + params.destination + " · " + total + " offer" + (total === 1 ? "" : "s")) + : (total + " offer" + (total === 1 ? "" : "s")); + } + list.innerHTML = ""; + if (!offers.length) { + list.innerHTML = '
No flight offers.
'; + return; + } + function code(p) { + if (!p) return ""; + if (typeof p === "string") return p; + return p.iata_code || p.iataCode || p.code || ""; + } + function legs(offer) { + if (offer.slices && offer.slices.length) return offer.slices; + const out = []; + if (offer.outbound) out.push(offer.outbound); + if (offer.return) out.push(offer.return); + return out; + } + offers.forEach(function(offer) { + const el = document.createElement("article"); + el.className = "offer ns-card"; + el.setAttribute("data-call-tool", "get_flight_details"); + el.setAttribute("data-args", JSON.stringify({ offerId: offer.id || "" })); + el.setAttribute("role", "button"); + el.tabIndex = 0; + const amount = offer.total_amount || offer.totalAmount || ""; + const currency = offer.total_currency || offer.totalCurrency || ""; + el.innerHTML = '
'; + el.querySelector(".price").textContent = amount + (currency ? " " + currency : ""); + el.querySelector(".id").textContent = offer.id || ""; + legs(offer).forEach(function(sl) { + const s = document.createElement("div"); + s.className = "slice"; + s.textContent = code(sl.origin) + " → " + code(sl.destination) + " · " + (sl.duration || ""); + el.appendChild(s); + }); + list.appendChild(el); + }); +}; +""".strip() + + +_AIRPORT_JS = """ +window.__nitroWidgetRender = function(data) { + const list = document.getElementById("list"); + const meta = document.getElementById("meta"); + if (!list) return; + const results = (data && (data.results || data.airports || data.places)) || []; + if (meta) meta.textContent = "Query: " + ((data && data.query) || "") + " · " + results.length + " result(s)"; + list.innerHTML = ""; + if (!results.length) { + list.innerHTML = '
No airports found.
'; + return; + } + results.forEach(function(item) { + const el = document.createElement("div"); + el.className = "row"; + el.innerHTML = '
'; + el.querySelector(".code").textContent = item.iata_code || item.iataCode || ""; + el.querySelector(".name").textContent = item.name || ""; + el.querySelector(".muted").textContent = (item.city_name || item.cityName || item.city || "") + " · " + (item.type || "airport"); + list.appendChild(el); + }); +}; +""".strip() + + +def _place_code_js() -> str: + return """ + function code(p) { + if (!p) return ""; + if (typeof p === "string") return p; + return p.iata_code || p.iataCode || p.code || ""; + } + function money(amount, currency) { + if (amount == null || amount === "") return ""; + return String(amount) + (currency ? " " + currency : ""); + } + function sliceHtml(sl) { + const origin = code(sl.origin); + const dest = code(sl.destination); + const wrap = document.createElement("div"); + wrap.className = "slice"; + const title = document.createElement("strong"); + title.textContent = origin + " → " + dest; + const times = document.createElement("div"); + times.className = "muted"; + times.textContent = (sl.departing_at || sl.departingAt || sl.departureTime || "") + + " – " + (sl.arriving_at || sl.arrivingAt || sl.arrivalTime || "") + + " · " + (sl.duration || ""); + wrap.appendChild(title); + wrap.appendChild(times); + return wrap; + } +""".strip() + + +_FLIGHT_DETAILS_JS = f""" +window.__nitroWidgetRender = function(data) {{ + const meta = document.getElementById("meta"); + const root = document.getElementById("root"); + if (!root) return; + if (!data) {{ + if (meta) meta.textContent = "Waiting for get_flight_details result."; + return; + }} +{_place_code_js()} + const amount = data.total_amount || data.totalAmount || ""; + const currency = data.total_currency || data.totalCurrency || ""; + if (meta) meta.textContent = "Offer " + (data.id || "") + " · " + money(amount, currency); + root.innerHTML = ""; + (data.slices || []).forEach(function(sl) {{ root.appendChild(sliceHtml(sl)); }}); + if (data.id) {{ + const actions = document.createElement("div"); + actions.className = "ns-actions"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "ns-btn ns-btn-primary"; + btn.setAttribute("data-call-tool", "get_seat_map"); + btn.setAttribute("data-args", JSON.stringify({{ offerId: data.id }})); + btn.textContent = "Seat map"; + actions.appendChild(btn); + root.appendChild(actions); + }} +}}; +""".strip() + + +_ORDER_SUMMARY_JS = f""" +window.__nitroWidgetRender = function(data) {{ + const root = document.getElementById("root"); + const card = document.querySelector(".card"); + if (!data) return; +{_place_code_js()} + const status = data.status || "held"; + const ref = data.booking_reference || data.bookingReference || ""; + const orderId = data.id || data.orderId || ""; + const amount = data.total_amount || data.totalAmount || ""; + const currency = data.total_currency || data.totalCurrency || ""; + const host = card || root; + if (!host) return; + host.innerHTML = ""; + const h1 = document.createElement("h1"); + h1.textContent = "Order " + status; + const meta = document.createElement("div"); + meta.className = "meta"; + meta.textContent = "Ref " + ref + " · " + orderId; + const price = document.createElement("div"); + price.className = "price"; + price.textContent = money(amount, currency); + host.appendChild(h1); + host.appendChild(meta); + host.appendChild(price); + const paxTitle = document.createElement("h2"); + paxTitle.textContent = "Passengers"; + host.appendChild(paxTitle); + const passengers = data.passengers || []; + if (!passengers.length) {{ + const empty = document.createElement("div"); + empty.className = "muted"; + empty.textContent = "None listed"; + host.appendChild(empty); + }} + passengers.forEach(function(p) {{ + const line = document.createElement("div"); + line.className = "muted"; + line.textContent = p.name || [p.given_name || p.givenName, p.family_name || p.familyName].filter(Boolean).join(" ") || p.id || ""; + host.appendChild(line); + }}); + const itin = document.createElement("h2"); + itin.textContent = "Itinerary"; + host.appendChild(itin); + (data.slices || []).forEach(function(sl) {{ host.appendChild(sliceHtml(sl)); }}); + if (orderId && String(status).toLowerCase().indexOf("cancel") < 0) {{ + const actions = document.createElement("div"); + actions.className = "ns-actions"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "ns-btn"; + btn.setAttribute("data-call-tool", "cancel_order"); + btn.setAttribute("data-args", JSON.stringify({{ orderId: orderId }})); + btn.textContent = "Cancel order"; + actions.appendChild(btn); + host.appendChild(actions); + }} +}}; +""".strip() + + +_SEAT_JS = """ +window.__nitroWidgetRender = function(data) { + const meta = document.getElementById("meta"); + const root = document.getElementById("root"); + if (!root) return; + if (!data) { + if (meta) meta.textContent = "Waiting for get_seat_map result."; + return; + } + if (meta) meta.textContent = "Offer " + (data.offerId || data.offer_id || ""); + root.innerHTML = ""; + const cabins = data.cabins || []; + if (!cabins.length) { + root.innerHTML = '
No seat map data.
'; + return; + } + cabins.forEach(function(cabin) { + const h2 = document.createElement("h2"); + h2.textContent = cabin.cabin_class || cabin.cabinClass || "cabin"; + root.appendChild(h2); + (cabin.rows || []).forEach(function(row) { + const line = document.createElement("div"); + line.className = "seat-row"; + const rn = document.createElement("span"); + rn.className = "rn"; + rn.textContent = row.row_number || row.rowNumber || ""; + line.appendChild(rn); + let seats = row.seats || row.elements || []; + if (!seats.length) { + (row.sections || []).forEach(function(section) { + seats = seats.concat(section.elements || []); + }); + } + seats.forEach(function(seat) { + if (seat.type && seat.type !== "seat") return; + const cell = document.createElement("span"); + const available = seat.available != null ? seat.available : (seat.available_services != null); + cell.className = available ? "seat ok" : "seat no"; + cell.textContent = seat.designator || seat.id || seat.column || ""; + line.appendChild(cell); + }); + root.appendChild(line); + }); + }); +}; +""".strip() + + +_CANCEL_JS = """ +window.__nitroWidgetRender = function(data) { + const card = document.querySelector(".card"); + if (!card || !data) return; + const status = data.status || "cancelled"; + const cid = data.id || data.cancellationId || ""; + const refund = data.refund_amount || data.refundAmount || ""; + const currency = data.refund_currency || data.refundCurrency || ""; + card.innerHTML = ""; + const h1 = document.createElement("h1"); + h1.textContent = "Booking cancelled"; + const meta = document.createElement("div"); + meta.className = "meta"; + meta.textContent = status + " · " + cid; + const p = document.createElement("p"); + p.textContent = data.message || "Booking cancelled."; + const price = document.createElement("div"); + price.className = "price"; + price.textContent = "Refund " + (refund ? (refund + (currency ? " " + currency : "")) : "n/a"); + card.appendChild(h1); + card.appendChild(meta); + card.appendChild(p); + card.appendChild(price); +}; +""".strip() + + +def build_flight_search_results_widget(data: Any | None = None) -> str: + return _page( + "Flight search", + _FLIGHT_CSS, + render_body("flight-search-results", data), + _FLIGHT_SEARCH_JS, + data, + ) + + +def build_flight_details_widget(data: Any | None = None) -> str: + return _page( + "Flight details", + _FLIGHT_CSS, + render_body("flight-details", data), + _FLIGHT_DETAILS_JS, + data, + ) + + +def build_airport_search_widget(data: Any | None = None) -> str: + return _page( + "Airport search", + _FLIGHT_CSS, + render_body("airport-search", data), + _AIRPORT_JS, + data, + ) + + +def build_order_summary_widget(data: Any | None = None) -> str: + return _page( + "Order summary", + _FLIGHT_CSS, + render_body("order-summary", data), + _ORDER_SUMMARY_JS, + data, + ) + + +def build_seat_selection_widget(data: Any | None = None) -> str: + return _page( + "Seat map", + _FLIGHT_CSS, + render_body("seat-selection", data), + _SEAT_JS, + data, + ) + + +def build_order_cancellation_widget(data: Any | None = None) -> str: + return _page( + "Cancellation", + _FLIGHT_CSS, + render_body("order-cancellation", data), + _CANCEL_JS, + data, + ) diff --git a/nitrostack/widgets/route_templates_generic.py b/nitrostack/widgets/route_templates_generic.py new file mode 100644 index 0000000..13deefc --- /dev/null +++ b/nitrostack/widgets/route_templates_generic.py @@ -0,0 +1,206 @@ +"""Page wrapper plus the generic, missing, calculator, card, table and chart widget templates.""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.host_bridge import wrap_widget_page +from nitrostack.widgets.views import missing_body, render_body + + +def _generic_render_js() -> str: + return """ +window.__nitroWidgetRender = function(data) { + const root = document.getElementById("root"); + const meta = document.getElementById("meta"); + if (!root) return; + if (!data) { + if (meta) meta.textContent = "Waiting for tool result (host injects tool output)."; + return; + } + if (meta) meta.textContent = "Tool output"; + root.innerHTML = ""; + const pre = document.createElement("pre"); + pre.textContent = JSON.stringify(data, null, 2); + root.appendChild(pre); +}; +""".strip() + + +_CALC_CSS = """ + :root { --ns-accent: #15803d; } + .card { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 20px; text-align: center; } + .expr { font-size: 0.95rem; color: var(--ns-muted); margin-bottom: 8px; } + .result { font-size: 2rem; font-weight: 800; color: var(--ns-accent); } +""" + + +_CARD_CSS = """ + .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 20px; box-shadow: var(--ns-shadow); max-width: 320px; border: 1px solid var(--ns-border); } + .card h2 { margin: 0 0 8px; font-size: 1.25rem; } + .price { font-size: 1.5rem; } + .desc { color: var(--ns-muted); margin-top: 8px; } +""" + + +_TABLE_CSS = """ + table { border-collapse: collapse; width: 100%; max-width: 480px; background: var(--ns-surface); border-radius: 10px; overflow: hidden; } + th, td { border: 1px solid var(--ns-border); padding: 8px 12px; text-align: left; } + th { background: var(--ns-accent-soft); } +""" + + +_CHART_CSS = """ + .chart { display: flex; align-items: flex-end; gap: 8px; height: 160px; } + .bar-wrap { flex: 1; display: flex; flex-direction: column; align-items: center; } + .bar { width: 100%; background: var(--ns-accent, #3b82f6); border-radius: 4px 4px 0 0; min-height: 4px; } + .label { font-size: 12px; margin-top: 4px; color: var(--ns-muted); } +""" + + +_GENERIC_CSS = """ + pre { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: 8px; padding: 12px; overflow: auto; } +""" + + +_MISSING_CSS = """ + :root { --ns-bg: #fef2f2; --ns-text: #7f1d1d; } + .meta { font-size: 0.9rem; line-height: 1.5; } +""" + + +_CALC_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data) return; + const expr = document.getElementById("expr"); + const result = document.getElementById("result"); + if (data.expression) expr.textContent = data.expression; + if (data.result != null) result.textContent = String(data.result); + else if (data.value != null) result.textContent = String(data.value); +}; +""".strip() + + +_CARD_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data) return; + const name = document.getElementById("name"); + const price = document.getElementById("price"); + const desc = document.getElementById("desc"); + if (name) name.textContent = data.name || "—"; + if (price) price.textContent = data.price != null ? "$" + Number(data.price).toFixed(2) : "—"; + if (desc) desc.textContent = data.description || ""; +}; +""".strip() + + +_TABLE_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data || !Array.isArray(data.rows)) return; + const cols = data.columns || Object.keys(data.rows[0] || {}); + const header = document.getElementById("header"); + const body = document.getElementById("body"); + if (!header || !body) return; + header.innerHTML = ""; + body.innerHTML = ""; + cols.forEach(function(c) { + const th = document.createElement("th"); + th.textContent = c; + header.appendChild(th); + }); + data.rows.forEach(function(row) { + const tr = document.createElement("tr"); + cols.forEach(function(c) { + const td = document.createElement("td"); + td.textContent = row[c] ?? ""; + tr.appendChild(td); + }); + body.appendChild(tr); + }); +}; +""".strip() + + +_CHART_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data) return; + const title = document.getElementById("title"); + const chart = document.getElementById("chart"); + if (title) title.textContent = data.title || "Chart"; + if (!chart) return; + chart.innerHTML = ""; + const items = data.items || []; + const max = Math.max.apply(null, items.map(function(i) { return i.value || 0; }).concat([1])); + items.forEach(function(item) { + const wrap = document.createElement("div"); + wrap.className = "bar-wrap"; + const bar = document.createElement("div"); + bar.className = "bar"; + bar.style.height = (((item.value || 0) / max) * 140) + "px"; + const label = document.createElement("div"); + label.className = "label"; + label.textContent = item.label || ""; + wrap.appendChild(bar); + wrap.appendChild(label); + chart.appendChild(wrap); + }); +}; +""".strip() + + +def _page( + title: str, + styles: str, + body: str, + render_js: str, + data: Any | None, + extra_head: str = "", + flush: bool = False, + chrome: bool = True, +) -> str: + return wrap_widget_page( + title=title, + styles=styles, + body=body, + render_js=render_js, + data=data, + extra_head=extra_head, + flush=flush, + chrome=chrome, + ) + + +def build_generic_widget(route: str, data: Any | None = None) -> str: + return _page(route, _GENERIC_CSS, render_body(route, data), _generic_render_js(), data) + + +def build_missing_widget(route: str, data: Any | None = None) -> str: + return _page( + f"Missing widget: {route}", + _MISSING_CSS, + missing_body(route), + _generic_render_js(), + data, + ) + + +def build_calculator_result_widget(data: Any | None = None) -> str: + return _page( + "Calculator result", + _CALC_CSS, + render_body("calculator-result", data), + _CALC_JS, + data, + ) + + +def build_card_widget(data: Any | None = None) -> str: + return _page("Product Card", _CARD_CSS, render_body("card", data), _CARD_JS, data) + + +def build_table_widget(data: Any | None = None) -> str: + return _page("Data Table", _TABLE_CSS, render_body("table", data), _TABLE_JS, data) + + +def build_chart_widget(data: Any | None = None) -> str: + return _page("Bar Chart", _CHART_CSS, render_body("chart", data), _CHART_JS, data) diff --git a/nitrostack/widgets/route_templates_pizza.py b/nitrostack/widgets/route_templates_pizza.py new file mode 100644 index 0000000..fa440fb --- /dev/null +++ b/nitrostack/widgets/route_templates_pizza.py @@ -0,0 +1,303 @@ +"""Pizza list, map and shop widget templates (CSS and render JS).""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.route_templates_generic import _page +from nitrostack.widgets.views import render_body + + +_PIZZA_LIST_CSS = """ + :root { --ns-accent: #ea580c; --ns-accent-soft: #ffedd5; } + .shop { min-width: 260px; max-width: 260px; scroll-snap-align: start; flex-shrink: 0; } + .img { width: 100%; height: 120px; object-fit: cover; border-radius: 10px; margin-bottom: 8px; background: var(--ns-accent-soft); } + .row { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; } + .name { font-weight: 700; } + .addr { color: var(--ns-muted); font-size: 0.85rem; margin-top: 4px; } +""" + + +_PIZZA_MAP_CSS = """ + :root { --ns-accent: #ea580c; } + html, body { width: 100%; height: 560px; } + body { position: relative; min-height: 560px; background: #e5e7eb; } + .meta { position: absolute; top: 12px; left: 12px; z-index: 3; margin: 0; + background: color-mix(in srgb, var(--ns-surface) 92%, transparent); border-radius: 8px; padding: 6px 10px; + box-shadow: var(--ns-shadow); } + .map { position: absolute; inset: 0; width: 100%; height: 560px; min-height: 560px; } + .map-live { position: absolute; inset: 0; } + .static-map { position: absolute; inset: 0; z-index: 1; width: 100%; height: 560px; + object-fit: cover; transition: opacity .4s ease; } + .static-map.is-ready { opacity: 0; pointer-events: none; } + .mapboxgl-map { width: 100%; height: 100%; } + .cards { position: absolute; left: 16px; right: 16px; bottom: 8px; z-index: 3; } + .map-card { min-width: 220px; max-width: 220px; flex-shrink: 0; scroll-snap-align: start; } + .map-card .name { font-weight: 700; } + .map-card .muted { margin-top: 4px; } + .map-card .rating { margin-top: 4px; } +""" + + +_PIZZA_SHOP_CSS = """ + :root { --ns-accent: #e11d48; --ns-accent-soft: #ffe4e6; } + .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 16px; border: 1px solid var(--ns-border); } + .hero { width: 100%; max-height: 180px; object-fit: cover; border-radius: 10px; margin-bottom: 12px; } + .chips { margin-top: 10px; } + .chip { margin: 0 4px 4px 0; } +""" + + +_PIZZA_LIST_JS = """ +window.__nitroWidgetRender = function(data) { + const list = document.getElementById("list"); + const meta = document.getElementById("meta"); + if (!list || !meta) return; + list.innerHTML = ""; + if (!data || !Array.isArray(data.shops)) { + meta.textContent = "Waiting for show_pizza_list result."; + return; + } + const state = (window.openai && window.openai.widgetState) || {}; + const sort = state.sort || "rating"; + const shops = data.shops.slice().sort(function(a, b) { + if (sort === "name") return String(a.name || "").localeCompare(String(b.name || "")); + return (b.rating || 0) - (a.rating || 0); + }); + document.querySelectorAll("#sorts [data-sort]").forEach(function(btn) { + btn.classList.toggle("is-on", btn.getAttribute("data-sort") === sort); + }); + const total = data.totalShops ?? data.shops.length; + meta.textContent = total + " shop" + (total === 1 ? "" : "s"); + if (!shops.length) { + list.innerHTML = '
No shops match these filters.
'; + return; + } + shops.forEach(function(shop) { + const el = document.createElement("article"); + el.className = "shop ns-card"; + el.setAttribute("data-call-tool", "show_pizza_shop"); + el.setAttribute("data-args", JSON.stringify({ shopId: shop.id || "" })); + el.setAttribute("role", "button"); + el.tabIndex = 0; + const open = shop.openNow + ? 'Open' + : 'Closed'; + const price = "$".repeat(shop.priceLevel || 1); + let img = ""; + if (shop.image) { + img = ''; + } + el.innerHTML = + img + + '
' + + '
' + open + '
'; + el.querySelector(".name").textContent = shop.name || shop.id || "Shop"; + el.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : ""; + el.querySelector(".addr").textContent = shop.address || ""; + el.querySelector(".price").textContent = price; + list.appendChild(el); + }); +}; +document.addEventListener("click", function(ev) { + const btn = ev.target.closest("#sorts [data-sort]"); + if (!btn || !window.nitrostack) return; + const next = Object.assign({}, (window.openai && window.openai.widgetState) || {}, { + sort: btn.getAttribute("data-sort") + }); + window.nitrostack.setWidgetState(next); + if (typeof window.__nitroWidgetRender === "function" && window.nitrostack.readHostData) { + window.__nitroWidgetRender(window.nitrostack.readHostData()); + } +}); +""".strip() + + +_MAPBOX_HEAD = """ + + +""".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.
'; + }} + return; + }} + if (typeof mapboxgl === "undefined") {{ + if ((attempt || 0) < 80) {{ + setTimeout(function() {{ mountMap((attempt || 0) + 1); }}, 50); + }} + return; + }} + window.__nitroMapSig = sig; + if (window.__nitroMap) {{ + window.__nitroMap.remove(); + window.__nitroMap = null; + }} + mapboxgl.accessToken = window.__NITRO_MAPBOX_TOKEN; + const first = (shops[0] && shops[0].coords) || [-122.4194, 37.7749]; + const map = new mapboxgl.Map({{ + container: mapEl, + style: "mapbox://styles/mapbox/streets-v12", + center: first, + zoom: 12, + cooperativeGestures: false, + fadeDuration: 0 + }}); + map.addControl(new mapboxgl.NavigationControl({{ showCompass: false }}), "top-right"); + map.addControl(new mapboxgl.FullscreenControl(), "top-right"); + shops.forEach(function(shop) {{ + const el = document.createElement("div"); + el.style.backgroundImage = "url(https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png)"; + el.style.width = "30px"; + el.style.height = "40px"; + el.style.backgroundSize = "100%"; + el.style.cursor = "pointer"; + el.title = shop.name || shop.id || ""; + el.addEventListener("click", function() {{ + if (window.nitrostack) window.nitrostack.callTool("show_pizza_shop", {{ shopId: shop.id || "" }}); + }}); + new mapboxgl.Marker(el).setLngLat(shop.coords).addTo(map); + }}); + if (shops.length > 1) {{ + const bounds = new mapboxgl.LngLatBounds(); + shops.forEach(function(s) {{ bounds.extend(s.coords); }}); + map.fitBounds(bounds, {{ padding: 60, maxZoom: 14, duration: 0 }}); + }} + map.once("idle", function() {{ + try {{ map.resize(); }} catch (e) {{}} + revealLive(); + }}); + window.__nitroMap = map; + }} + mountMap(0); +}}; +""".strip() + + +_PIZZA_SHOP_JS = """ +window.__nitroWidgetRender = function(data) { + const shop = data && (data.shop || data); + const hero = document.getElementById("hero"); + if (!shop || !shop.name) { + const desc = document.getElementById("desc"); + if (desc) desc.textContent = "Waiting for show_pizza_shop result."; + return; + } + if (shop.image && hero) { + hero.src = shop.image; + hero.style.display = "block"; + } else if (hero) { + hero.style.display = "none"; + } + document.getElementById("name").textContent = shop.name; + document.getElementById("rating").textContent = + shop.rating != null ? "★ " + shop.rating + " (" + (shop.reviews || 0) + " reviews)" : ""; + document.getElementById("desc").textContent = shop.description || ""; + document.getElementById("addr").textContent = shop.address || ""; + const hours = shop.hours ? (shop.hours.open + " – " + shop.hours.close) : ""; + document.getElementById("hours").textContent = hours ? "Hours: " + hours : ""; + document.getElementById("phone").textContent = shop.phone || ""; + const chips = document.getElementById("chips"); + chips.innerHTML = ""; + (shop.specialties || []).forEach(function(item) { + const chip = document.createElement("span"); + chip.className = "chip"; + chip.textContent = item; + chips.appendChild(chip); + }); + const actions = document.getElementById("actions"); + if (actions) { + actions.innerHTML = ""; + function addLink(label, url, primary) { + if (!url) return; + const a = document.createElement("a"); + a.className = primary ? "ns-btn ns-btn-primary" : "ns-btn"; + a.setAttribute("data-open-link", url); + a.href = url; + a.textContent = label; + actions.appendChild(a); + } + let maps = ""; + if (Array.isArray(shop.coords) && shop.coords.length === 2) { + maps = "https://www.google.com/maps/search/?api=1&query=" + shop.coords[1] + "," + shop.coords[0]; + } else if (shop.address) { + maps = "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(shop.address); + } + addLink("Maps", maps, false); + if (shop.phone) { + const tel = String(shop.phone).replace(/[^0-9+]/g, ""); + if (tel) addLink("Call", "tel:" + tel, false); + } + addLink("Website", shop.website || "", true); + } +}; +""".strip() + + +def build_pizza_list_widget(data: Any | None = None) -> str: + return _page("Pizza shops", _PIZZA_LIST_CSS, render_body("pizza-list", data), _PIZZA_LIST_JS, data) + + +def build_pizza_map_widget(data: Any | None = None) -> str: + return _page( + "Pizza map", + _PIZZA_MAP_CSS, + render_body("pizza-map", data), + _pizza_map_js(), + data, + extra_head=_MAPBOX_HEAD, + flush=True, + ) + + +def build_pizza_shop_widget(data: Any | None = None) -> str: + return _page("Pizza shop", _PIZZA_SHOP_CSS, render_body("pizza-shop", data), _PIZZA_SHOP_JS, data) diff --git a/nitrostack/widgets/views.py b/nitrostack/widgets/views.py index 9822cbf..9e84807 100644 --- a/nitrostack/widgets/views.py +++ b/nitrostack/widgets/views.py @@ -3,13 +3,17 @@ Hosts that inject data later still use the HTML document's small host-bridge script. First paint (Inspector ``tools/call`` HTML, live preview) uses these builders so the iframe matches the actual tool output — not sample JSON. + +This module is the route -> body dispatcher. The bodies live in views_common, +views_pizza and views_flight and are re-exported here, so existing imports keep working. """ from __future__ import annotations from typing import Any, Callable, Dict -from nitrostack.widgets.html_util import ( +# Re-exported only so existing ``from nitrostack.widgets.views import ...`` lines keep working. +from nitrostack.widgets.html_util import ( # noqa: F401 as_dict, as_list, esc, @@ -20,529 +24,34 @@ place_code, place_name, ) -from nitrostack.widgets.ui import action_row, call_attrs, maps_url - - -def _safe_int( - value: Any, - default: int = 0, - *, - minimum: int | None = None, - maximum: int | None = None, -) -> int: - try: - # OverflowError covers infinities: `json.loads("1e400")` yields `inf`, and - # `int(float("inf"))` raises. NaN already surfaces as ValueError. - n = int(float(value)) - except (TypeError, ValueError, OverflowError): - n = default - if minimum is not None: - n = max(minimum, n) - if maximum is not None: - n = min(maximum, n) - return n - - -def _safe_float(value: Any, default: float = 0.0) -> float: - try: - n = float(value) - except (TypeError, ValueError): - return default - if n != n or n in (float("inf"), float("-inf")): - return default - return n - - -def pizza_list_body(data: Any | None) -> str: - payload = as_dict(data) - shops = as_list(payload.get("shops")) - total = payload.get("totalShops") - if total is None: - total = len(shops) - if data is None: - meta = "Waiting for show_pizza_list result." - cards = "" - elif not shops: - meta = f"{total} shops" - cards = '
No shops match these filters.
' - else: - meta = f"{total} shop" + ("" if total == 1 else "s") - parts = [] - for shop in shops: - shop = as_dict(shop) - open_cls = "open" if shop.get("openNow") else "closed" - open_label = "Open" if shop.get("openNow") else "Closed" - price = "$" * _safe_int(shop.get("priceLevel"), 1, minimum=1, maximum=4) - img = "" - if shop.get("image"): - img = f'' - rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else "" - shop_id = shop.get("id") or "" - parts.append( - f'
' - f"{img}" - f'
{esc(shop.get("name") or shop_id or "Shop")}' - f'{rating}
' - f'
{esc(shop.get("address"))}
' - f'
{open_label} ' - f'{esc(price)}
' - "
" - ) - cards = "".join(parts) - return ( - "

Pizza shops

" - f'
{esc(meta)}
' - '
' - '' - '' - "
" - f'
{cards}
' - '
' - ) - - -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'Pizza shop map' - 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'
{esc(money(amount, currency))}' - f'{esc(offer_id)}
{slice_html}
' - ) - if not cards: - cards.append('
No flight offers.
') - return ( - "

Flight search

" - f'
{esc(meta)}
' - f'
{"".join(cards)}
' - ) - - -def flight_details_body(data: Any | None) -> str: - payload = as_dict(data) - if data is None or not payload: - return ( - "

Flight details

" - '
Waiting for get_flight_details result.
' - '
' - ) - amount = pick(payload, "total_amount", "totalAmount", default="") - currency = pick(payload, "total_currency", "totalCurrency", default="") - slices = as_list(payload.get("slices")) - slice_html = "".join(_offer_slice_html(as_dict(s)) for s in slices) - offer_id = payload.get("id") or "" - seats = "" - if offer_id: - seats = ( - f'
' - ) - return ( - "

Flight details

" - f'
Offer {esc(offer_id)} · {esc(money(amount, currency))}
' - f'
{slice_html}{seats}
' - ) - - -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 ( - "

Cancellation

" - '
Waiting for cancel_order result.
' - '
' - ) - refund = pick(payload, "refund_amount", "refundAmount", default="") - currency = pick(payload, "refund_currency", "refundCurrency", default="") - status = pick(payload, "status", default="cancelled") - msg = pick(payload, "message", default="Booking cancelled.") - cid = pick(payload, "id", "cancellationId", default="") - return ( - '
' - "

Booking cancelled

" - f'
{esc(status)} · {esc(cid)}
' - f'

{esc(msg)}

' - f'
Refund {esc(money(refund, currency) or "n/a")}
' - "
" - '
' - ) - - -def generic_body(route: str, data: Any | None) -> str: - import json - - if data is None: - preview = "Waiting for host to send tool output…" - else: - preview = json.dumps(data, indent=2, default=str) - return ( - f"

{esc(route)}

" - '
Tool output
' - f'
{esc(preview)}
' - ) - - -def missing_body(route: str) -> str: - return ( - "

Widget template missing

" - f'
No HTML found for route {esc(route)}. ' - f"Create widgets/out/{esc(route)}.html or run nitrostack-py init again.
" - '
' - ) +from nitrostack.widgets.ui import action_row, call_attrs, maps_url # noqa: F401 +from nitrostack.widgets.views_common import ( # noqa: F401 + _safe_int, + _safe_float, + calculator_result_body, + card_body, + table_body, + chart_body, + generic_body, + missing_body, +) +from nitrostack.widgets.views_pizza import ( # noqa: F401 + pizza_list_body, + _pizza_map_card, + pizza_map_body, + pizza_shop_body, +) +from nitrostack.widgets.views_flight import ( # noqa: F401 + _offer_slice_html, + _offer_itinerary_html, + flight_search_results_body, + flight_details_body, + airport_search_body, + order_summary_body, + _seat_cells, + seat_selection_body, + order_cancellation_body, +) BODY_BUILDERS: Dict[str, Callable[[Any | None], str]] = { diff --git a/nitrostack/widgets/views_common.py b/nitrostack/widgets/views_common.py new file mode 100644 index 0000000..f5fb8c5 --- /dev/null +++ b/nitrostack/widgets/views_common.py @@ -0,0 +1,131 @@ +"""Shared view helpers and the generic, calculator, card, table and chart widget bodies.""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.html_util import as_dict, as_list, esc + + +def _safe_int( + value: Any, + default: int = 0, + *, + minimum: int | None = None, + maximum: int | None = None, +) -> int: + try: + # OverflowError covers infinities: `json.loads("1e400")` yields `inf`, and + # `int(float("inf"))` raises. NaN already surfaces as ValueError. + n = int(float(value)) + except (TypeError, ValueError, OverflowError): + n = default + if minimum is not None: + n = max(minimum, n) + if maximum is not None: + n = min(maximum, n) + return n + + +def _safe_float(value: Any, default: float = 0.0) -> float: + try: + n = float(value) + except (TypeError, ValueError): + return default + if n != n or n in (float("inf"), float("-inf")): + return default + return n + + +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 generic_body(route: str, data: Any | None) -> str: + import json + + if data is None: + preview = "Waiting for host to send tool output…" + else: + preview = json.dumps(data, indent=2, default=str) + return ( + f"

{esc(route)}

" + '
Tool output
' + f'
{esc(preview)}
' + ) + + +def missing_body(route: str) -> str: + return ( + "

Widget template missing

" + f'
No HTML found for route {esc(route)}. ' + f"Create widgets/out/{esc(route)}.html or run nitrostack-py init again.
" + '
' + ) diff --git a/nitrostack/widgets/views_flight.py b/nitrostack/widgets/views_flight.py new file mode 100644 index 0000000..6b72c62 --- /dev/null +++ b/nitrostack/widgets/views_flight.py @@ -0,0 +1,273 @@ +"""Flight search, details, airport, order, seat and cancellation widget bodies.""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.html_util import ( + as_dict, + as_list, + esc, + format_duration, + money, + pick, + place_code, +) +from nitrostack.widgets.ui import call_attrs + + +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'
{esc(money(amount, currency))}' + f'{esc(offer_id)}
{slice_html}
' + ) + if not cards: + cards.append('
No flight offers.
') + return ( + "

Flight search

" + f'
{esc(meta)}
' + f'
{"".join(cards)}
' + ) + + +def flight_details_body(data: Any | None) -> str: + payload = as_dict(data) + if data is None or not payload: + return ( + "

Flight details

" + '
Waiting for get_flight_details result.
' + '
' + ) + amount = pick(payload, "total_amount", "totalAmount", default="") + currency = pick(payload, "total_currency", "totalCurrency", default="") + slices = as_list(payload.get("slices")) + slice_html = "".join(_offer_slice_html(as_dict(s)) for s in slices) + offer_id = payload.get("id") or "" + seats = "" + if offer_id: + seats = ( + f'
' + ) + return ( + "

Flight details

" + f'
Offer {esc(offer_id)} · {esc(money(amount, currency))}
' + f'
{slice_html}{seats}
' + ) + + +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 ( + "

Cancellation

" + '
Waiting for cancel_order result.
' + '
' + ) + refund = pick(payload, "refund_amount", "refundAmount", default="") + currency = pick(payload, "refund_currency", "refundCurrency", default="") + status = pick(payload, "status", default="cancelled") + msg = pick(payload, "message", default="Booking cancelled.") + cid = pick(payload, "id", "cancellationId", default="") + return ( + '
' + "

Booking cancelled

" + f'
{esc(status)} · {esc(cid)}
' + f'

{esc(msg)}

' + f'
Refund {esc(money(refund, currency) or "n/a")}
' + "
" + '
' + ) diff --git a/nitrostack/widgets/views_pizza.py b/nitrostack/widgets/views_pizza.py new file mode 100644 index 0000000..cc8691d --- /dev/null +++ b/nitrostack/widgets/views_pizza.py @@ -0,0 +1,155 @@ +"""Pizza list, map and shop widget bodies.""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.html_util import ( + as_dict, + as_list, + esc, + mapbox_static_url, +) +from nitrostack.widgets.ui import action_row, call_attrs, maps_url +from nitrostack.widgets.views_common import _safe_int + + +def pizza_list_body(data: Any | None) -> str: + payload = as_dict(data) + shops = as_list(payload.get("shops")) + total = payload.get("totalShops") + if total is None: + total = len(shops) + if data is None: + meta = "Waiting for show_pizza_list result." + cards = "" + elif not shops: + meta = f"{total} shops" + cards = '
No shops match these filters.
' + else: + meta = f"{total} shop" + ("" if total == 1 else "s") + parts = [] + for shop in shops: + shop = as_dict(shop) + open_cls = "open" if shop.get("openNow") else "closed" + open_label = "Open" if shop.get("openNow") else "Closed" + price = "$" * _safe_int(shop.get("priceLevel"), 1, minimum=1, maximum=4) + img = "" + if shop.get("image"): + img = f'' + rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else "" + shop_id = shop.get("id") or "" + parts.append( + f'
' + f"{img}" + f'
{esc(shop.get("name") or shop_id or "Shop")}' + f'{rating}
' + f'
{esc(shop.get("address"))}
' + f'
{open_label} ' + f'{esc(price)}
' + "
" + ) + cards = "".join(parts) + return ( + "

Pizza shops

" + f'
{esc(meta)}
' + '
' + '' + '' + "
" + f'
{cards}
' + '
' + ) + + +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'Pizza shop map' + 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="

Example

")) + async def example(self, input: Empty, context: ExecutionContext): + raise AssertionError("Listing widgets must not execute tools") + + @module(name="stdio-registry", providers=[Tools]) + class AppModule: + pass + + with safe_stdio_transport(): + app = McpApplication(AppModule) + await run_stdio(app.mcp_server, "auto") + + +if __name__ == "__main__": + if sys.argv[1] == "stdio": + asyncio.run(stdio_server()) + else: + print(json.dumps(template_manifest(sys.argv[1]))) diff --git a/tests/test_app_mode.py b/tests/test_app_mode.py index e11c0e1..d1615ac 100644 --- a/tests/test_app_mode.py +++ b/tests/test_app_mode.py @@ -1,9 +1,12 @@ -"""Phase 4 — NITROSTACK_APP_MODE parsing (Python-only).""" +"""NITROSTACK_APP_MODE / APP_MODE parsing (mirrors TS core app-mode tests).""" + from __future__ import annotations import os import sys +import pytest + sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from nitrostack.core.app_mode import ( @@ -16,19 +19,63 @@ ) -def test_default_mode_is_universal(monkeypatch): +@pytest.fixture(autouse=True) +def _clean_app_mode_env(monkeypatch): monkeypatch.delenv("NITROSTACK_APP_MODE", raising=False) + monkeypatch.delenv("APP_MODE", raising=False) + yield + + +def test_default_mode_is_openai(): + assert get_app_mode() == "openai" + assert is_mcp_app_mode() is False + assert is_openai_mode() is True + assert get_widget_mime_type() == RESOURCE_MIME_TYPE_OPENAI + + +def test_defaults_openai_for_blank_or_unknown(monkeypatch): + monkeypatch.setenv("NITROSTACK_APP_MODE", " ") + assert get_app_mode() == "openai" + monkeypatch.setenv("NITROSTACK_APP_MODE", "unknown-flavor") + assert get_app_mode() == "openai" + + +def test_openai_aliases(monkeypatch): + monkeypatch.setenv("NITROSTACK_APP_MODE", " OPENAI ") + assert get_app_mode() == "openai" + monkeypatch.setenv("NITROSTACK_APP_MODE", "chatgpt") + assert get_app_mode() == "openai" + monkeypatch.setenv("APP_MODE", "openai") + assert get_app_mode() == "openai" + + +@pytest.mark.parametrize( + "alias", + ["mcp-app", "mcpapp", "mcp_app", "mcp app", "mcp", "mcpapps", "MCP-APP"], +) +def test_mcp_app_aliases(monkeypatch, alias): + monkeypatch.setenv("NITROSTACK_APP_MODE", alias) + assert get_app_mode() == "mcp-app" + assert is_mcp_app_mode() is True + assert is_openai_mode() is False + assert get_widget_mime_type() == RESOURCE_MIME_TYPE_MCP_APP + + +def test_mcp_app_via_app_mode(monkeypatch): + monkeypatch.setenv("APP_MODE", "mcp-app") + assert get_app_mode() == "mcp-app" + + +@pytest.mark.parametrize("alias", ["universal", "UNIVERSAL", "all", "both"]) +def test_universal_aliases(monkeypatch, alias): + monkeypatch.setenv("NITROSTACK_APP_MODE", alias) assert get_app_mode() == "universal" assert is_mcp_app_mode() is True assert is_openai_mode() is True assert get_widget_mime_type() == RESOURCE_MIME_TYPE_MCP_APP -def test_mcp_app_and_openai_aliases(monkeypatch): - monkeypatch.setenv("NITROSTACK_APP_MODE", "mcp-app") - assert get_app_mode() == "mcp-app" - assert is_openai_mode() is False +def test_nitrostack_app_mode_wins_over_app_mode(monkeypatch): monkeypatch.setenv("NITROSTACK_APP_MODE", "openai") - assert get_app_mode() == "openai" - assert is_mcp_app_mode() is False - assert get_widget_mime_type() == RESOURCE_MIME_TYPE_OPENAI + monkeypatch.setenv("APP_MODE", "mcp-app") + assert get_app_mode() == "openai" \ No newline at end of file diff --git a/tests/test_auth_setup.py b/tests/test_auth_setup.py new file mode 100644 index 0000000..88bba1a --- /dev/null +++ b/tests/test_auth_setup.py @@ -0,0 +1,184 @@ +"""Issue #70: quick-setup helpers and environment validation for JWT, API key and OAuth.""" + +from __future__ import annotations + +import pytest + +from nitrostack import ( + ApiKeyModule, + DIContainer, + JWTModule, + OAuthModule, + SecretValue, + generate_test_credentials, + print_auth_setup_instructions, + setup_api_key_auth, + setup_jwt_auth, + setup_oauth_auth, + validate_auth_env, +) +from nitrostack.auth.api_key import ApiKeyService +from nitrostack.auth.jwt import JWTService +from nitrostack.auth.oauth import OAuthService +from nitrostack.core.errors import ConfigurationError + +_AUTH_ENV = ( + "JWT_SECRET", "TOKEN_AUDIENCE", "TOKEN_ISSUER", "RESOURCE_URI", "AUTH_SERVER_URL", + "JWKS_URI", "OAUTH_INTROSPECTION_ENDPOINT", "INTROSPECTION_ENDPOINT", +) + + +@pytest.fixture(autouse=True) +def clean(monkeypatch): + import os + + for name in list(os.environ): + if name in _AUTH_ENV or name == "API_KEY" or name.startswith("API_KEY_"): + monkeypatch.delenv(name) + DIContainer.reset() + yield + DIContainer.reset() + + +def test_jwt_config_configures_module(monkeypatch): + monkeypatch.setenv("JWT_SECRET", "x" * 40) + cfg = setup_jwt_auth() + JWTModule.for_root(**cfg) + service = DIContainer.get_instance().resolve(JWTService) + token = service.create_token({"sub": "u1"}) + assert service.verify_token(token)["sub"] == "u1" + assert service.get_secret() == "x" * 40 + + +def test_jwt_explicit_secret_and_plain_str(monkeypatch): + cfg = setup_jwt_auth(secret="y" * 40, audience="aud") + assert isinstance(cfg["secret"], SecretValue) + JWTModule.for_root(**cfg) + service = DIContainer.get_instance().resolve(JWTService) + assert service.audience == "aud" + assert service.get_secret() == "y" * 40 + + +def test_jwt_missing_secret_raises(): + with pytest.raises(ConfigurationError, match="JWT_SECRET"): + setup_jwt_auth() + + +def test_api_key_config_from_explicit_keys(): + cfg = setup_api_key_auth(keys=["k" * 32, SecretValue("m" * 32)]) + ApiKeyModule.for_root(**cfg) + service = DIContainer.get_instance().resolve(ApiKeyService) + assert set(service.get_keys()) == {"k" * 32, "m" * 32} + + +def test_api_key_config_from_env(monkeypatch): + monkeypatch.setenv("API_KEY_1", "a" * 32) + cfg = setup_api_key_auth(header_name="x-token") + assert cfg["keys"] == [] + ApiKeyModule.for_root(**cfg) + service = DIContainer.get_instance().resolve(ApiKeyService) + assert service.get_keys() == ["a" * 32] + assert service.header_name == "x-token" + + +def test_api_key_missing_raises(): + with pytest.raises(ConfigurationError, match="API_KEY"): + setup_api_key_auth() + + +def test_oauth_config_from_env_configures_module(monkeypatch): + monkeypatch.setenv("RESOURCE_URI", "https://srv/mcp") + monkeypatch.setenv("AUTH_SERVER_URL", "https://auth.example") + monkeypatch.setenv("JWKS_URI", "https://auth.example/jwks") + cfg = setup_oauth_auth(scopes_supported=["read"]) + OAuthModule.for_root(**cfg) + service = DIContainer.get_instance().resolve(OAuthService) + assert service.resource_uri == "https://srv/mcp" + assert service.authorization_servers == ["https://auth.example"] + assert service.scopes_supported == ["read"] + assert service.jwks_uri == "https://auth.example/jwks" + + +def test_oauth_overrides_and_secret_wrapping(): + cfg = setup_oauth_auth( + resource_uri="https://srv/mcp", + authorization_servers=["https://auth.example"], + token_introspection_endpoint="https://auth.example/introspect", + token_introspection_client_secret="z" * 32, + ) + assert isinstance(cfg["token_introspection_client_secret"], SecretValue) + OAuthModule.for_root(**cfg) + service = DIContainer.get_instance().resolve(OAuthService) + assert service.token_introspection_endpoint == "https://auth.example/introspect" + + +def test_oauth_reports_every_missing_variable(): + with pytest.raises(ConfigurationError) as err: + setup_oauth_auth() + text = str(err.value) + assert "RESOURCE_URI" in text and "AUTH_SERVER_URL" in text and "JWKS_URI" in text + + +def test_validate_lists_all_missing_not_just_first(): + valid, missing = validate_auth_env("oauth") + assert valid is False + assert len(missing) == 3 + assert missing[0] == "RESOURCE_URI" and missing[1] == "AUTH_SERVER_URL" + assert "JWKS_URI" in missing[2] and "OAUTH_INTROSPECTION_ENDPOINT" in missing[2] + + +def test_validate_partial_and_complete(monkeypatch): + monkeypatch.setenv("RESOURCE_URI", "https://srv/mcp") + assert validate_auth_env("oauth")[1] == [m for m in validate_auth_env("oauth")[1] if "RESOURCE" not in m] + assert len(validate_auth_env("oauth")[1]) == 2 + monkeypatch.setenv("AUTH_SERVER_URL", "https://a") + monkeypatch.setenv("INTROSPECTION_ENDPOINT", "https://a/i") + assert validate_auth_env("oauth") == (True, []) + + +def test_validate_jwt_and_api_key(monkeypatch): + assert validate_auth_env("jwt") == (False, ["JWT_SECRET"]) + monkeypatch.setenv("JWT_SECRET", " ") + assert validate_auth_env("jwt")[0] is False + monkeypatch.setenv("JWT_SECRET", "s" * 32) + assert validate_auth_env("jwt") == (True, []) + assert validate_auth_env("api_key")[0] is False + monkeypatch.setenv("API_KEY_2", "k" * 32) + assert validate_auth_env("api_key") == (True, []) + + +def test_validate_unknown_kind(): + with pytest.raises(ValueError): + validate_auth_env("saml") + + +def test_test_credentials_random_each_call_and_not_printed(capsys, caplog): + first = generate_test_credentials() + second = generate_test_credentials() + assert first["jwt_secret"].unwrap() != second["jwt_secret"].unwrap() + assert first["api_key"].unwrap() != second["api_key"].unwrap() + raw = first["jwt_secret"].unwrap() + assert raw not in repr(first) and raw not in str(first) + assert capsys.readouterr().out == "" + assert raw not in caplog.text + + +def test_test_credentials_configure_modules(): + creds = generate_test_credentials() + JWTModule.for_root(**setup_jwt_auth(secret=creds["jwt_secret"])) + ApiKeyModule.for_root(**setup_api_key_auth(keys=[creds["api_key"]])) + di = DIContainer.get_instance() + assert di.resolve(JWTService).get_secret() == creds["jwt_secret"].unwrap() + assert di.resolve(ApiKeyService).get_keys() == [creds["api_key"].unwrap()] + + +@pytest.mark.parametrize("kind", ["jwt", "api_key", "oauth"]) +def test_print_instructions(kind, capsys): + print_auth_setup_instructions(kind) + out = capsys.readouterr().out + assert "for_root" in out + + +def test_config_repr_hides_secret(monkeypatch): + monkeypatch.setenv("JWT_SECRET", "topsecret-" + "q" * 30) + assert "topsecret" not in repr(setup_jwt_auth()) diff --git a/tests/test_cache_unhashable.py b/tests/test_cache_unhashable.py new file mode 100644 index 0000000..e10f2f3 --- /dev/null +++ b/tests/test_cache_unhashable.py @@ -0,0 +1,284 @@ +from __future__ import annotations + +import asyncio +import pytest + +from pydantic import BaseModel, Field + +from nitrostack.core.additional_decorators import cache, _make_cache_key_part +from nitrostack.core.context import ExecutionContext + + +def run(coro): + return asyncio.run(coro) + + +class SearchQuery(BaseModel): + q: str + limit: int = 10 + + +class FilterOptions(BaseModel): + tags: list[str] = [] + active: bool = True + + +class TestMakeCacheKeyPart: + def test_pydantic_model_returns_deterministic_tuple(self): + m = SearchQuery(q="hello", limit=5) + part = _make_cache_key_part(m, "arg") + assert isinstance(part, tuple) + assert part[0] == "__pydantic__" + assert "SearchQuery" in part[1] + assert isinstance(part[2], str) + + def test_same_model_state_produces_same_key(self): + a = SearchQuery(q="same", limit=3) + b = SearchQuery(q="same", limit=3) + assert _make_cache_key_part(a, "x") == _make_cache_key_part(b, "x") + + def test_different_model_state_produces_different_key(self): + a = SearchQuery(q="foo") + b = SearchQuery(q="bar") + assert _make_cache_key_part(a, "x") != _make_cache_key_part(b, "x") + + def test_hashable_value_returned_as_is(self): + assert _make_cache_key_part(42, "n") == 42 + assert _make_cache_key_part("text", "s") == "text" + assert _make_cache_key_part(3.14, "f") == 3.14 + assert _make_cache_key_part(None, "n") is None + assert _make_cache_key_part((1, 2), "t") == (1, 2) + + def test_unhashable_list_raises_descriptive_type_error(self): + with pytest.raises(TypeError, match="args\\[0\\]"): + _make_cache_key_part([1, 2, 3], "args[0]") + + def test_unhashable_dict_raises_descriptive_type_error(self): + with pytest.raises(TypeError, match="my_param"): + _make_cache_key_part({"a": 1}, "my_param") + + def test_error_message_contains_type_name(self): + with pytest.raises(TypeError, match="list"): + _make_cache_key_part([1], "x") + + def test_error_message_mentions_key_callable(self): + with pytest.raises(TypeError, match="key="): + _make_cache_key_part({"k": "v"}, "x") + + +class TestCacheWithPydanticModels: + def test_pydantic_positional_arg_caches_correctly(self): + calls = [] + + @cache(ttl=60) + async def search(query: SearchQuery) -> str: + calls.append(query.q) + return f"result:{query.q}" + + q = SearchQuery(q="python") + assert run(search(q)) == "result:python" + assert run(search(q)) == "result:python" + assert calls == ["python"] + + def test_different_pydantic_models_produce_different_cache_entries(self): + calls = [] + + @cache(ttl=60) + async def search(query: SearchQuery) -> str: + calls.append(query.q) + return query.q + + run(search(SearchQuery(q="a"))) + run(search(SearchQuery(q="b"))) + run(search(SearchQuery(q="a"))) + assert calls == ["a", "b"] + + def test_pydantic_keyword_arg_caches_correctly(self): + calls = [] + + @cache(ttl=60) + async def fetch(query: SearchQuery, options: FilterOptions) -> int: + calls.append(1) + return len(query.q) + + q = SearchQuery(q="hello") + f = FilterOptions(tags=["python"]) + assert run(fetch(query=q, options=f)) == 5 + assert run(fetch(query=q, options=f)) == 5 + assert calls == [1] + + def test_pydantic_model_cache_isolation_between_decorated_functions(self): + calls_a, calls_b = [], [] + + @cache(ttl=60) + async def fn_a(q: SearchQuery) -> str: + calls_a.append(q.q) + return "a" + + @cache(ttl=60) + async def fn_b(q: SearchQuery) -> str: + calls_b.append(q.q) + return "b" + + q = SearchQuery(q="x") + run(fn_a(q)) + run(fn_b(q)) + assert calls_a == ["x"] + assert calls_b == ["x"] + + def test_pydantic_positional_and_keyword_mixed(self): + calls = [] + + @cache(ttl=60) + async def op(query: SearchQuery, limit: int = 5) -> str: + calls.append((query.q, limit)) + return f"{query.q}:{limit}" + + q = SearchQuery(q="mix") + run(op(q, limit=3)) + run(op(q, limit=3)) + assert calls == [("mix", 3)] + + run(op(q, limit=10)) + assert len(calls) == 2 + + def test_excluded_field_produces_separate_cache_entries(self): + class UserQuery(BaseModel): + q: str + user_id: str = Field(default="", exclude=True) + + calls = [] + + @cache(ttl=60) + async def fetch(uq: UserQuery) -> str: + calls.append(uq.user_id) + return uq.user_id + + assert run(fetch(UserQuery(q="hello", user_id="alice"))) == "alice" + assert run(fetch(UserQuery(q="hello", user_id="bob"))) == "bob" + assert calls == ["alice", "bob"] + + def test_same_class_name_different_module_no_cache_collision(self): + class Q(BaseModel): + q: str + + OtherQ = type("Q", (BaseModel,), {"__annotations__": {"q": str}, "__module__": "other_module"}) + + calls = [] + + @cache(ttl=60) + async def fetch(v) -> str: + result = type(v).__module__ + calls.append(result) + return result + + r1, r2 = run(fetch(Q(q="x"))), run(fetch(OtherQ(q="x"))) + assert r1 != r2 + assert len(calls) == 2 + + +class TestCacheWithUnhashableArguments: + def test_unhashable_positional_arg_raises_type_error(self): + @cache(ttl=60) + async def fn(data: list) -> int: + return len(data) + + with pytest.raises(TypeError, match="args\\[0\\]"): + run(fn([1, 2, 3])) + + def test_unhashable_keyword_arg_raises_type_error(self): + @cache(ttl=60) + async def fn(mapping: dict) -> int: + return len(mapping) + + with pytest.raises(TypeError, match="mapping"): + run(fn(mapping={"a": 1})) + + def test_error_identifies_unhashable_type(self): + @cache(ttl=60) + async def fn(x: set) -> int: + return len(x) + + with pytest.raises(TypeError, match="set"): + run(fn({1, 2})) + + +class TestCacheCustomKeyCallable: + def test_custom_key_accepts_pydantic_model(self): + calls = [] + + @cache(ttl=60, key=lambda q: q.q) + async def search(query: SearchQuery) -> str: + calls.append(query.q) + return query.q + + run(search(SearchQuery(q="hi"))) + run(search(SearchQuery(q="hi"))) + assert calls == ["hi"] + + def test_custom_key_discriminates_on_custom_field(self): + calls = [] + + @cache(ttl=60, key=lambda q: q.q) + async def search(query: SearchQuery) -> str: + calls.append(query.q) + return query.q + + run(search(SearchQuery(q="same", limit=1))) + run(search(SearchQuery(q="same", limit=99))) + assert calls == ["same"] + + def test_custom_key_accepts_unhashable_list(self): + calls = [] + + @cache(ttl=60, key=lambda data: tuple(sorted(data))) + async def process(data: list) -> int: + calls.append(len(data)) + return len(data) + + run(process([3, 1, 2])) + run(process([3, 1, 2])) + assert calls == [3] + + def test_custom_key_with_kwargs(self): + calls = [] + + @cache(ttl=60, key=lambda *, q, limit: (q, limit)) + async def search(*, q: str, limit: int) -> str: + calls.append((q, limit)) + return f"{q}:{limit}" + + run(search(q="hello", limit=5)) + run(search(q="hello", limit=5)) + assert calls == [("hello", 5)] + + def test_custom_key_function_called_with_filtered_args(self): + seen = [] + + def my_key(*args, **kwargs): + seen.append((args, kwargs)) + return str(args) + str(sorted(kwargs.items())) + + @cache(ttl=60, key=my_key) + async def fn(value: int, ctx: ExecutionContext | None = None) -> int: + return value + + ctx = ExecutionContext.__new__(ExecutionContext) + run(fn(42, ctx=ctx)) + + assert all( + not any(isinstance(a, ExecutionContext) for a in call_args) + for call_args, _ in seen + ) + assert all( + not any(isinstance(v, ExecutionContext) for v in call_kwargs.values()) + for _, call_kwargs in seen + ) + + def test_custom_key_returning_unhashable_raises_descriptive_error(self): + @cache(ttl=60, key=lambda x: [x]) + async def fn(x: int) -> int: + return x + + with pytest.raises(TypeError, match="key= callable"): + run(fn(1)) diff --git a/tests/test_cli.py b/tests/test_cli.py index 40b218e..6536dc6 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -18,6 +18,14 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +class _TtyInput(io.StringIO): + """Scripted answers for prompts, which only read stdin when it is a TTY.""" + + def isatty(self): + return True + + from nitrostack.cli.main import ( DEFAULT_MCP_PORT, DEFAULT_PROJECT_NAME, @@ -41,6 +49,7 @@ init_project, main, print_banner, + register_cursor_server, register_server, run_dev, run_start, @@ -123,14 +132,14 @@ def test_init_with_name_and_explicit_template(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("A test server\nTester\n") + sys.stdin = _TtyInput("A test server\nTester\n") init_project("cli-demo", template="python-starter", skip_install=True) project = os.path.join(tmp, "cli-demo") assert os.path.isfile(os.path.join(project, "main.py")) env_text = open(os.path.join(project, ".env"), encoding="utf-8").read() assert "PORT=3000" in env_text assert "WIDGETS_DEV_PORT=3001" in env_text - assert "NITROSTACK_APP_MODE=universal" in env_text + assert "NITROSTACK_APP_MODE=openai" in env_text assert "SERVER_DESC=\"A test server\"" in env_text assert "SERVER_AUTHOR=\"Tester\"" in env_text assert os.path.isfile(os.path.join(project, "widgets", "out", "calculator-result.html")) @@ -150,7 +159,7 @@ def test_init_prompts_for_name_when_omitted(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("prompted-server\n\n\n") + sys.stdin = _TtyInput("prompted-server\n\n\n") init_project(None, template="python-starter", skip_install=True) assert os.path.isdir(os.path.join(tmp, "prompted-server")) print("Success! Missing name is asked on the next readline.") @@ -166,7 +175,7 @@ def test_init_default_name_when_blank_readline(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("\n\n\n") + sys.stdin = _TtyInput("\n\n\n") init_project(None, template="python-pizzaz", skip_install=True) assert os.path.isdir(os.path.join(tmp, DEFAULT_PROJECT_NAME)) env_text = open(os.path.join(tmp, DEFAULT_PROJECT_NAME, ".env"), encoding="utf-8").read() @@ -190,7 +199,7 @@ def test_init_python_oauth_template(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("\n\n") + sys.stdin = _TtyInput("\n\n") init_project("oauth-demo", template="python-oauth", skip_install=True) project = os.path.join(tmp, "oauth-demo") assert os.path.isfile(os.path.join(project, "OAUTH_SETUP.md")) @@ -279,7 +288,7 @@ def test_init_port_and_widget_flags_override_defaults(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("\n\n") + sys.stdin = _TtyInput("\n\n") init_project( "ports-demo", template="python-starter", @@ -307,7 +316,7 @@ def test_init_install_dependencies_prompt_no(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("desc\nauthor\nn\n") + sys.stdin = _TtyInput("desc\nauthor\nn\n") with patch("nitrostack.cli.main.install_dependencies") as pip_install: init_project("no-npm", template="python-starter") pip_install.assert_not_called() @@ -364,12 +373,25 @@ def test_run_npm_does_not_use_shell(): print("Success! npm is invoked as an argv list without shell=True.") +def test_prompts_return_defaults_without_tty(): + """Studio and CI inherit a non-TTY stdin: prompts must not read from it.""" + original = sys.stdin + try: + sys.stdin = io.StringIO("typed\n") + assert _prompt("Name", "fallback") == "fallback" + assert _prompt_template() == "python-starter" + assert _prompt_yes_no("Install", default_yes=False) is False + assert sys.stdin.read() == "typed\n" + print("Success! prompts use defaults and leave a non-TTY stdin unread.") + finally: + sys.stdin = original + def test_prompt_uses_value_or_default(): original = sys.stdin try: - sys.stdin = io.StringIO("custom\n") + sys.stdin = _TtyInput("custom\n") assert _prompt("Name", "fallback") == "custom" - sys.stdin = io.StringIO("\n") + sys.stdin = _TtyInput("\n") assert _prompt("Name", "fallback") == "fallback" class Boom: @@ -393,13 +415,13 @@ def test_resolve_template_accepts_official_names(): def test_prompt_template_choice_and_explicit_name(): original = sys.stdin try: - sys.stdin = io.StringIO("2\n") + sys.stdin = _TtyInput("2\n") assert _prompt_template() == "python-pizzaz" - sys.stdin = io.StringIO("python-oauth\n") + sys.stdin = _TtyInput("python-oauth\n") assert _prompt_template() == "python-oauth" - sys.stdin = io.StringIO("nope\n3\n") + sys.stdin = _TtyInput("nope\n3\n") assert _prompt_template() == "python-oauth" - sys.stdin = io.StringIO("\n") + sys.stdin = _TtyInput("\n") assert _prompt_template() == "python-starter" print("Success! _prompt_template handles numbers, names, retries, and default.") finally: @@ -457,19 +479,19 @@ def test_upsert_env_var_replaces_and_appends(): def test_prompt_yes_no_answers(): original = sys.stdin try: - sys.stdin = io.StringIO("\n") + sys.stdin = _TtyInput("\n") assert _prompt_yes_no("Install", default_yes=True) is True - sys.stdin = io.StringIO("\n") + sys.stdin = _TtyInput("\n") assert _prompt_yes_no("Install", default_yes=False) is False - sys.stdin = io.StringIO("y\n") + sys.stdin = _TtyInput("y\n") assert _prompt_yes_no("Install", default_yes=False) is True - sys.stdin = io.StringIO("yes\n") + sys.stdin = _TtyInput("yes\n") assert _prompt_yes_no("Install") is True - sys.stdin = io.StringIO("n\n") + sys.stdin = _TtyInput("n\n") assert _prompt_yes_no("Install") is False - sys.stdin = io.StringIO("no\n") + sys.stdin = _TtyInput("no\n") assert _prompt_yes_no("Install") is False - sys.stdin = io.StringIO("maybe\n") + sys.stdin = _TtyInput("maybe\n") assert _prompt_yes_no("Install", default_yes=True) is True print("Success! _prompt_yes_no handles Y/n, empty default, and unknown input.") finally: @@ -542,7 +564,7 @@ def test_init_project_rejects_blank_name_and_overwrite_cancel(): except SystemExit: pass os.mkdir("taken") - sys.stdin = io.StringIO("n\n") + sys.stdin = _TtyInput("n\n") try: init_project("taken", template="python-starter", skip_install=True) raise AssertionError("overwrite cancel should exit") @@ -566,14 +588,14 @@ def test_init_project_overwrite_and_install_yes_calls_npm(): os.chdir(tmp) os.mkdir("taken") open(os.path.join("taken", "old.txt"), "w", encoding="utf-8").write("x") - sys.stdin = io.StringIO("y\ndesc\nauthor\n") + sys.stdin = _TtyInput("y\ndesc\nauthor\n") with patch("nitrostack.cli.main._run_npm") as npm: init_project("taken", template="python-starter", skip_install=True) npm.assert_not_called() assert os.path.isfile(os.path.join("taken", "main.py")) assert not os.path.exists(os.path.join("taken", "old.txt")) - sys.stdin = io.StringIO("d\na\nY\n") + sys.stdin = _TtyInput("d\na\nY\n") with patch("nitrostack.cli.main.install_dependencies") as pip_install: with patch("nitrostack.cli.main._run_npm") as npm: init_project("installed", template="python-starter") @@ -582,7 +604,7 @@ def test_init_project_overwrite_and_install_yes_calls_npm(): npm.assert_not_called() assert os.path.isfile(os.path.join("installed", "widgets", "out", "calculator-result.html")) - sys.stdin = io.StringIO("d\na\n\n") + sys.stdin = _TtyInput("d\na\n\n") with patch("nitrostack.cli.main.install_dependencies") as pip_install: init_project("installed-enter", template="python-starter") pip_install.assert_called_once() @@ -802,6 +824,50 @@ def test_register_server_writes_config_and_handles_errors(): shutil.rmtree(tmp, ignore_errors=True) +def test_cursor_registration_merges_project_config_and_is_idempotent(tmp_path, monkeypatch): + import json + + project = tmp_path / "project" + project.mkdir() + monkeypatch.chdir(project) + (project / "main.py").write_text("print('hi')\n", encoding="utf-8") + config_path = project / ".cursor" / "mcp.json" + config_path.parent.mkdir() + config_path.write_text( + json.dumps({"mcpServers": {"other": {"url": "http://example.test/mcp"}}}), + encoding="utf-8", + ) + + register_cursor_server("demo", "main.py") + register_cursor_server("demo", "main.py") + + config = json.loads(config_path.read_text(encoding="utf-8")) + assert config["mcpServers"]["other"] == {"url": "http://example.test/mcp"} + assert config["mcpServers"]["demo"]["command"] == sys.executable + assert config["mcpServers"]["demo"]["args"] == [str((project / "main.py").resolve())] + assert len(config["mcpServers"]) == 2 + + +def test_cursor_registration_global_target_and_http_transports(tmp_path, monkeypatch): + import json + + home = tmp_path / "home" + home.mkdir() + monkeypatch.setattr("nitrostack.cli.main.os.path.expanduser", lambda value: str(home) if value == "~" else value) + project = tmp_path / "project" + project.mkdir() + monkeypatch.chdir(project) + + register_cursor_server("web", global_config=True, transport="streamable-http") + register_cursor_server("events", global_config=True, transport="sse") + + config_path = home / ".cursor" / "mcp.json" + config = json.loads(config_path.read_text(encoding="utf-8")) + assert config["mcpServers"]["web"] == {"url": "http://localhost:3000/mcp"} + assert config["mcpServers"]["events"] == {"url": "http://localhost:3000/sse"} + assert not (project / ".cursor" / "mcp.json").exists() + + def test_main_dispatches_commands(): from unittest.mock import patch @@ -851,6 +917,13 @@ def test_main_dispatches_commands(): ) as reg: main() reg.assert_called_once_with("x", "main.py") + + with patch( + "sys.argv", + ["nitrostack-py", "cursor", "--global", "--transport", "sse", "--name", "x"], + ), patch("nitrostack.cli.main.register_cursor_server") as cursor: + main() + cursor.assert_called_once_with("x", "main.py", global_config=True, transport="sse") print("Success! main() dispatches init/dev/start/generate/register.") @@ -879,7 +952,7 @@ def test_init_rewrites_pyproject_identity_and_copies_uv_files(template): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("Rewritten description\nTester\n") + sys.stdin = _TtyInput("Rewritten description\nTester\n") init_project("My_App", template=template, skip_install=True) project = os.path.join(tmp, "My_App") pyproject = open(os.path.join(project, "pyproject.toml"), encoding="utf-8").read() @@ -908,7 +981,7 @@ def test_init_runs_uv_lock_in_project_dir(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("\n\n") + sys.stdin = _TtyInput("\n\n") with patch.dict(os.environ, {}, clear=False): os.environ.pop("NITROSTACK_SKIP_UV_LOCK", None) with patch("nitrostack.cli.install._uv_bin", return_value="/usr/bin/uv"): @@ -930,7 +1003,7 @@ def test_init_succeeds_when_uv_is_missing(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("\n\n") + sys.stdin = _TtyInput("\n\n") with patch.dict(os.environ, {}, clear=False): os.environ.pop("NITROSTACK_SKIP_UV_LOCK", None) with patch("nitrostack.cli.install._uv_bin", return_value=None): @@ -949,7 +1022,7 @@ def test_init_succeeds_when_uv_lock_fails(): original_stdin = sys.stdin try: os.chdir(tmp) - sys.stdin = io.StringIO("\n\n") + sys.stdin = _TtyInput("\n\n") with patch.dict(os.environ, {}, clear=False): os.environ.pop("NITROSTACK_SKIP_UV_LOCK", None) with patch("nitrostack.cli.install._uv_bin", return_value="/usr/bin/uv"): @@ -1072,38 +1145,6 @@ def test_pack_dry_run_lists_files_without_writing(tmp_path: Path): assert not (project / "dist").exists() -def test_pack_include_env_dry_run_lists_env_without_printing_contents(tmp_path: Path, capsys): - project = _mini_project(tmp_path) - (project / ".env.local").write_text("TOKEN=local-secret\n", encoding="utf-8") - result = pack_project(str(project), dry_run=True, include_env=True) - assert result["dry_run"] is True - assert ".env" in result["files"] - assert ".env.local" in result["files"] - captured = capsys.readouterr().out - assert "Warning: Including .env files in the wheel (use with caution!)" in captured - assert ".env" in captured - assert ".env.local" in captured - assert "SECRET=should-never-pack" not in captured - assert "TOKEN=local-secret" not in captured - - -def test_pack_include_env_puts_env_in_wheel_without_printing_contents(tmp_path: Path, capsys): - project = _mini_project(tmp_path) - result = pack_project(str(project), dry_run=False, include_env=True) - captured = capsys.readouterr().out - assert "Warning: Including .env files in the wheel (use with caution!)" in captured - assert "SECRET=should-never-pack" not in captured - - wheel = Path(result["wheel"]) - with zipfile.ZipFile(wheel) as zf: - names = zf.namelist() - assert any(n == ".env" or n.endswith("/.env") for n in names) - env_data = next( - zf.read(n).decode("utf-8") for n in names if n == ".env" or n.endswith("/.env") - ) - assert "SECRET=should-never-pack" in env_data - - def test_pack_creates_valid_wheel(tmp_path: Path): project = _mini_project(tmp_path) result = pack_project(str(project), dry_run=False) @@ -1186,33 +1227,6 @@ def test_validate_catches_broken_imports_and_module_refs(tmp_path: Path): assert "→" in messages or "Fix the import" in messages -def test_validate_skips_the_vendored_sdk(tmp_path: Path): - """`init` vendors the SDK; its testing helpers apply @mcp_app inside functions.""" - (tmp_path / "pyproject.toml").write_text( - "[project]\n" - 'name = "vendored"\n' - 'version = "0.1.0"\n' - "dependencies = [\n" - ' "nitrostack",\n' - "]\n", - encoding="utf-8", - ) - sdk = tmp_path / "vendor" / "nitrostack" / "nitrostack" / "testing" - sdk.mkdir(parents=True) - (sdk / "__init__.py").write_text( - "from nitrostack import mcp_app, ServerConfig\n\n" - "def create(module):\n" - " @mcp_app(module=module, server=ServerConfig(name='test'))\n" - " class TestApp:\n" - " pass\n" - " return TestApp\n", - encoding="utf-8", - ) - - issues = validate_project(str(tmp_path)) - assert not [issue for issue in issues if "vendor" in issue.path], [i.format() for i in issues] - - def test_validate_accepts_module_only_bootstrap(tmp_path: Path): """Init templates use @module + McpApplicationFactory.create — no @mcp_app.""" (tmp_path / "pyproject.toml").write_text( @@ -1521,7 +1535,7 @@ def test_pack_and_validate_agree_on_bom_dependencies(tmp_path: Path): validate_deps = validate_parse((tmp_path / "pyproject.toml").read_text(encoding="utf-8-sig")) assert pack_deps == validate_deps assert pack_deps[0] == "uvicorn[standard]>=0.20" - assert requirements_from_project(str(tmp_path)) == pack_deps + assert [d for d in requirements_from_project(str(tmp_path)) if not d.lower().startswith("nitrostack")] == [d for d in pack_deps if not d.lower().startswith("nitrostack")] issues = validate_dependencies(str(tmp_path)) assert not any("not declared" in issue.message for issue in issues) diff --git a/tests/test_cli_install.py b/tests/test_cli_install.py index 2088914..3d2b3c5 100644 --- a/tests/test_cli_install.py +++ b/tests/test_cli_install.py @@ -24,6 +24,9 @@ def _uv_absent(monkeypatch): """Keep the existing pip-path tests off a real uv binary on PATH.""" monkeypatch.setattr("nitrostack.cli.install._uv_bin", lambda: None) + # pip/uv version gates are covered in test_cli_install_security.py + monkeypatch.setattr("nitrostack.cli.install._ensure_secure_pip", lambda *a, **k: None) + monkeypatch.setattr("nitrostack.cli.install._check_uv_version", lambda *a, **k: None) def test_optional_extra_names_parses_pyproject(): diff --git a/tests/test_cli_install_security.py b/tests/test_cli_install_security.py new file mode 100644 index 0000000..2649b01 --- /dev/null +++ b/tests/test_cli_install_security.py @@ -0,0 +1,158 @@ +"""eMudhra/emSign remediation: secure pip bootstrap and uv version gate.""" +from __future__ import annotations + +import os +import sys +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from nitrostack.cli.install import ( # noqa: E402 + SECURE_PIP_SPEC, + _check_uv_version, + _ensure_secure_pip, + _get_pip_version, + _parse_version, + _run_pip, + _run_uv, +) + +MOD = "nitrostack.cli.install" + + +def _ok(stdout: str = "") -> SimpleNamespace: + return SimpleNamespace(returncode=0, stdout=stdout, stderr="") + + +def _fail() -> SimpleNamespace: + return SimpleNamespace(returncode=1, stdout="", stderr="") + + +# ---- version parsing ------------------------------------------------------ + +def test_parse_pip_two_and_three_part_versions(): + assert _parse_version("pip 24.0 from /x/pip (python 3.12)", "pip") == (24, 0, 0) + assert _parse_version("pip 26.2.2 from /x/pip (python 3.12)", "pip") == (26, 2, 2) + + +def test_parse_uv_version_with_build_suffix(): + assert _parse_version("uv 0.13.4 (abc123 2026-10-20)", "uv") == (0, 13, 4) + + +def test_parse_garbage_returns_none(): + assert _parse_version("command not found", "pip") is None + assert _parse_version("", "uv") is None + + +def test_get_pip_version_none_when_command_fails(): + with patch(f"{MOD}.subprocess.run", return_value=_fail()): + assert _get_pip_version("python") is None + + +def test_get_pip_version_none_when_python_missing(): + with patch(f"{MOD}.subprocess.run", side_effect=OSError("nope")): + assert _get_pip_version("python") is None + + +# ---- pip bootstrap -------------------------------------------------------- + +@pytest.mark.parametrize("version", [(26, 2, 2), (26, 3, 0), (27, 0, 0)]) +def test_pip_already_secure_skips_bootstrap(version, tmp_path): + with patch(f"{MOD}._get_pip_version", return_value=version): + with patch(f"{MOD}.subprocess.run") as run: + _ensure_secure_pip("python", str(tmp_path)) + run.assert_not_called() + + +def test_outdated_pip_is_upgraded_with_pinned_wheel(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[(24, 0, 0), (26, 2, 2)]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()) as run: + _ensure_secure_pip("python", str(tmp_path)) + run.assert_called_once() + assert run.call_args.args[0] == ["python", "-m", "pip", "install", SECURE_PIP_SPEC] + assert "#sha256=" in SECURE_PIP_SPEC + + +def test_unknown_pip_version_triggers_upgrade(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[None, (26, 2, 2)]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()) as run: + _ensure_secure_pip("python", str(tmp_path)) + run.assert_called_once() + + +def test_pip_upgrade_failure_raises_actionable_error(tmp_path): + with patch(f"{MOD}._get_pip_version", return_value=(24, 0, 0)): + with patch(f"{MOD}.subprocess.run", return_value=_fail()): + with pytest.raises(RuntimeError, match="Secure pip upgrade failed"): + _ensure_secure_pip("python", str(tmp_path)) + + +def test_pip_still_old_after_upgrade_raises(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[(24, 0, 0), (24, 0, 0)]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()): + with pytest.raises(RuntimeError, match="still below 26.2.2"): + _ensure_secure_pip("python", str(tmp_path)) + + +def test_pip_version_unverifiable_after_upgrade_raises(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[(24, 0, 0), None]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()): + with pytest.raises(RuntimeError, match="still below 26.2.2"): + _ensure_secure_pip("python", str(tmp_path)) + + +def test_run_pip_stops_before_installing_when_bootstrap_fails(tmp_path): + with patch(f"{MOD}.ensure_project_venv", return_value="python"): + with patch(f"{MOD}._ensure_secure_pip", side_effect=RuntimeError("boom")): + with patch(f"{MOD}.subprocess.run") as run: + with pytest.raises(RuntimeError, match="boom"): + _run_pip(["-e", "."], cwd=str(tmp_path)) + run.assert_not_called() + + +def test_run_pip_bootstraps_before_installing(tmp_path): + order: list[str] = [] + with patch(f"{MOD}.ensure_project_venv", return_value="python"): + with patch(f"{MOD}._ensure_secure_pip", side_effect=lambda *a, **k: order.append("bootstrap")): + with patch( + f"{MOD}.subprocess.run", + side_effect=lambda *a, **k: order.append("install") or _ok(), + ): + _run_pip(["-e", "."], cwd=str(tmp_path)) + assert order == ["bootstrap", "install"] + + +# ---- uv gate -------------------------------------------------------------- + +@pytest.mark.parametrize("version", [(0, 13, 4), (0, 14, 0), (1, 0, 0)]) +def test_uv_meeting_minimum_is_allowed(version): + with patch(f"{MOD}._get_uv_version", return_value=version): + _check_uv_version("/usr/bin/uv") + + +@pytest.mark.parametrize("version", [(0, 13, 3), (0, 9, 0), None]) +def test_old_or_unknown_uv_is_blocked(version): + with patch(f"{MOD}._get_uv_version", return_value=version): + with pytest.raises(RuntimeError, match="0.13.4"): + _check_uv_version("/usr/bin/uv") + + +def test_run_uv_blocked_before_any_download(tmp_path): + with patch(f"{MOD}._uv_bin", return_value="/usr/bin/uv"): + with patch(f"{MOD}._get_uv_version", return_value=(0, 13, 3)): + with patch(f"{MOD}.subprocess.run") as run: + with pytest.raises(RuntimeError, match="uv 0.13.4"): + _run_uv(["sync"], cwd=str(tmp_path)) + run.assert_not_called() + + +def test_run_uv_runs_when_version_ok(tmp_path): + with patch(f"{MOD}._uv_bin", return_value="/usr/bin/uv"): + with patch(f"{MOD}._get_uv_version", return_value=(0, 13, 4)): + with patch(f"{MOD}.subprocess.run", return_value=_ok()) as run: + _run_uv(["sync"], cwd=str(tmp_path)) + run.assert_called_once() + assert run.call_args.args[0] == ["/usr/bin/uv", "sync"] \ No newline at end of file diff --git a/tests/test_cli_studio_noninteractive.py b/tests/test_cli_studio_noninteractive.py new file mode 100644 index 0000000..31dfc1b --- /dev/null +++ b/tests/test_cli_studio_noninteractive.py @@ -0,0 +1,120 @@ +"""Studio generate-wizard contract: init must not block on inherited stdin. + +NitroStudio step 4 of 5 used to hang because `nitrostack-py init --skip-install` +still prompted Description/Author via readline() on an inherited stdin that +never wrote. --skip-install only skips dependency install. + +These tests spawn the real CLI with stdin left open (PIPE, never written, never +closed) so they fail if prompts return. +""" +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + + +def _cli_env(): + env = os.environ.copy() + env["PYTHONPATH"] = ROOT + env["PYTHONUNBUFFERED"] = "1" + return env + + +def _run_init_open_stdin(cwd: str, extra_args: list[str], timeout: float = 20.0): + """Spawn init with stdin PIPE left open. Do not write or close it.""" + proc = subprocess.Popen( + [sys.executable, "-m", "nitrostack.cli.main", *extra_args], + cwd=cwd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=_cli_env(), + ) + chunks_out: list[bytes] = [] + chunks_err: list[bytes] = [] + + def _drain(stream, bucket): + try: + while True: + data = stream.read(4096) + if not data: + break + bucket.append(data) + except Exception: + pass + + threading.Thread(target=_drain, args=(proc.stdout, chunks_out), daemon=True).start() + threading.Thread(target=_drain, args=(proc.stderr, chunks_err), daemon=True).start() + + deadline = time.time() + timeout + while proc.poll() is None: + if time.time() > deadline: + proc.kill() + proc.wait(timeout=5) + stdout = b"".join(chunks_out).decode("utf-8", "replace") + stderr = b"".join(chunks_err).decode("utf-8", "replace") + raise TimeoutError( + f"CLI hung for {timeout}s on open unused stdin\n" + f"stdout:\n{stdout}\nstderr:\n{stderr}" + ) + time.sleep(0.05) + + stdout = b"".join(chunks_out).decode("utf-8", "replace") + stderr = b"".join(chunks_err).decode("utf-8", "replace") + return proc.returncode, stdout, stderr + + +def test_init_skip_install_does_not_hang_on_open_unused_stdin(): + tmp = tempfile.mkdtemp(prefix="nitro-cli-studio-") + try: + code, stdout, stderr = _run_init_open_stdin( + tmp, + ["init", "studio_demo", "--template", "python-starter", "--skip-install"], + ) + assert code == 0, f"exit {code}\n{stdout}\n{stderr}" + project = Path(tmp) / "studio_demo" + assert (project / "main.py").is_file() + assert (project / "app_module.py").is_file() + req = (project / "requirements.txt").read_text(encoding="utf-8") + assert "nitrostack" in req.lower() + finally: + import shutil + + shutil.rmtree(tmp, ignore_errors=True) + + +def test_init_without_args_uses_defaults_on_open_unused_stdin(): + tmp = tempfile.mkdtemp(prefix="nitro-cli-noargs-") + try: + code, stdout, stderr = _run_init_open_stdin(tmp, ["init", "--skip-install"]) + assert code == 0, f"exit {code}\n{stdout}\n{stderr}" + project = Path(tmp) / "my-mcp-server" + assert (project / "main.py").is_file() + finally: + import shutil + + shutil.rmtree(tmp, ignore_errors=True) + +def test_init_existing_dir_exits_without_overwrite_prompt(): + tmp = tempfile.mkdtemp(prefix="nitro-cli-exists-") + try: + os.mkdir(os.path.join(tmp, "already")) + code, stdout, stderr = _run_init_open_stdin( + tmp, + ["init", "already", "--template", "python-starter", "--skip-install"], + timeout=15.0, + ) + assert code != 0 + combined = (stdout + stderr).lower() + assert "already exists" in combined + finally: + import shutil + + shutil.rmtree(tmp, ignore_errors=True) diff --git a/tests/test_cli_upgrade_vendored.py b/tests/test_cli_upgrade_vendored.py index 8cc09c8..45f3398 100644 --- a/tests/test_cli_upgrade_vendored.py +++ b/tests/test_cli_upgrade_vendored.py @@ -123,7 +123,9 @@ def test_upgrade_replaces_the_vendored_sdk_from_the_wheel(project: Path, no_skil assert deps == ["mcp<3,>=2", "pydantic>=2.0.0", 'tomli>=2.0.0; python_version < "3.11"'] # The project keeps the plain name; the vendored copy decides the version. assert (project / "pyproject.toml").read_text(encoding="utf-8") == pyproject_before - assert (project / "requirements.txt").read_text(encoding="utf-8") == "nitrostack\n" + from nitrostack.cli.vendor import runtime_nitrostack_requirement + + assert (project / "requirements.txt").read_text(encoding="utf-8") == f"{runtime_nitrostack_requirement()}\n" assert not [p for p in (project / "vendor").iterdir() if p.name.startswith(".nitrostack-")] diff --git a/tests/test_decorators_extra.py b/tests/test_decorators_extra.py index fdd64fa..0580c69 100644 --- a/tests/test_decorators_extra.py +++ b/tests/test_decorators_extra.py @@ -1,4 +1,6 @@ + """Phase 6 — cache, rate_limit, and health_check decorators.""" + from __future__ import annotations import asyncio @@ -46,7 +48,11 @@ def test_cache_returns_same_result_within_ttl(): class Svc: @cache(ttl=60) - async def add(self, value: int, context: ExecutionContext | None = None) -> int: + async def add( + self, + value: int, + context: ExecutionContext | None = None, + ) -> int: calls["n"] += 1 return value + 1 @@ -83,8 +89,9 @@ def db_ok(self) -> bool: return True HealthCheckRegistry.bind_instance("db", Probe.db_ok, Probe()) - results = HealthCheckRegistry.run_all() + results = asyncio.run(HealthCheckRegistry.run_all()) assert results["db"] == "healthy" + HealthCheckRegistry._checks.clear() HealthCheckRegistry._bound_checks.clear() @@ -97,8 +104,9 @@ def boom(): raise RuntimeError("down") HealthCheckRegistry._bound_checks["svc"] = boom - results = HealthCheckRegistry.run_all() + results = asyncio.run(HealthCheckRegistry.run_all()) assert results["svc"].startswith("error:") + HealthCheckRegistry._checks.clear() HealthCheckRegistry._bound_checks.clear() @@ -115,14 +123,14 @@ def down(): HealthCheckRegistry._bound_checks["async"] = async_ok HealthCheckRegistry._bound_checks["down"] = down - results = HealthCheckRegistry.run_all() + results = asyncio.run(HealthCheckRegistry.run_all()) assert results["async"] == "healthy" assert results["down"] == "unhealthy" + HealthCheckRegistry._checks.clear() HealthCheckRegistry._bound_checks.clear() - def test_copy_mcp_attributes_copies_mcp_prefixed_fields(): def src(): return None diff --git a/tests/test_decorators_limits.py b/tests/test_decorators_limits.py new file mode 100644 index 0000000..6591eac --- /dev/null +++ b/tests/test_decorators_limits.py @@ -0,0 +1,170 @@ +import asyncio + +import pytest + +from nitrostack import RateLimitExceededError, cache, rate_limit +from nitrostack.core import additional_decorators as deco + + +@pytest.mark.parametrize("bad", [0, -1, 1.5, True]) +def test_rate_limit_rejects_invalid_max(bad): + with pytest.raises(ValueError): + rate_limit(max=bad, window=1) + + +@pytest.mark.parametrize("bad", [0, -5]) +def test_rate_limit_rejects_non_positive_window(bad): + with pytest.raises(ValueError): + rate_limit(max=1, window=bad) + + +@pytest.mark.parametrize("bad", [0, -1]) +def test_cache_rejects_non_positive_max_size(bad): + with pytest.raises(ValueError): + cache(ttl=60, max_size=bad) + + +def test_cache_rejects_non_positive_ttl(): + with pytest.raises(ValueError): + cache(ttl=0) + + +def test_cache_allows_unbounded_and_default_sizes(): + cache(ttl=60, max_size=None) + cache(ttl=60) + + +class Clock: + def __init__(self): + self.now = 1000.0 + + def __call__(self): + return self.now + + +@pytest.fixture +def clock(monkeypatch): + c = Clock() + monkeypatch.setattr(deco.time, "time", c) + return c + + +def run(coro): + return asyncio.run(coro) + + +def test_cache_evicts_least_recently_used(clock): + calls = [] + + @cache(ttl=60, max_size=2) + async def f(x): + calls.append(x) + return x + + run(f(1)) + run(f(2)) + run(f(1)) + run(f(3)) + run(f(1)) + run(f(2)) + assert calls == [1, 2, 3, 2] + + +def test_cache_purges_expired_entries_before_lru(clock): + calls = [] + + @cache(ttl=10, max_size=2) + async def f(x): + calls.append(x) + return x + + run(f(1)) + clock.now += 5 + run(f(2)) + clock.now += 6 + run(f(3)) + run(f(2)) + assert calls == [1, 2, 3] + + +def test_cache_unbounded_when_max_size_none(clock): + calls = [] + + @cache(ttl=60, max_size=None) + async def f(x): + calls.append(x) + return x + + for i in range(2000): + run(f(i)) + for i in range(2000): + run(f(i)) + assert len(calls) == 2000 + + +def test_cache_clear(clock): + calls = [] + + @cache(ttl=60) + async def f(x): + calls.append(x) + return x + + run(f(1)) + run(f(1)) + f.cache_clear() + run(f(1)) + assert calls == [1, 1] + + +def test_cache_rejects_invalid_max_size(): + with pytest.raises(ValueError): + cache(ttl=60, max_size=0) + + +def test_rate_limit_error_is_typed_and_has_retry_after(clock): + @rate_limit(max=2, window=60) + async def ping(): + return "ok" + + run(ping()) + clock.now += 10 + run(ping()) + with pytest.raises(RateLimitExceededError) as info: + run(ping()) + assert isinstance(info.value, ValueError) + assert info.value.retry_after_seconds == pytest.approx(50) + assert "Rate limit exceeded" in str(info.value) + + +def test_rate_limit_recovers_after_window(clock): + @rate_limit(max=1, window=60) + async def ping(): + return "ok" + + run(ping()) + with pytest.raises(RateLimitExceededError): + run(ping()) + clock.now += 60 + assert run(ping()) == "ok" + + +def test_rate_limit_per_key(clock): + @rate_limit(max=1, window=60, key=lambda user: user) + async def ping(user): + return user + + assert run(ping("a")) == "a" + assert run(ping("b")) == "b" + with pytest.raises(RateLimitExceededError): + run(ping("a")) + + +def test_rate_limit_default_is_shared(clock): + @rate_limit(max=1, window=60) + async def ping(user): + return user + + run(ping("a")) + with pytest.raises(RateLimitExceededError): + run(ping("b")) \ No newline at end of file diff --git a/tests/test_dev_hot_reload.py b/tests/test_dev_hot_reload.py new file mode 100644 index 0000000..b4b8d53 --- /dev/null +++ b/tests/test_dev_hot_reload.py @@ -0,0 +1,136 @@ +"""Integration test for nitrostack-py dev hot reload.""" + +from __future__ import annotations + +import json +import os +import signal +import subprocess +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +import pytest + + +def _list_calculate_description(port: int) -> str: + req = urllib.request.Request( + f"http://127.0.0.1:{port}/mcp", + data=json.dumps( + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/list", + "params": { + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": {"name": "pytest-dev-reload", "version": "1"}, + "io.modelcontextprotocol/clientCapabilities": {}, + } + }, + } + ).encode(), + headers={ + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + "MCP-Protocol-Version": "2026-07-28", + "Mcp-Method": "tools/list", + }, + method="POST", + ) + with urllib.request.urlopen(req, timeout=8) as resp: + raw = resp.read().decode() + if raw.startswith("{"): + body = json.loads(raw) + else: + body = json.loads(next(line[5:].strip() for line in raw.splitlines() if line.startswith("data:"))) + return next(tool["description"] for tool in body["result"]["tools"] if tool["name"] == "calculate") + + +def _wait_for_health(port: int, timeout: float = 12.0) -> None: + deadline = time.time() + timeout + while time.time() < deadline: + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/mcp/health", timeout=2) as resp: + if json.loads(resp.read().decode()).get("status") == "ok": + return + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError): + time.sleep(0.2) + raise AssertionError(f"MCP server did not become healthy on port {port}") + + +@pytest.mark.timeout(30) +def test_dev_hot_reload_updates_tool_description(tmp_path: Path) -> None: + port = 47640 + marker = "PYTEST_DEV_RELOAD" + env = {**os.environ, "DO_NOT_TRACK": "1"} + init = subprocess.run( + [sys.executable, "-m", "nitrostack.cli.main", "init", "app", "--template", "python-starter", "--skip-install"], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + assert init.returncode == 0, init.stderr or init.stdout + project = tmp_path / "app" + tool_file = project / "modules" / "calculator" / "calculator_tools.py" + original = tool_file.read_text(encoding="utf-8") + (project / ".env").write_text("MCP_TRANSPORT_TYPE=http\nDO_NOT_TRACK=1\n", encoding="utf-8") + needle = "Perform basic arithmetic calculations" + + dev = subprocess.Popen( + [sys.executable, "-m", "nitrostack.cli.main", "dev", "--port", str(port)], + cwd=project, + env={**env, "MCP_TRANSPORT_TYPE": "http"}, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + _wait_for_health(port) + assert marker not in _list_calculate_description(port) + tool_file.write_text(original.replace(needle, f"{needle} {marker}", 1), encoding="utf-8") + + deadline = time.time() + 10 + while time.time() < deadline: + try: + if marker in _list_calculate_description(port): + break + except urllib.error.URLError: + pass + time.sleep(0.4) + else: + pytest.fail("calculate tool description did not reload within 10s") + + dev.send_signal(signal.SIGINT) + dev.wait(timeout=8) + assert dev.returncode is not None + if sys.platform != "win32": + # Parent must not leave the HTTP child listening after shutdown. + time.sleep(0.5) + with pytest.raises((urllib.error.URLError, ConnectionError)): + with urllib.request.urlopen(f"http://127.0.0.1:{port}/mcp/health", timeout=1): + pass + finally: + tool_file.write_text(original, encoding="utf-8") + if dev.poll() is None: + dev.kill() + dev.wait(timeout=3) + +def test_stop_child_never_signals_a_group_it_did_not_create(monkeypatch): + """A fake or non-leader process must not reach os.killpg (pid 1 is init's group).""" + from unittest.mock import MagicMock + + from nitrostack.cli import _servers + + sent = [] + monkeypatch.setattr(_servers.os, "killpg", lambda *a: sent.append(a)) + fake = MagicMock() + fake.poll.return_value = None + for pid in (MagicMock(), 0, 1, os.getpid()): + fake.pid = pid + _servers._stop_child(fake) + assert sent == [] + assert fake.terminate.called diff --git a/tests/test_file_length_check.py b/tests/test_file_length_check.py new file mode 100644 index 0000000..17ff5de --- /dev/null +++ b/tests/test_file_length_check.py @@ -0,0 +1,189 @@ +"""Tests for the dependency-free file-length checker and baseline ratchet.""" + +import sys +from pathlib import Path + +# Ensure repo root is in sys.path so scripts can be imported cleanly +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + + +from scripts.check_file_lengths import ( + check_files, + count_physical_lines, + load_baseline, + run_check, + save_baseline, +) + + +def test_count_physical_lines(tmp_path: Path): + file_path = tmp_path / "sample.py" + # Content with blank lines, comments, docstrings, multiline strings + content = '"""Module docstring.\nLine 2.\n"""\n\n# A comment\nx = 1\n' + file_path.write_text(content, encoding="utf-8") + assert count_physical_lines(file_path) == 6 + + # Trailing newline does not add a phantom line + file_path_no_newline = tmp_path / "no_newline.py" + file_path_no_newline.write_text("a = 1\nb = 2", encoding="utf-8") + assert count_physical_lines(file_path_no_newline) == 2 + + # Non-existent file + assert count_physical_lines(tmp_path / "non_existent.py") == 0 + + +def test_file_exactly_at_500_lines(tmp_path: Path): + repo_root = tmp_path + py_file = repo_root / "nitrostack" / "boundary.py" + py_file.parent.mkdir(parents=True) + # Write exactly 500 lines + py_file.write_text("\n".join(f"x_{i} = {i}" for i in range(500)), encoding="utf-8") + + tracked = ["nitrostack/boundary.py"] + baseline = {} + + violations, ratcheted = check_files( + repo_root=repo_root, + tracked_files=tracked, + baseline=baseline, + max_lines=500, + ) + assert len(violations) == 0 + assert ratcheted == {} + + +def test_new_file_over_500_lines(tmp_path: Path): + repo_root = tmp_path + py_file = repo_root / "nitrostack" / "large.py" + py_file.parent.mkdir(parents=True) + # Write 501 lines + py_file.write_text("\n".join(f"x_{i} = {i}" for i in range(501)), encoding="utf-8") + + tracked = ["nitrostack/large.py"] + baseline = {} + + violations, _ = check_files( + repo_root=repo_root, + tracked_files=tracked, + baseline=baseline, + max_lines=500, + ) + assert len(violations) == 1 + v = violations[0] + assert v.path == "nitrostack/large.py" + assert v.count == 501 + assert v.allowed == 500 + assert v.violation_type == "new_file" + assert "File exceeds line limit" in v.message + + +def test_baseline_growth(tmp_path: Path): + repo_root = tmp_path + py_file = repo_root / "nitrostack" / "legacy.py" + py_file.parent.mkdir(parents=True) + # File has 600 lines, baseline is 550 + py_file.write_text("\n".join(f"x_{i} = {i}" for i in range(600)), encoding="utf-8") + + tracked = ["nitrostack/legacy.py"] + baseline = {"nitrostack/legacy.py": 550} + + violations, _ = check_files( + repo_root=repo_root, + tracked_files=tracked, + baseline=baseline, + max_lines=500, + ) + assert len(violations) == 1 + v = violations[0] + assert v.path == "nitrostack/legacy.py" + assert v.count == 600 + assert v.allowed == 550 + assert v.violation_type == "baseline_growth" + assert "File grew above baseline" in v.message + + +def test_file_below_its_baseline_ratchet(tmp_path: Path): + repo_root = tmp_path + py_file = repo_root / "nitrostack" / "legacy.py" + py_file.parent.mkdir(parents=True) + # File previously was 700 lines (in baseline), now shrunk to 620 lines (> 500) + py_file.write_text("\n".join(f"x_{i} = {i}" for i in range(620)), encoding="utf-8") + + tracked = ["nitrostack/legacy.py"] + baseline = {"nitrostack/legacy.py": 700} + + violations, ratcheted = check_files( + repo_root=repo_root, + tracked_files=tracked, + baseline=baseline, + max_lines=500, + ) + assert len(violations) == 0 + # Ratchet lowered the baseline + assert ratcheted["nitrostack/legacy.py"] == 620 + + +def test_file_drops_to_or_below_500_removed_from_baseline(tmp_path: Path): + repo_root = tmp_path + py_file = repo_root / "nitrostack" / "legacy.py" + py_file.parent.mkdir(parents=True) + # File was 600 in baseline, now shrunk to 500 lines + py_file.write_text("\n".join(f"x_{i} = {i}" for i in range(500)), encoding="utf-8") + + tracked = ["nitrostack/legacy.py"] + baseline = {"nitrostack/legacy.py": 600} + + violations, ratcheted = check_files( + repo_root=repo_root, + tracked_files=tracked, + baseline=baseline, + max_lines=500, + ) + assert len(violations) == 0 + # Ratchet removed it from baseline because it now satisfies the standard 500 threshold + assert "nitrostack/legacy.py" not in ratcheted + + +def test_baseline_save_and_load(tmp_path: Path): + baseline_path = tmp_path / "baseline.json" + data = {"b.py": 600, "a.py": 700} + save_baseline(baseline_path, data) + + # Should be saved sorted by key + loaded = load_baseline(baseline_path) + assert list(loaded.keys()) == ["a.py", "b.py"] + assert loaded == {"a.py": 700, "b.py": 600} + + +def test_run_check_flow_and_update_baseline(tmp_path: Path, capsys): + repo_root = tmp_path + baseline_path = repo_root / ".file_length_baseline.json" + + # Create tracked files under nitrostack and tests + f1 = repo_root / "nitrostack" / "f1.py" + f1.parent.mkdir(parents=True) + f1.write_text("\n".join(f"x_{i} = {i}" for i in range(550)), encoding="utf-8") + + save_baseline(baseline_path, {"nitrostack/f1.py": 600}) + + # Run check without update: should succeed (550 <= 600) and notify ratchet + code = run_check(repo_root=repo_root, baseline_path=baseline_path, update_baseline=False) + assert code == 0 + captured = capsys.readouterr().out + assert "Baseline ratchet improvement detected" in captured + + # Run check with update: should update baseline + code = run_check(repo_root=repo_root, baseline_path=baseline_path, update_baseline=True) + assert code == 0 + updated_baseline = load_baseline(baseline_path) + assert updated_baseline["nitrostack/f1.py"] == 550 + + # Grow file to 580: should fail + f1.write_text("\n".join(f"x_{i} = {i}" for i in range(580)), encoding="utf-8") + code = run_check(repo_root=repo_root, baseline_path=baseline_path, update_baseline=False) + assert code == 1 + captured = capsys.readouterr().out + assert "FAILED: Found 1 Python file-length violation(s)" in captured + assert "baseline_growth" in captured diff --git a/tests/test_flight_booking.py b/tests/test_flight_booking.py index d01cd62..0e39bc1 100644 --- a/tests/test_flight_booking.py +++ b/tests/test_flight_booking.py @@ -100,6 +100,7 @@ class FlightStudioModule: def test_studio_can_search_flights_without_token(): os.environ.pop("OAUTH_REQUIRED", None) + os.environ["NITROSTACK_APP_MODE"] = "universal" async def run(): harness = await NitroTestingModule.create(FlightStudioModule) diff --git a/tests/test_health_async_checks.py b/tests/test_health_async_checks.py new file mode 100644 index 0000000..b48765f --- /dev/null +++ b/tests/test_health_async_checks.py @@ -0,0 +1,174 @@ +import asyncio +import json +import threading +import warnings + +import pytest + +from nitrostack import injectable, module +from nitrostack.core.additional_decorators import HealthCheckRegistry, health_check +from nitrostack.testing import NitroTestingModule + + +@pytest.fixture(autouse=True) +def clean_registry(): + saved = (dict(HealthCheckRegistry._checks), dict(HealthCheckRegistry._bound_checks)) + HealthCheckRegistry._checks.clear() + HealthCheckRegistry._bound_checks.clear() + yield + HealthCheckRegistry._checks.clear() + HealthCheckRegistry._bound_checks.clear() + HealthCheckRegistry._checks.update(saved[0]) + HealthCheckRegistry._bound_checks.update(saved[1]) + + +def _app_module(): + @injectable() + class Svc: + @health_check("async_ok") + async def async_ok(self): + await asyncio.sleep(0) + return True + + @health_check("sync_ok") + def sync_ok(self): + return True + + @health_check("async_boom") + async def async_boom(self): + raise RuntimeError("db down") + + @module(name="m", providers=[Svc]) + class M: + pass + + return M + + +def _read_status(): + async def run(): + harness = await NitroTestingModule.create(_app_module()) + raw = await harness.read_resource("health://status") + return json.loads(raw) if isinstance(raw, str) else raw + + return asyncio.run(run()) + + +def test_async_and_sync_checks_both_report_healthy(): + status = _read_status() + assert "event loop" not in str(status["async_ok"]) + assert status["async_ok"] == status["sync_ok"] + + +def test_raising_check_reports_error_without_affecting_others(): + status = _read_status() + assert "db down" in status["async_boom"] + assert "error" not in str(status["async_ok"]) + assert "error" not in str(status["sync_ok"]) + + +def test_no_never_awaited_warning(): + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + _read_status() + + +def _read_checks(app_module): + async def run(): + harness = await NitroTestingModule.create(app_module) + return await harness.read_resource("health://checks") + + return asyncio.run(run()) + + +def test_health_payload_distinguishes_healthy_degraded_and_failing(): + @injectable() + class Svc: + @health_check("healthy") + def healthy(self): + return True + + @health_check("degraded") + def degraded(self): + return False + + @health_check("failing") + def failing(self): + raise RuntimeError("dependency unavailable") + + @module(name="health-statuses", providers=[Svc]) + class M: + pass + + payload = _read_checks(M) + statuses = {check["name"]: check["status"] for check in payload["checks"]} + assert statuses == {"healthy": "healthy", "degraded": "unhealthy", "failing": "error"} + failing_check = next(check for check in payload["checks"] if check["name"] == "failing") + assert failing_check["message"] == "Check failed" + assert payload["status"] == "unhealthy" + + +def test_false_check_degrades_aggregate_without_failing_it(): + @injectable() + class Svc: + @health_check("partial") + def partial(self): + return False + + @module(name="health-degraded", providers=[Svc]) + class M: + pass + + payload = _read_checks(M) + assert payload["status"] == "degraded" + + +def test_timed_out_sync_check_does_not_block_asyncio_run_or_other_checks(): + release = threading.Event() + + @injectable() + class Svc: + @health_check("slow_sync", timeout=0.05) + def slow_sync(self): + release.wait(timeout=5) + return True + + @health_check("fast") + async def fast(self): + await asyncio.sleep(0.005) + return True + + @module(name="health-timeouts", providers=[Svc]) + class M: + pass + + result = {} + read_complete = threading.Event() + + def read_resource(): + try: + result["payload"] = _read_checks(M) + finally: + read_complete.set() + + reader = threading.Thread(target=read_resource) + reader.start() + completed_before_release = read_complete.wait(timeout=2) + release.set() + reader.join(timeout=2) + + assert completed_before_release, "asyncio.run waited for the timed-out sync check" + assert not reader.is_alive() + payload = result["payload"] + statuses = {check["name"]: check for check in payload["checks"]} + assert statuses["slow_sync"]["status"] == "timeout" + assert statuses["slow_sync"]["message"] == "Timed out after 0.05s" + assert statuses["fast"]["status"] == "healthy" + assert payload["status"] == "unhealthy" + + +def test_health_status_retains_legacy_string_map(): + status = _read_status() + assert status["async_ok"] == "healthy" + assert status["sync_ok"] == "healthy" + assert status["async_boom"] == "error: db down" diff --git a/tests/test_json_body_limit.py b/tests/test_json_body_limit.py new file mode 100644 index 0000000..59a5b27 --- /dev/null +++ b/tests/test_json_body_limit.py @@ -0,0 +1,205 @@ +"""Configurable JSON body limit on HTTP transports (TS #366).""" + +from __future__ import annotations + +import asyncio +import json +import os +import sys +from typing import Any + +import pytest +from starlette.testclient import TestClient + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from pydantic import BaseModel + +from nitrostack import McpApplicationFactory, ServerConfig, injectable, mcp_app, module, tool +from nitrostack.core.context import ExecutionContext +from nitrostack.transports.http import build_http_app +from nitrostack.transports.http.middleware import JsonBodyLimitMiddleware + +INITIALIZE = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "1.0"}, + }, +} + + +class EmptyInput(BaseModel): + pass + + +@injectable() +class PingController: + @tool(name="ping", description="ping", input_schema=EmptyInput) + async def ping(self, input: EmptyInput, context: ExecutionContext) -> str: + return "pong" + + +@module(name="ping", controllers=[PingController]) +class PingModule: + pass + + +async def _app(): + @mcp_app(module=PingModule, server=ServerConfig(name="body-limit-test", protocol_era="legacy")) + class TestApp: + pass + + return await McpApplicationFactory.create(TestApp) + + +def _big_initialize(padding: str) -> dict: + body = dict(INITIALIZE) + body["params"] = dict(body["params"]) + body["params"]["clientInfo"] = dict(body["params"]["clientInfo"]) + body["params"]["clientInfo"]["padding"] = padding + return body + + +def _json_post_scope(content_type: bytes = b"application/json") -> dict[str, Any]: + return { + "type": "http", + "asgi": {"spec_version": "2.4", "version": "3.0"}, + "http_version": "1.1", + "method": "POST", + "scheme": "http", + "path": "/mcp", + "raw_path": b"/mcp", + "query_string": b"", + "root_path": "", + "headers": [(b"content-type", content_type)], + "client": ("testclient", 50000), + "server": ("testserver", 80), + "state": {}, + } + + +def test_json_body_limit_rejects_oversize_with_413(): + app = asyncio.run(_app()) + http_app = build_http_app( + app, + enable_cors=True, + protocol_era="legacy", + json_body_limit="1kb", + ) + big = _big_initialize("x" * 2048) + with TestClient(http_app) as client: + assert client.post("/mcp", json=big).status_code == 413 + assert client.post("/mcp", json=INITIALIZE).status_code == 200 + + +def test_json_body_limit_default_accepts_over_1kb(): + app = asyncio.run(_app()) + http_app = build_http_app(app, enable_cors=True, protocol_era="legacy") + big = _big_initialize("x" * 2048) + with TestClient(http_app) as client: + assert client.post("/mcp", json=big).status_code == 200 + + +def test_json_body_limit_default_rejects_over_1mb(): + app = asyncio.run(_app()) + http_app = build_http_app(app, enable_cors=True, protocol_era="legacy") + big = _big_initialize("x" * (1024 * 1024 + 512)) + with TestClient(http_app) as client: + assert client.post("/mcp", json=big).status_code == 413 + + +@pytest.mark.asyncio +async def test_json_body_limit_chunked_rejects_with_single_413(caplog): + app_calls = 0 + + async def inner_app(scope, receive, send): + nonlocal app_calls + app_calls += 1 + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": b"ok", "more_body": False}) + + limit = 200 + middleware = JsonBodyLimitMiddleware(inner_app, limit_bytes=limit) + body = b"x" * (limit + 50) + chunks = [body[:100], body[100:]] + chunk_index = 0 + + async def receive(): + nonlocal chunk_index + if chunk_index < len(chunks): + message = { + "type": "http.request", + "body": chunks[chunk_index], + "more_body": chunk_index < len(chunks) - 1, + } + chunk_index += 1 + return message + return {"type": "http.disconnect"} + + sent: list[dict[str, Any]] = [] + + async def capture_send(message): + sent.append(message) + + with caplog.at_level("ERROR"): + await middleware(_json_post_scope(), receive, capture_send) + + assert app_calls == 0 + starts = [m for m in sent if m["type"] == "http.response.start"] + assert len(starts) == 1 + assert starts[0]["status"] == 413 + assert not any(record.levelname == "ERROR" for record in caplog.records) + + +@pytest.mark.asyncio +async def test_json_body_limit_chunked_within_limit_reaches_app(): + app_calls = 0 + + async def inner_app(scope, receive, send): + nonlocal app_calls + app_calls += 1 + chunks: list[bytes] = [] + while True: + message = await receive() + assert message["type"] == "http.request" + chunks.append(message.get("body", b"") or b"") + if not message.get("more_body", False): + break + assert json.loads(b"".join(chunks)) == {"ok": True} + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": b"ok", "more_body": False}) + + limit = 512 + middleware = JsonBodyLimitMiddleware(inner_app, limit_bytes=limit) + payload = json.dumps({"ok": True}).encode("utf-8") + chunks = [payload[:20], payload[20:]] + chunk_index = 0 + + async def receive(): + nonlocal chunk_index + if chunk_index < len(chunks): + message = { + "type": "http.request", + "body": chunks[chunk_index], + "more_body": chunk_index < len(chunks) - 1, + } + chunk_index += 1 + return message + return {"type": "http.disconnect"} + + sent: list[dict[str, Any]] = [] + + async def capture_send(message): + sent.append(message) + + content_type = b"application/vnd.api+json; charset=utf-8" + await middleware(_json_post_scope(content_type), receive, capture_send) + + assert app_calls == 1 + starts = [m for m in sent if m["type"] == "http.response.start"] + assert len(starts) == 1 + assert starts[0]["status"] == 200 \ No newline at end of file diff --git a/tests/test_lazy_imports.py b/tests/test_lazy_imports.py new file mode 100644 index 0000000..1203e48 --- /dev/null +++ b/tests/test_lazy_imports.py @@ -0,0 +1,140 @@ +"""Import-time regression: public API and CLI should stay light.""" + +import json +import pkgutil +import subprocess +import sys +import time +from pathlib import Path +from unittest.mock import patch + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +NITROSTACK_ROOT = ROOT / "nitrostack" + + +def _legacy_subpackage_names() -> list[str]: + """Subpackages reachable as ``nitrostack.`` after eager import at 1790572.""" + names = {m.name for m in pkgutil.iter_modules([str(NITROSTACK_ROOT)]) if not m.name.startswith("_")} + for path in NITROSTACK_ROOT.iterdir(): + if path.is_dir() and not path.name.startswith("_") and path.name != "__pycache__": + names.add(path.name) + return sorted(names) + + +def test_import_nitrostack_avoids_heavy_optional_modules(): + script = """ +import sys +import nitrostack +assert nitrostack.__version__ +blocked = ("uvicorn", "cryptography", "quickjs", "posthog") +loaded = [name for name in blocked if name in sys.modules] +assert not loaded, f"eager imports: {loaded}" +print("ok") +""" + result = subprocess.run( + [sys.executable, "-c", script], + cwd=ROOT, + env={**dict(__import__("os").environ), "PYTHONPATH": str(ROOT), "DO_NOT_TRACK": "1"}, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_nitrostack_py_help_starts_quickly(): + cli = ROOT / ".venv" / "bin" / "nitrostack-py" + if not cli.is_file(): + pytest.skip("venv CLI missing") + env = {"DO_NOT_TRACK": "1", **dict(__import__("os").environ)} + for _ in range(2): + subprocess.run( + [str(cli), "--help"], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + timeout=30, + check=True, + ) + started = time.perf_counter() + result = subprocess.run( + [str(cli), "--help"], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + timeout=30, + ) + elapsed_ms = (time.perf_counter() - started) * 1000 + assert result.returncode == 0, result.stderr + assert elapsed_ms < 150, f"--help took {elapsed_ms:.0f} ms" + + +def test_subpackage_attributes_reachable_in_fresh_subprocess(): + subs = _legacy_subpackage_names() + script = f""" +import nitrostack +subs = {json.dumps(subs)} +for name in subs: + mod = getattr(nitrostack, name) + assert mod.__name__ == f"nitrostack.{{name}}", (name, mod) +print("ok") +""" + env = {**dict(__import__("os").environ), "PYTHONPATH": str(ROOT), "DO_NOT_TRACK": "1"} + result = subprocess.run( + [sys.executable, "-c", script], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_lazy_export_patch_roundtrip(): + import nitrostack + + original = nitrostack.tool + with patch("nitrostack.tool", autospec=True) as mocked: + assert nitrostack.tool is mocked + assert nitrostack.tool is original + + +def test_cli_module_entry_help_matches_main(): + env = {**dict(__import__("os").environ), "PYTHONPATH": str(ROOT), "DO_NOT_TRACK": "1"} + cmd_main = [sys.executable, "-m", "nitrostack.cli.main"] + cli = ROOT / ".venv" / "bin" / "nitrostack-py" + if not cli.is_file(): + pytest.skip("venv CLI missing") + for argv_suffix, expect_code in ( + (["--help"], 0), + ([], 1), + (["not-a-real-command"], 2), + ): + main_r = subprocess.run( + [*cmd_main, *argv_suffix], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + timeout=30, + ) + cli_r = subprocess.run( + [str(cli), *argv_suffix], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + timeout=30, + ) + assert main_r.returncode == cli_r.returncode == expect_code, ( + argv_suffix, + main_r.stderr, + cli_r.stderr, + ) + if expect_code == 0: + assert main_r.stdout == cli_r.stdout diff --git a/tests/test_lifecycle_http.py b/tests/test_lifecycle_http.py index c4bb13b..6e3f39d 100644 --- a/tests/test_lifecycle_http.py +++ b/tests/test_lifecycle_http.py @@ -98,7 +98,7 @@ class App: def test_http_guard_pipe_task_progress_and_completion(): - @mcp_app(module=LifecycleModule, server=ServerConfig(name="lifecycle-task", stateless=True)) + @mcp_app(module=LifecycleModule, server=ServerConfig(name="lifecycle-task", stateless=True, protocol_era="legacy")) class App: pass diff --git a/tests/test_list_registration_order.py b/tests/test_list_registration_order.py new file mode 100644 index 0000000..343bde6 --- /dev/null +++ b/tests/test_list_registration_order.py @@ -0,0 +1,146 @@ +"""Regression: tools/resources/prompts list order must not depend on PYTHONHASHSEED.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import textwrap + +_WORKER = textwrap.dedent( + """ + import asyncio + import json + import os + + os.environ.setdefault("DO_NOT_TRACK", "1") + + import mcp.types as types + from pydantic import BaseModel, Field + + from nitrostack import DIContainer, module, prompt, resource, tool + from nitrostack.core.app import McpApplication + + class EchoIn(BaseModel): + value: str = Field(default="x") + + def _provider(mod_idx: int) -> type: + attrs = {} + for ti in range(3): + name = f"tool_{mod_idx}_{ti}" + + def _make_tool(tool_name: str): + @tool(name=tool_name, description="d", input_schema=EchoIn) + async def handler(self, input: EchoIn) -> str: + return input.value + + return handler + + attrs[f"_tool_{ti}"] = _make_tool(name) + return type(f"P{mod_idx}", (), attrs) + + mods = [] + for mi in range(3): + prov = _provider(mi) + + @module(name=f"sub-{mi}", providers=[prov]) + class Sub: + pass + + mods.append(Sub) + + root_attrs = {} + for ri in range(2): + uri = f"bench://r{ri}" + + def _make_res(resource_uri: str, idx: int): + @resource(uri=resource_uri, name=f"res{idx}", description="d") + async def handler(self) -> str: + return "ok" + + return handler + + root_attrs[f"_res_{ri}"] = _make_res(uri, ri) + + for pi in range(2): + pname = f"prompt_{pi}" + + @prompt(name=pname, description="d") + async def ph(self): + return [] + + root_attrs[f"_prompt_{pi}"] = ph + + RootBase = type("RootBase", (), root_attrs) + + @module(name="root", imports=mods, providers=[RootBase]) + class Root: + pass + + DIContainer.reset() + app = McpApplication(Root) + srv = app.mcp_server + + async def listed(): + tools = ( + await srv.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list") + ) + ).root.tools + resources = ( + await srv.request_handlers[types.ListResourcesRequest]( + types.ListResourcesRequest(method="resources/list") + ) + ).root.resources + prompts = ( + await srv.request_handlers[types.ListPromptsRequest]( + types.ListPromptsRequest(method="prompts/list") + ) + ).root.prompts + return { + "tools": [t.name for t in tools], + "resources": [r.uri for r in resources], + "prompts": [p.name for p in prompts], + } + + print(json.dumps(asyncio.run(listed()))) + """ +) + + +def _capture_lists_with_hash_seed(seed: str) -> dict: + env = {**os.environ, "PYTHONHASHSEED": seed, "DO_NOT_TRACK": "1"} + proc = subprocess.run( + [sys.executable, "-c", _WORKER], + env=env, + capture_output=True, + text=True, + check=False, + cwd=os.path.dirname(os.path.dirname(__file__)), + ) + if proc.returncode != 0: + raise AssertionError( + f"worker failed (seed={seed}): stdout={proc.stdout!r} stderr={proc.stderr!r}" + ) + return json.loads(proc.stdout.strip()) + + +def test_list_endpoints_order_independent_of_hash_seed(): + results = [_capture_lists_with_hash_seed(s) for s in ("0", "1", "2")] + assert results[0] == results[1] == results[2] + + +def test_multi_module_tools_follow_import_declaration_order(): + names = _capture_lists_with_hash_seed("0")["tools"] + assert names == [ + "tool_0_0", + "tool_0_1", + "tool_0_2", + "tool_1_0", + "tool_1_1", + "tool_1_2", + "tool_2_0", + "tool_2_1", + "tool_2_2", + ] \ No newline at end of file diff --git a/tests/test_log_emitter.py b/tests/test_log_emitter.py new file mode 100644 index 0000000..b1474aa --- /dev/null +++ b/tests/test_log_emitter.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import logging +import io +import threading + +from nitrostack.core.context import FileLogger +from nitrostack.core.log_emitter import LogEmitter, LogEmitterHandler, log_emitter + + +def _wait_for(event: threading.Event) -> None: + assert event.wait(2), "timed out waiting for log subscriber" + + +def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(): + logger = logging.Logger("nitrostack.test.last-resort") + # Detach from pytest's logging capture handlers so Python's fallback is + # the only possible destination, as it is before any NitroStack handlers + # or subscriptions have been installed. + logger.parent = None + old_last_resort = logging.lastResort + fallback_stream = io.StringIO() + fallback = logging.StreamHandler(fallback_stream) + try: + fallback.setLevel(logging.WARNING) + logging.lastResort = fallback + logger.setLevel(logging.WARNING) + logger.propagate = True + logger.warning("warning before subscription") + assert not any(getattr(handler, "_nitrostack_log_emitter", False) for handler in logger.handlers) + assert "warning before subscription" in fallback_stream.getvalue() + finally: + logging.lastResort = old_last_resort + fallback.close() + + +def test_global_emitter_receives_nitrostack_records_and_extra_fields(): + received = [] + done = threading.Event() + + def collect(record): + received.append(record) + done.set() + + unsubscribe = log_emitter.subscribe(collect) + try: + logging.getLogger("nitrostack.test.emitter").warning( + "hello %s", "tooling", extra={"request_id": "r-1"} + ) + _wait_for(done) + finally: + unsubscribe() + + record = received[0] + assert record.level == "WARNING" + assert record.message == "hello tooling" + assert record.logger_name == "nitrostack.test.emitter" + assert record.extra == {"request_id": "r-1"} + assert record.timestamp.endswith("+00:00") + + +def test_unsubscribe_stops_future_delivery(): + emitter = LogEmitter() + received = [] + ready = threading.Event() + unsubscribe = emitter.subscribe(lambda record: (received.append(record), ready.set())) + logger = logging.getLogger("nitrostack.test.unsubscribe") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + try: + logger.info("before") + _wait_for(ready) + unsubscribe() + logger.info("after") + assert len(received) == 1 + finally: + logger.removeHandler(handler) + + +def test_unsubscribe_waits_for_in_flight_callback(): + emitter = LogEmitter() + entered = threading.Event() + release = threading.Event() + drained = threading.Event() + unsubscribe_returned = threading.Event() + received = [] + + def callback(record): + received.append(record) + entered.set() + release.wait(2) + + unsubscribe = emitter.subscribe(callback) + logger = logging.getLogger("nitrostack.test.unsubscribe-in-flight") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + worker = threading.Thread(target=lambda: logger.info("in flight")) + try: + worker.start() + _wait_for(entered) + + def stop_subscription(): + unsubscribe() + unsubscribe_returned.set() + + stopper = threading.Thread(target=stop_subscription) + stopper.start() + assert not unsubscribe_returned.wait(0.05) + release.set() + _wait_for(unsubscribe_returned) + stopper.join(2) + logger.info("after unsubscribe") + assert len(received) == 1 + finally: + release.set() + worker.join(2) + logger.removeHandler(handler) + + +def test_file_logger_keeps_file_output_and_publishes_to_subscribers(tmp_path): + received = [] + done = threading.Event() + unsubscribe = log_emitter.subscribe(lambda record: (received.append(record), done.set())) + logger = FileLogger(log_file=str(tmp_path / "sdk.log"), name="nitrostack.test.filelogger") + try: + logger.info("through FileLogger", meta={"source": "test"}) + _wait_for(done) + assert "through FileLogger" in (tmp_path / "sdk.log").read_text(encoding="utf-8") + assert received[0].logger_name == "nitrostack.test.filelogger" + assert received[0].extra == {} + assert "meta: {'source': 'test'}" in received[0].message + finally: + unsubscribe() + for handler in list(logger.logger.handlers): + logger.logger.removeHandler(handler) + handler.close() + + +def test_http_logger_with_propagation_disabled_reaches_subscribers(): + from nitrostack.transports.http import _enable_trace_logging, logger as http_logger + + received = [] + done = threading.Event() + unsubscribe = log_emitter.subscribe(lambda record: (received.append(record), done.set())) + old_level = http_logger.level + old_propagate = http_logger.propagate + old_trace_handlers = { + handler + for handler in http_logger.handlers + if getattr(handler, "_nitrostack_trace", False) + } + try: + _enable_trace_logging() + http_logger.info("isolated HTTP logger") + _wait_for(done) + assert received[0].logger_name == "nitrostack.transports.http" + assert received[0].message == "isolated HTTP logger" + finally: + unsubscribe() + http_logger.setLevel(old_level) + http_logger.propagate = old_propagate + for handler in list(http_logger.handlers): + if ( + getattr(handler, "_nitrostack_trace", False) + and handler not in old_trace_handlers + ): + http_logger.removeHandler(handler) + handler.close() + + +def test_http_logger_enabled_before_subscribe_reaches_subscribers(): + from nitrostack.transports.http import _enable_trace_logging, logger as http_logger + + received = [] + done = threading.Event() + old_level = http_logger.level + old_propagate = http_logger.propagate + old_trace_handlers = { + handler + for handler in http_logger.handlers + if getattr(handler, "_nitrostack_trace", False) + } + # Server start order: trace logging is enabled before tooling subscribes. + _enable_trace_logging() + unsubscribe = log_emitter.subscribe(lambda record: (received.append(record), done.set())) + try: + http_logger.info("HTTP record after late subscribe") + _wait_for(done) + assert received[0].logger_name == "nitrostack.transports.http" + assert received[0].message == "HTTP record after late subscribe" + finally: + unsubscribe() + assert not any( + getattr(handler, "_nitrostack_log_emitter", False) + for handler in http_logger.handlers + ) + http_logger.setLevel(old_level) + http_logger.propagate = old_propagate + for handler in list(http_logger.handlers): + if ( + getattr(handler, "_nitrostack_trace", False) + and handler not in old_trace_handlers + ): + http_logger.removeHandler(handler) + handler.close() + + +def test_raising_subscriber_does_not_prevent_another_subscriber(): + emitter = LogEmitter() + received = [] + done = threading.Event() + unsubscribe_raising = emitter.subscribe( + lambda record: (_ for _ in ()).throw(RuntimeError("subscriber failure")) + ) + unsubscribe_healthy = emitter.subscribe(lambda record: (received.append(record), done.set())) + logger = logging.getLogger("nitrostack.test.failure-isolation") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + try: + logger.info("still delivered") + _wait_for(done) + assert received[0].message == "still delivered" + finally: + logger.removeHandler(handler) + unsubscribe_raising() + unsubscribe_healthy() + + +def test_slow_subscriber_has_bounded_buffer_and_keeps_recent_records(): + emitter = LogEmitter(max_buffer=2) + entered = threading.Event() + release = threading.Event() + drained = threading.Event() + received = [] + + def slow(record): + received.append(record.message) + if record.message == "0": + entered.set() + release.wait(2) + if record.message == "5": + drained.set() + + unsubscribe_slow = emitter.subscribe(slow) + logger = logging.getLogger("nitrostack.test.bounded") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + try: + logger.info("0") + _wait_for(entered) + for index in range(1, 5): + logger.info("%s", index) + finished = threading.Event() + + def last_seen(record): + if record.message == "5": + finished.set() + + # A second subscriber provides an asynchronous completion signal. + unsubscribe = emitter.subscribe(last_seen) + logger.info("5") + _wait_for(finished) + release.set() + _wait_for(drained) + unsubscribe() + assert received[0] == "0" + assert received[-2:] == ["4", "5"] + finally: + release.set() + logger.removeHandler(handler) + unsubscribe_slow() diff --git a/tests/test_mcp20_acceptance.py b/tests/test_mcp20_acceptance.py index ffc2cce..ef158fb 100644 --- a/tests/test_mcp20_acceptance.py +++ b/tests/test_mcp20_acceptance.py @@ -3,11 +3,9 @@ from __future__ import annotations import asyncio -import importlib.util import os import sys import time -from pathlib import Path import mcp.types as types import pytest @@ -22,22 +20,8 @@ from nitrostack.core.task import TaskManager, TaskStatus from nitrostack.protocol.constants import LEGACY_SESSION_HEADER from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION -from nitrostack.runtime.acceptance import ( - ACCEPTANCE_CRITERIA, - MCP20_TEST_MODULES, - PROTOCOL_DELIVERABLES, - ProtocolArea, - acceptance_criteria_registered, - deliverables_for_area, - iter_area_summary, - modern_protocol_target, - protocol_coverage_complete, -) -from nitrostack.runtime.conformance import assert_blueprint_layout -REPO_ROOT = Path(__file__).resolve().parents[1] - class EchoInput(BaseModel): value: str = Field(default="") @@ -51,50 +35,6 @@ def teardown_function() -> None: DIContainer.reset() -class TestProtocolRegistry: - def test_all_areas_have_deliverables(self): - assert protocol_coverage_complete() - for line in iter_area_summary(): - assert "0 deliverable" not in line - - def test_deliverable_count(self): - assert len(PROTOCOL_DELIVERABLES) >= 14 - - def test_acceptance_criteria_registered(self): - assert acceptance_criteria_registered() - keys = {item.key for item in ACCEPTANCE_CRITERIA} - assert keys == { - "stateless", - "task_conformance", - "task_cancellation", - "ttl_safety", - "multi_tenant", - "ssrf_security", - "error_parity", - "automated_tests", - } - - def test_modern_protocol_target(self): - assert modern_protocol_target() == "2026-07-28" - - @pytest.mark.parametrize("area", list(ProtocolArea)) - def test_each_area_maps_to_tests(self, area: ProtocolArea): - items = deliverables_for_area(area) - assert items, f"Area {area} has no deliverables" - for item in items: - assert item.test_module.startswith("tests/test_mcp20_") - - -class TestLayoutAndTestTraceability: - def test_all_mcp20_test_modules_exist(self): - for module_path in MCP20_TEST_MODULES: - path = REPO_ROOT / module_path - assert path.is_file(), module_path - - def test_blueprint_layout_importable(self): - assert_blueprint_layout() - - class TestAcceptanceTaskConformance: def test_task_augmented_call_returns_immediately(self): @injectable() @@ -108,7 +48,7 @@ async def fast_task(self, input: EchoInput, context: ExecutionContext) -> str: class TasksModule: pass - @mcp_app(module=TasksModule, server=ServerConfig(name="acceptance-tasks")) + @mcp_app(module=TasksModule, server=ServerConfig(name="acceptance-tasks", protocol_era="legacy")) class TasksApp: pass @@ -151,7 +91,7 @@ async def noop_accept(self, input: EchoInput, context: ExecutionContext) -> str: class CancelModule: pass - @mcp_app(module=CancelModule, server=ServerConfig(name="acceptance-cancel")) + @mcp_app(module=CancelModule, server=ServerConfig(name="acceptance-cancel", protocol_era="legacy")) class CancelApp: pass @@ -208,19 +148,3 @@ def test_server_config_defaults_to_modern_protocol(self): cfg = ServerConfig(name="x") assert cfg.protocol_version == MODERN_PROTOCOL_VERSION - -class TestAutomatedTestCoverageMap: - def test_mcp20_test_modules_importable(self): - for module_path in MCP20_TEST_MODULES: - file_path = REPO_ROOT / module_path - spec = importlib.util.spec_from_file_location( - module_path.replace("/", "_").replace(".", "_"), - file_path, - ) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - - def test_full_mcp20_suite_module_count(self): - suite = sorted(REPO_ROOT.glob("tests/test_mcp20_*.py")) - assert len(suite) == 17 diff --git a/tests/test_mcp20_blueprint.py b/tests/test_mcp20_blueprint.py index ea3b26f..e7d81c2 100644 --- a/tests/test_mcp20_blueprint.py +++ b/tests/test_mcp20_blueprint.py @@ -3,17 +3,15 @@ from __future__ import annotations import asyncio -import json import os import sys from unittest.mock import patch import mcp.types as types import pytest -from nitrostack.runtime.request_ctx import Experimental, RequestContext, RequestParamsMeta, request_ctx +from nitrostack.runtime.request_ctx import Experimental, RequestContext, request_ctx from mcp import MCPError as McpError from pydantic import BaseModel, Field -from starlette.testclient import TestClient sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) @@ -23,29 +21,31 @@ from nitrostack.core.di import DIContainer from nitrostack.core.errors import ResourceNotFoundError, TaskNotFoundError from nitrostack.core.task import TaskManager -from nitrostack.protocol.constants import LEGACY_SESSION_HEADER, MAX_CIMD_BYTES +from nitrostack.protocol.constants import MAX_CIMD_BYTES from nitrostack.protocol.deprecated import deprecated_method_message from nitrostack.protocol.discovery import build_discover_result from nitrostack.protocol.errors import JsonRpcErrorCode from nitrostack.protocol.extensions import MCPExtensionId from nitrostack.protocol.jsonrpc import map_exception_to_jsonrpc from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION -from nitrostack.runtime.conformance import ( - BLUEPRINT_CONFORMANCE_AREAS, - ConformanceArea, - DEPRECATED_MODERN_METHODS, - MODERN_JSONRPC_ERROR_CODES, - REQUIRED_BLUEPRINT_MODULES, - assert_blueprint_layout, - protocol_version_matches_blueprint, - verify_package_layout, -) -from nitrostack.runtime.stateless import assert_stateless_headers +from nitrostack.protocol.method_contract import DEPRECATED_MODERN_METHODS from nitrostack.tasks.eviction import should_evict_terminal_task from nitrostack.tasks.types import TaskAccessContext, TaskEntry, TaskWireData, datetime_to_ms, utc_now from nitrostack.tasks.authorization import check_task_access from nitrostack.transports.cors import cors_preflight_response_headers -from nitrostack.transports.dispatch import IngressContext, StatelessIngressPipeline +from tests.http_probe import decode, http_client, post + + +def test_blueprint_discover_uses_official_http_without_session(): + with http_client("auto") as (app, _, client): + response = post(client, "server/discover") + assert response.status_code == 200, response.text + result = decode(response)["result"] + assert MODERN_PROTOCOL_VERSION in result["supportedVersions"] + assert result["capabilities"]["resources"]["subscribe"] is False + assert result["capabilities"]["tools"]["listChanged"] is True + assert "mcp-session-id" not in response.headers + assert app.mcp_server.get_capabilities().resources.subscribe is False class EchoInput(BaseModel): @@ -63,23 +63,6 @@ def teardown_function() -> None: DIContainer.reset() -class TestBlueprintRegistry: - def test_conformance_areas_defined(self): - assert set(BLUEPRINT_CONFORMANCE_AREAS) == set(ConformanceArea) - assert len(BLUEPRINT_CONFORMANCE_AREAS) == 5 - - def test_modern_protocol_version(self): - assert protocol_version_matches_blueprint() - assert MODERN_PROTOCOL_VERSION == "2026-07-28" - - def test_required_modules_import(self): - assert verify_package_layout() == [] - assert_blueprint_layout() - - def test_blueprint_module_count(self): - assert len(REQUIRED_BLUEPRINT_MODULES) >= 17 - - class TestStatelessHttpConformance: def test_discover_advertises_modern_protocol_and_extensions(self): result = build_discover_result( @@ -94,57 +77,13 @@ def test_discover_advertises_modern_protocol_and_extensions(self): assert isinstance(result["ttlMs"], int) and result["ttlMs"] >= 0 assert result["cacheScope"] in ("public", "private") - def test_stateless_pipeline_handles_discover_without_session(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION), - discover_handler=lambda _req: build_discover_result( - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - ), - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": "d1", "method": "server/discover", "params": {}} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"]["protocolVersion"] == MODERN_PROTOCOL_VERSION - assert_stateless_headers({"Content-Type": "application/json"}) - - asyncio.run(_run()) def test_post_mcp_stateless_no_session_header(self): - @injectable() - class PingController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="BlueprintHttp", controllers=[PingController]) - class HttpModule: - pass - - @mcp_app(module=HttpModule, server=ServerConfig(name="blueprint-http", stateless=True)) - class HttpApp: - pass - - app = asyncio.run(McpApplicationFactory.create(HttpApp)) - http_app = app.get_combined_app(stateless=True, json_response=True) - with TestClient(http_app) as client: - resp = client.post( - "/mcp", - headers={**JSON_HEADERS, "Mcp-Method": "tools/call", "Mcp-Name": "echo"}, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - assert resp.status_code == 200 - assert LEGACY_SESSION_HEADER not in {k.title() for k in resp.headers.keys()} - assert resp.json()["result"]["content"][0]["text"] == "ok" + with http_client("auto") as (_, _, client): + response = post(client, "tools/call", {"name": "echo", "arguments": {"value": "ok"}}) + assert response.status_code == 200, response.text + assert "mcp-session-id" not in response.headers + assert decode(response)["result"]["structuredContent"]["value"] == "ok" def test_cors_preflight_includes_mcp_headers(self): headers = cors_preflight_response_headers({"Origin": "https://app.example.com"}) @@ -156,13 +95,6 @@ def test_cors_preflight_includes_mcp_headers(self): class TestJsonRpcConformance: - @pytest.mark.parametrize( - "code", - sorted(MODERN_JSONRPC_ERROR_CODES), - ) - def test_standard_error_codes_registered(self, code: JsonRpcErrorCode): - assert int(code) in MODERN_JSONRPC_ERROR_CODES - def test_missing_resource_maps_to_invalid_params(self): resp = map_exception_to_jsonrpc(ResourceNotFoundError("mcp://missing"), "99") assert resp["error"]["code"] == JsonRpcErrorCode.INVALID_PARAMS @@ -192,15 +124,10 @@ class JsonRpcApp: async def _run(): app = await McpApplicationFactory.create(JsonRpcApp) - handler = app.mcp_server.request_handlers[types.GetTaskPayloadRequest] - with pytest.raises(McpError) as exc: - await handler( - types.GetTaskPayloadRequest( - method="tasks/result", - params=types.GetTaskPayloadRequestParams(taskId="missing"), - ) - ) - assert exc.value.error.code == types.METHOD_NOT_FOUND + # The 2026 wire has no Tasks surface, so tasks/result has no handler at all + # and the official server answers it as method-not-found. + assert types.GetTaskPayloadRequest not in app.mcp_server.request_handlers + assert app.mcp_server.has_task_support is False asyncio.run(_run()) @@ -217,7 +144,7 @@ async def slow(self, input: EchoInput, context: ExecutionContext) -> str: class TasksModule: pass - @mcp_app(module=TasksModule, server=ServerConfig(name="tasks")) + @mcp_app(module=TasksModule, server=ServerConfig(name="tasks", protocol_era="legacy")) class TasksApp: pass @@ -266,7 +193,7 @@ async def noop_bp(self, input: EchoInput, context: ExecutionContext) -> str: class GetModule: pass - @mcp_app(module=GetModule, server=ServerConfig(name="get")) + @mcp_app(module=GetModule, server=ServerConfig(name="get", protocol_era="legacy")) class GetApp: pass @@ -344,7 +271,7 @@ async def noop_iso(self, input: EchoInput, context: ExecutionContext) -> str: class IsoModule: pass - @mcp_app(module=IsoModule, server=ServerConfig(name="iso")) + @mcp_app(module=IsoModule, server=ServerConfig(name="iso", protocol_era="legacy")) class IsoApp: pass diff --git a/tests/test_mcp20_deprecated.py b/tests/test_mcp20_deprecated.py index e06e5e2..6fda893 100644 --- a/tests/test_mcp20_deprecated.py +++ b/tests/test_mcp20_deprecated.py @@ -1,99 +1,11 @@ -"""Deprecated-method policy is the same on every modern entry point.""" - -from __future__ import annotations - -import asyncio -import json -import os -import sys +"""Retired methods are rejected by the official handler and HTTP transport.""" import mcp.types as types import pytest -from mcp import MCPError as McpError -from pydantic import BaseModel, Field -from starlette.testclient import TestClient -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) - -from nitrostack import ExecutionContext, injectable, module, tool -from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app +from tests.http_probe import decode, http_client, make_app, post from nitrostack.core.di import DIContainer -from nitrostack.protocol.deprecated import ( - DEPRECATED_MODERN_METHODS, - deprecated_method_message, - rejects_deprecated_method, -) -from nitrostack.protocol.errors import JsonRpcErrorCode -from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION -from nitrostack.transports.dispatch import IngressContext, StatelessIngressPipeline -from nitrostack.transports.middleware import StatelessTransportMiddleware - -INITIALIZE_BODY = { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, -} - -JSON_HEADERS = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", -} - - -class EchoInput(BaseModel): - value: str = Field(default="") - - -def setup_function() -> None: - DIContainer.reset() - - -def teardown_function() -> None: - DIContainer.reset() - - -def _pipeline(era: str) -> StatelessIngressPipeline: - wire_mode = "reject" if era == "modern" else "stateless" - return StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode=wire_mode, - protocol_era=era, - ) - ) - - -def _middleware(era: str) -> StatelessTransportMiddleware: - return StatelessTransportMiddleware( - lambda scope, receive, send: None, - pipeline=_pipeline(era), - ) - - -def _echo_http_app(era: str): - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name=f"Deprecated{era.title()}", controllers=[EchoController]) - class EchoModule: - pass - - @mcp_app(module=EchoModule, server=ServerConfig(name=f"deprecated-{era}", protocol_era=era)) - class EchoApp: - pass - - app = asyncio.run(McpApplicationFactory.create(EchoApp)) - return app, app.get_combined_app(json_response=True) +from nitrostack.protocol.deprecated import DEPRECATED_MODERN_METHODS, deprecated_method_message, rejects_deprecated_method def test_initialize_is_not_in_retired_method_table(): @@ -103,204 +15,54 @@ def test_initialize_is_not_in_retired_method_table(): @pytest.mark.parametrize("method", sorted(DEPRECATED_MODERN_METHODS)) -def test_retired_methods_error_only_on_modern(method: str): - assert rejects_deprecated_method(method, "modern") is True - assert rejects_deprecated_method(method, "auto") is False - assert rejects_deprecated_method(method, "legacy") is False - - -@pytest.mark.parametrize("entry", ["pipeline", "replay", "http_post", "http_get"]) -def test_modern_initialize_is_method_not_found_on_every_route(entry: str, monkeypatch): - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) - monkeypatch.delenv("MCP_STATELESS", raising=False) - body = json.dumps(INITIALIZE_BODY).encode() - expected = "Method not found: initialize" - - if entry == "pipeline": - - async def _run(): - status, resp = await _pipeline("modern").handle_post(body, {}) - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - - asyncio.run(_run()) - return - - if entry == "replay": - rejected = _middleware("modern")._reject_replay_headers(body, {}) - assert rejected is not None - status, resp = rejected - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - return - - _, http_app = _echo_http_app("modern") +def test_retired_method_policy(method): + assert rejects_deprecated_method(method, "modern") + assert not rejects_deprecated_method(method, "auto") + assert not rejects_deprecated_method(method, "legacy") + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +@pytest.mark.parametrize("method", ["resources/subscribe", "resources/unsubscribe"]) +@pytest.mark.parametrize("modern", [True, False]) +def test_sessionless_resource_subscriptions_are_rejected(era, method, modern): + with http_client(era) as (_, _, client): + response = post(client, method, {"uri": "probe://info"}, modern=modern, + version="2026-07-28" if modern else "2025-06-18") + assert response.status_code == (404 if modern else 200), response.text + error = decode(response)["error"] + assert error["code"] == (types.METHOD_NOT_FOUND if modern or era == "auto" else -32022) + + +@pytest.mark.parametrize("method", ["resources/subscribe", "resources/unsubscribe"]) +def test_legacy_resource_subscription_compatibility(method): + with http_client("legacy") as (_, _, client): + response = post(client, method, {"uri": "probe://info"}, modern=False, version="2025-06-18") + assert response.status_code == 200, response.text + assert decode(response)["result"] == {} + + +@pytest.mark.parametrize("method", ["tasks/list", "tasks/result", "logging/setLevel"]) +def test_modern_retired_methods_reach_official_dispatch(method): + params = {"tasks/list": {}, "tasks/result": {"taskId": "missing"}, "logging/setLevel": {"level": "info"}}[method] + with http_client("modern") as (_, _, client): + response = post(client, method, params) + assert response.status_code == 404, response.text + assert decode(response)["error"]["code"] == types.METHOD_NOT_FOUND + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_sessionless_official_handler_hides_tasks_list(era): + app = make_app(era) try: - if entry == "http_post": - with TestClient(http_app) as client: - response = client.post("/mcp", headers=JSON_HEADERS, json=INITIALIZE_BODY) - assert response.status_code == 200 - assert response.json()["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert response.json()["error"]["message"] == expected - return - status, payload = asyncio.run( - _asgi_json_get(http_app, {**JSON_HEADERS, "Mcp-Method": "initialize"}) - ) - assert status == 200 - assert payload["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert payload["error"]["message"] == expected + assert types.ListTasksRequest not in app.mcp_server.request_handlers finally: DIContainer.reset() -async def _asgi_json_get(app, headers: dict[str, str]) -> tuple[int, dict]: - status = 0 - chunks: list[bytes] = [] - sent_request = False - finished = asyncio.Event() - - async def receive(): - nonlocal sent_request - if not sent_request: - sent_request = True - return {"type": "http.request", "body": b"", "more_body": False} - await finished.wait() - return {"type": "http.disconnect"} - - async def send(message): - nonlocal status - if message["type"] == "http.response.start": - status = message["status"] - elif message["type"] == "http.response.body": - chunks.append(message.get("body") or b"") - if not message.get("more_body", False): - finished.set() - - scope = { - "type": "http", - "asgi": {"version": "3.0"}, - "http_version": "1.1", - "method": "GET", - "scheme": "http", - "path": "/mcp", - "raw_path": b"/mcp", - "query_string": b"", - "headers": [ - (key.lower().encode("latin-1"), value.encode("latin-1")) - for key, value in headers.items() - ], - "client": ("testclient", 50000), - "server": ("test", 80), - } - - async def _http(): - await app(scope, receive, send) - await asyncio.wait_for(finished.wait(), timeout=2) - return status, json.loads(b"".join(chunks) or b"{}") - - started = asyncio.Event() - messages: asyncio.Queue = asyncio.Queue() - await messages.put({"type": "lifespan.startup"}) - - async def life_receive(): - return await messages.get() - - async def life_send(message): - if message["type"] == "lifespan.startup.complete": - started.set() - - task = asyncio.create_task(app({"type": "lifespan"}, life_receive, life_send)) - await asyncio.wait_for(started.wait(), timeout=2) - try: - return await _http() - finally: - await messages.put({"type": "lifespan.shutdown"}) - await asyncio.wait_for(task, timeout=2) - - -@pytest.mark.parametrize("entry", ["pipeline", "replay", "http_post"]) -def test_auto_initialize_is_not_the_deprecated_error(entry: str, monkeypatch): - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - body = json.dumps(INITIALIZE_BODY).encode() - - if entry == "pipeline": - - async def _run(): - status, resp = await _pipeline("auto").handle_post(body, {}) - assert status == 200 - assert "error" not in resp - assert resp["result"]["protocolVersion"] == "2025-06-18" - - asyncio.run(_run()) - return - - if entry == "replay": - rejected = _middleware("auto")._reject_replay_headers(body, {}) - assert rejected is None - return - - _, http_app = _echo_http_app("auto") - try: - with TestClient(http_app) as client: - response = client.post("/mcp", headers=JSON_HEADERS, json=INITIALIZE_BODY) - assert response.status_code == 200 - payload = response.json() - assert "error" not in payload - assert payload["result"]["protocolVersion"] == "2025-06-18" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -@pytest.mark.parametrize("method", sorted(DEPRECATED_MODERN_METHODS)) -@pytest.mark.parametrize("entry", ["pipeline", "replay"]) -def test_modern_retired_methods_match_on_post_and_replay(method: str, entry: str): - body = json.dumps({"jsonrpc": "2.0", "id": 7, "method": method, "params": {}}).encode() - headers = {"Mcp-Method": method} - expected = deprecated_method_message(method) - - async def _pipeline_reject(): - status, resp = await _pipeline("modern").handle_post(body, headers) - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - - if entry == "pipeline": - asyncio.run(_pipeline_reject()) - return - - rejected = _middleware("modern")._reject_replay_headers(body, headers) - assert rejected is not None - status, resp = rejected - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - - -def test_auto_official_handler_still_lists_tasks(monkeypatch): - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) - monkeypatch.delenv("MCP_STATELESS", raising=False) - app, _ = _echo_http_app("auto") - try: - handler = app.mcp_server.request_handlers[types.ListTasksRequest] - result = asyncio.run(handler(types.ListTasksRequest(method="tasks/list", params={}))) - assert result.tasks == [] - finally: - DIContainer.reset() - - -def test_modern_official_handler_rejects_tasks_list(monkeypatch): - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) - monkeypatch.delenv("MCP_STATELESS", raising=False) - app, _ = _echo_http_app("modern") - try: - handler = app.mcp_server.request_handlers[types.ListTasksRequest] - with pytest.raises(McpError) as exc: - asyncio.run(handler(types.ListTasksRequest(method="tasks/list", params={}))) - assert exc.value.error.code == types.METHOD_NOT_FOUND - assert exc.value.error.message == deprecated_method_message("tasks/list") - finally: - DIContainer.reset() +@pytest.mark.parametrize("era", ["auto", "modern"]) +@pytest.mark.parametrize("method", ["tasks/list", "tasks/get", "tasks/result", "tasks/cancel", "tasks/update"]) +def test_sessionless_http_hides_task_methods(era, method): + with http_client(era) as (_, _, client): + response = post(client, method, {"taskId": "missing"} if method != "tasks/list" else {}) + assert response.status_code == 404, response.text + assert decode(response)["error"]["code"] == types.METHOD_NOT_FOUND diff --git a/tests/test_mcp20_foundation.py b/tests/test_mcp20_foundation.py index 9d57c28..4299400 100644 --- a/tests/test_mcp20_foundation.py +++ b/tests/test_mcp20_foundation.py @@ -9,7 +9,6 @@ MAX_SCHEMA_DEPTH, ) from nitrostack.protocol.extensions import MCPExtensionId -from nitrostack.protocol.layers import RuntimeLayer from nitrostack.protocol.version import ( LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION, @@ -84,17 +83,6 @@ def test_legacy_session_header_name(self): assert LEGACY_SESSION_HEADER == "Mcp-Session-Id" -class TestRuntimeLayers: - def test_all_architecture_layers_defined(self): - layers = {layer.value for layer in RuntimeLayer} - assert layers == { - "transport_security", - "protocol_dispatcher", - "registries", - "task_management", - } - - class TestExtensions: def test_canonical_extension_ids(self): assert MCPExtensionId.APP.value == "io.modelcontextprotocol/app" diff --git a/tests/test_mcp20_jsonrpc_wire.py b/tests/test_mcp20_jsonrpc_wire.py index 89e81aa..3c849aa 100644 --- a/tests/test_mcp20_jsonrpc_wire.py +++ b/tests/test_mcp20_jsonrpc_wire.py @@ -1,6 +1,5 @@ """Tests for MCP 2.0 JSON-RPC wire specification.""" -import asyncio import json import pytest @@ -18,9 +17,6 @@ build_tool_error_result, map_exception_to_jsonrpc, parse_jsonrpc_request, - validate_header_body_name, - validate_header_body_method, - validate_required_mcp_name, ) from nitrostack.core.context import AuthContext, ExecutionContext from nitrostack.protocol.meta import ( @@ -31,7 +27,45 @@ split_params_and_meta, ) from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION -from nitrostack.transports.dispatch import IngressContext, StatelessIngressPipeline +from tests.http_probe import decode, http_client, post + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_official_http_rejects_unknown_protocol_header(era): + with http_client(era) as (_, _, client): + response = post(client, version="1999-01-01") + assert response.status_code == 400, response.text + assert "result" not in decode(response) + + +@pytest.mark.parametrize("era,version", [ + ("auto", "2025-06-18"), ("auto", "2025-11-25"), ("auto", "2026-07-28"), + ("modern", "2026-07-28"), +]) +def test_official_http_accepts_supported_protocol(era, version): + with http_client(era) as (_, _, client): + response = post(client, modern=version == MODERN_PROTOCOL_VERSION, version=version) + assert response.status_code == 200, response.text + assert decode(response)["result"]["tools"][0]["name"] == "echo" + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +@pytest.mark.parametrize("wrong_header", [{"Mcp-Method": "tools/list"}, {"Mcp-Name": "wrong"}]) +def test_official_http_checks_method_and_name_headers(era, wrong_header): + with http_client(era) as (_, _, client): + response = post(client, "tools/call", {"name": "echo", "arguments": {}}, + extra_headers=wrong_header) + assert response.status_code == 400, response.text + assert decode(response)["error"]["code"] == HEADER_BODY_MISMATCH + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_protocol_header_and_envelope_must_agree_in_official_runner(era): + with http_client(era) as (_, _, client): + response = post(client, extra_headers={"MCP-Protocol-Version": "2025-06-18"}) + # The 2025 header selects the SDK's legacy HTTP error mapping. + assert response.status_code == 200, response.text + assert decode(response)["error"]["code"] == HEADER_BODY_MISMATCH class TestErrorCodes: @@ -196,51 +230,6 @@ def test_apply_request_envelope_sets_verified_jwt_user(self): class TestHeaderBodyMismatch: - def test_mcp_method_mismatch(self): - with pytest.raises(HeaderBodyMismatchError) as exc: - validate_header_body_method("tools/list", "tools/call") - assert int(exc.value.code) == HEADER_BODY_MISMATCH - - def test_mcp_name_mismatch(self): - with pytest.raises(HeaderBodyMismatchError): - validate_header_body_name("get_weather", "get_forecast") - - def test_optional_name_allows_missing_header(self): - validate_header_body_name(None, "echo") - - def test_required_mcp_name_rejects_missing_header(self): - with pytest.raises(HeaderBodyMismatchError) as exc: - validate_required_mcp_name(None, "echo") - assert int(exc.value.code) == HEADER_BODY_MISMATCH - assert "required" in exc.value.message - - def test_required_mcp_name_rejects_mismatch(self): - with pytest.raises(HeaderBodyMismatchError) as exc: - validate_required_mcp_name("foo", "bar") - assert int(exc.value.code) == HEADER_BODY_MISMATCH - - def test_required_mcp_name_accepts_exact_match(self): - validate_required_mcp_name("echo", "echo") - - def test_required_mcp_method_rejects_missing_header(self): - from nitrostack.protocol.jsonrpc import validate_required_mcp_method - - with pytest.raises(HeaderBodyMismatchError) as exc: - validate_required_mcp_method(None, "tools/call") - assert int(exc.value.code) == HEADER_BODY_MISMATCH - assert "required" in exc.value.message - - def test_required_mcp_method_rejects_mismatch(self): - from nitrostack.protocol.jsonrpc import validate_required_mcp_method - - with pytest.raises(HeaderBodyMismatchError): - validate_required_mcp_method("tools/list", "tools/call") - - def test_required_mcp_method_accepts_exact_match(self): - from nitrostack.protocol.jsonrpc import validate_required_mcp_method - - validate_required_mcp_method("tools/call", "tools/call") - def test_protocol_version_header_meta_mismatch(self): from nitrostack.protocol.jsonrpc import validate_protocol_version_header_meta @@ -255,62 +244,6 @@ def test_protocol_version_header_only_is_allowed(self): validate_protocol_version_header_meta(None, "2025-06-18") validate_protocol_version_header_meta("2026-07-28", "2026-07-28") - def test_pipeline_rejects_header_and_meta_mismatch(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "ping", - "params": {"_meta": {"mcp": {"protocolVersion": "2025-06-18"}}}, - } - ).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - assert status == 400 - assert resp["error"]["code"] == HEADER_BODY_MISMATCH - - asyncio.run(_run()) - - def test_pipeline_header_only_proceeds(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_pipeline_ignores_unrelated_meta_keys(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "ping", - "params": {"_meta": {"trace": {"id": "span"}, "userId": "eve"}}, - } - ).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - class TestUnsupportedProtocolVersion: def test_unknown_header_is_rejected(self): @@ -325,76 +258,6 @@ def test_unknown_header_is_rejected(self): assert int(exc.value.code) == UNSUPPORTED_PROTOCOL_VERSION assert str(exc.value) == "Unsupported protocol version" - def test_pipeline_rejects_unknown_header(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "1999-01-01"} - ) - assert status == 400 - assert resp["error"]["code"] == -32022 - assert resp["error"]["message"] == "Unsupported protocol version" - - asyncio.run(_run()) - - def test_pipeline_accepts_supported_header(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - modern, modern_resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - legacy, legacy_resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2025-06-18"} - ) - absent, absent_resp = await pipeline.handle_post(body, {}) - assert modern == 200 - assert modern_resp["result"] == {} - assert legacy == 200 - assert legacy_resp["result"] == {} - assert absent == 200 - assert absent_resp["result"] == {} - - asyncio.run(_run()) - - def test_pipeline_rejects_envelope_only_unknown_version(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "ping", - "params": {"_meta": {"mcp": {"protocolVersion": "1999-01-01"}}}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - - def test_modern_rejects_legacy_dated_header(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2025-06-18", "Mcp-Method": "ping"} - ) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - class TestToolVsProtocolErrors: def test_tool_error_result_uses_is_error_flag(self): @@ -419,49 +282,11 @@ def test_tool_execution_error_maps_to_result_not_rpc_error(self): class TestDeprecatedMethods: @pytest.mark.parametrize( "method", - ["tasks/result", "tasks/list", "resources/subscribe", "logging/setLevel"], + ["resources/subscribe", "logging/setLevel"], ) def test_deprecated_methods_have_messages(self, method): assert deprecated_method_message(method) is not None - def test_pipeline_rejects_tasks_list(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="reject", - protocol_era="modern", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": "tasks/list", "params": {}} - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "tasks/list"}) - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - - asyncio.run(_run()) - - def test_pipeline_auto_forwards_tasks_list(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - protocol_era="auto", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": "tasks/list", "params": {}} - ).encode() - assert await pipeline.handle_post(body, {"Mcp-Method": "tasks/list"}) is None - - asyncio.run(_run()) - class TestJsonRpcParseErrors: def test_invalid_json(self): diff --git a/tests/test_mcp20_oauth_cimd.py b/tests/test_mcp20_oauth_cimd.py index b269faa..fc72ce0 100644 --- a/tests/test_mcp20_oauth_cimd.py +++ b/tests/test_mcp20_oauth_cimd.py @@ -176,9 +176,10 @@ def test_direct_peer_must_match_pin(self, monkeypatch): assert cimd_peer_is_acceptable("8.8.8.8", "8.8.8.8") is True assert cimd_peer_is_acceptable("1.2.3.4", "8.8.8.8") is False - def test_trusted_proxy_peer_is_acceptable(self, monkeypatch): + def test_trusted_proxy_peer_is_not_acceptable_for_outbound(self, monkeypatch): monkeypatch.setenv("TRUSTED_PROXIES", "10.0.0.5") - assert cimd_peer_is_acceptable("10.0.0.5", "8.8.8.8") is True + # Trusted proxies apply to inbound headers, NOT outbound socket fetch pins. + assert cimd_peer_is_acceptable("10.0.0.5", "8.8.8.8") is False assert cimd_peer_is_acceptable("10.0.0.9", "8.8.8.8") is False def test_untrusted_forwarded_host_cannot_rebind_cimd(self, monkeypatch): @@ -191,7 +192,7 @@ def test_untrusted_forwarded_host_cannot_rebind_cimd(self, monkeypatch): assert request_host_for_cimd(headers, peer="8.8.8.8") == "mcp.nitrostack.io" assert cimd_host_matches_request(url, headers, peer="8.8.8.8") is False - def test_apply_cimd_records_untrusted_request_host(self, monkeypatch): + def test_apply_cimd_denies_untrusted_request_host_mismatch(self, monkeypatch): monkeypatch.delenv("TRUSTED_PROXIES", raising=False) url = "https://app.nitrostack.io/oauth/client-metadata.json" headers = { @@ -202,13 +203,13 @@ def test_apply_cimd_records_untrusted_request_host(self, monkeypatch): "nitrostack.auth.oauth_module.resolve_cimd_sync", return_value={"client_id": url, "client_name": "Studio"}, ): - body = apply_cimd_to_registration_body( - {"client_id": url}, - headers=headers, - peer="8.8.8.8", - ) - assert body["_cimd_request_host"] == "mcp.nitrostack.io" - assert body["_cimd_host_matches_request"] is False + with pytest.raises(CimdValidationError) as exc_info: + apply_cimd_to_registration_body( + {"client_id": url}, + headers=headers, + peer="8.8.8.8", + ) + assert "host" in str(exc_info.value).lower() def test_apply_cimd_honors_trusted_forwarded_host(self, monkeypatch): monkeypatch.setenv("TRUSTED_PROXIES", "10.0.0.5") @@ -229,6 +230,12 @@ def test_apply_cimd_honors_trusted_forwarded_host(self, monkeypatch): assert body["_cimd_request_host"] == "app.nitrostack.io" assert body["_cimd_host_matches_request"] is True + def test_cimd_helpers_defined_once(self): + from pathlib import Path + source = Path("nitrostack/auth/cimd.py").read_text(encoding="utf-8") + assert source.count("def looks_like_cimd_url") == 1 + assert source.count("def resolve_cimd_sync") == 1 + class TestCimdRegistrationWiring: def test_applies_cimd_document_to_registration_body(self): @@ -266,3 +273,44 @@ def test_rejects_missing_iss(self): def test_rejects_mismatched_iss(self): with pytest.raises(AuthorizationIssuerMismatchError, match="mismatch"): validate_authorization_iss("https://evil.example", "https://auth.nitrostack.io") + + +class TestVerifyBearerPayload: + def test_returns_payload_for_valid_token(self): + from nitrostack.auth.jwt import JWTService + from nitrostack.auth.request import verify_bearer_payload + from nitrostack.core.di import DIContainer + + DIContainer.reset() + service = JWTService() + DIContainer.get_instance().register_value(JWTService, service) + token = service.create_token({"sub": "user_123", "tenant_id": "org_abc"}) + payload = verify_bearer_payload(token) + assert payload is not None + assert payload["sub"] == "user_123" + assert payload["tenant_id"] == "org_abc" + + def test_returns_none_for_invalid_token(self): + from nitrostack.auth.jwt import JWTService + from nitrostack.auth.request import verify_bearer_payload + from nitrostack.core.di import DIContainer + + DIContainer.reset() + service = JWTService() + DIContainer.get_instance().register_value(JWTService, service) + assert verify_bearer_payload("invalid.token.structure") is None + assert verify_bearer_payload("not-a-jwt") is None + + def test_raises_on_di_misconfig(self): + from nitrostack.auth.request import verify_bearer_payload + from nitrostack.core.di import DIContainer + from nitrostack.core.errors import DependencyResolutionError + + DIContainer.reset() + with patch.object( + DIContainer.get_instance(), + "resolve", + side_effect=DependencyResolutionError("JWTService missing"), + ): + with pytest.raises(DependencyResolutionError): + verify_bearer_payload("header.payload.signature") diff --git a/tests/test_mcp20_stateless_http.py b/tests/test_mcp20_stateless_http.py index 5cb3c00..169b61c 100644 --- a/tests/test_mcp20_stateless_http.py +++ b/tests/test_mcp20_stateless_http.py @@ -1,35 +1,21 @@ """Tests for MCP 2.0 stateless HTTP transport.""" -import asyncio import json import pytest from nitrostack.protocol.constants import LEGACY_SESSION_HEADER from nitrostack.protocol.contracts import MCP_CACHE_HINT_KEY -from nitrostack.protocol.discovery import DISCOVER_RESULT_TYPE, SERVER_DISCOVER_METHOD, build_discover_result +from nitrostack.protocol.discovery import DISCOVER_RESULT_TYPE, build_discover_result from nitrostack.protocol.jsonrpc import ( HEADER_BODY_MISMATCH, PARSE_ERROR, HeaderBodyMismatchError, JsonRpcParseError, - build_ping_response, parse_jsonrpc_request, - validate_header_body_method, -) -from nitrostack.protocol.method_contract import ( - MODERN_METHOD_CONTRACTS, - mcp_name_field, - mcp_name_is_required, ) from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION from nitrostack.transports.cors import build_cors_headers, cors_preflight_response_headers, resolve_allowed_origin -from nitrostack.transports.dispatch import ( - IngressContext, - StatelessIngressPipeline, - is_header_only_ping, - is_task_wire_interception, -) from nitrostack.transports.headers import ( MAX_MCP_PARAM_VALUE_BYTES, build_mcp_echo_headers, @@ -46,6 +32,120 @@ strip_legacy_session_headers_asgi, ) from nitrostack.transports.sse import format_sse_message, sse_notification +from tests.http_probe import decode, envelope, headers, http_client, post + + +@pytest.mark.parametrize("era", ["legacy", "auto", "modern"]) +@pytest.mark.parametrize("json_response", [True, False]) +def test_official_transport_tool_and_resource_roundtrip(era, json_response): + version = "2025-06-18" if era == "legacy" else MODERN_PROTOCOL_VERSION + with http_client(era, json_response=json_response) as (_, http, client): + assert http.state.streamable_http_manager_count == 1 + assert http.state.sessionful == (era == "legacy") + response = post(client, "tools/call", {"name": "echo", "arguments": {"value": "wire"}}, + modern=era != "legacy", version=version) + assert response.status_code == 200, response.text + assert decode(response)["result"]["structuredContent"]["value"] == "wire" + response = post(client, "resources/read", {"uri": "probe://info"}, + modern=era != "legacy", version=version) + assert response.status_code == 200, response.text + assert decode(response)["result"]["contents"][0]["text"] == "probe resource" + if era != "legacy": + assert "mcp-session-id" not in response.headers + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +@pytest.mark.parametrize("body", [b"", b"not-json", b"{}"]) +def test_header_only_ping_cannot_synthesize_a_success(era, body): + with http_client(era) as (_, _, client): + response = client.post("/mcp", content=body, headers=headers("ping")) + assert response.status_code == 400, response.text + assert "result" not in decode(response) + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_unknown_method_is_answered_by_official_dispatch(era): + with http_client(era) as (_, _, client): + response = post(client, "unknown/probe") + assert response.status_code == 404, response.text + assert decode(response)["error"]["code"] == -32601 + + +@pytest.mark.parametrize("era", ["legacy", "auto", "modern"]) +def test_http_health_version_slash_and_era(era): + with http_client(era) as (_, http, client): + health = client.get("/mcp/health") + assert health.status_code == 200 + assert http.state.protocol_era == era + version = client.get("/json/version").json()["Protocol-Version"] + assert version == ("2025-06-18" if era == "legacy" else MODERN_PROTOCOL_VERSION) + response = client.post("/mcp/", json=envelope(), headers=headers()) + if era != "legacy": + assert response.status_code == 200, response.text + assert decode(response)["result"]["tools"][0]["name"] == "echo" + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_allowlisted_cors_applies_once_to_success_and_errors(era, monkeypatch): + monkeypatch.setenv("MCP_CORS_ALLOWED_ORIGINS", "https://allowed.example") + with http_client(era) as (_, _, client): + for method in ["tools/list", "unknown/probe"]: + response = post(client, method, extra_headers={"Origin": "https://allowed.example"}) + assert response.headers.get_list("access-control-allow-origin") == ["https://allowed.example"] + denied = post(client, extra_headers={"Origin": "https://denied.example"}) + assert "access-control-allow-origin" not in denied.headers + preflight = client.options("/mcp", headers={"Origin": "https://allowed.example", + "Access-Control-Request-Method": "POST"}) + assert preflight.status_code == 200 + assert preflight.headers.get_list("access-control-allow-origin") == ["https://allowed.example"] + + +def test_verified_http_identity_and_argument_header_mirroring(): + from nitrostack.auth.jwt import JWTService + from nitrostack.core.di import DIContainer + + with http_client("auto") as (_, _, client): + jwt = JWTService() + DIContainer.get_instance().register_value(JWTService, jwt) + token = jwt.create_token({"sub": "alice", "tenant_id": "one"}) + response = post(client, "tools/call", { + "name": "echo", "arguments": {}, "_meta": {"userId": "mallory"}, + }, extra_headers={"Authorization": "Bearer " + token, "Mcp-Param-value": "from-header"}) + result = decode(response)["result"]["structuredContent"] + assert result["value"] == "from-header" + assert result["mirrored"] == {"value": "from-header"} + assert result["user"] == "alice" + assert result["protocol_version"] == MODERN_PROTOCOL_VERSION + kept = post(client, "tools/call", {"name": "echo", "arguments": {"value": "from-body"}}, + extra_headers={"Mcp-Param-value": "from-header"}) + assert decode(kept)["result"]["structuredContent"]["value"] == "from-body" + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_incoming_session_id_cannot_attach_sessionless_calls(era): + with http_client(era) as (_, _, client): + first = post(client, "tools/call", {"name": "echo", "arguments": {"value": "first"}}, + extra_headers={"Mcp-Session-Id": "forged"}) + second = post(client, "tools/call", {"name": "echo", "arguments": {"value": "second"}}, + extra_headers={"Mcp-Session-Id": "forged"}) + for response, expected in [(first, "first"), (second, "second")]: + assert response.status_code == 200, response.text + assert "mcp-session-id" not in response.headers + assert decode(response)["result"]["structuredContent"]["value"] == expected + + +def test_response_echo_uses_supported_request_version(): + echoed = build_mcp_echo_headers( + {"MCP-Protocol-Version": "2025-06-18", "Mcp-Method": "tools/call"}, + protocol_version=MODERN_PROTOCOL_VERSION, + supported_versions={MODERN_PROTOCOL_VERSION, "2025-06-18"}, + ) + assert echoed["MCP-Protocol-Version"] == "2025-06-18" + assert echoed["Mcp-Method"] == "tools/call" + assert handled_protocol_version( + {"MCP-Protocol-Version": "1999-01-01"}, fallback=MODERN_PROTOCOL_VERSION, + supported={MODERN_PROTOCOL_VERSION, "2025-06-18"}, + ) == MODERN_PROTOCOL_VERSION class TestRequestHeaders: @@ -218,128 +318,6 @@ def test_oversized_param_is_detected(self): assert first_oversized_mcp_param({"Mcp-Param-City": huge}) == "City" assert first_oversized_mcp_param({"Mcp-Param-City": "Boston"}) is None - def test_pipeline_name_check_uses_body_not_mirrored_params(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {}}, - } - ).encode() - result = await pipeline.handle_post( - body, - { - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - "Mcp-Param-Name": "other", - }, - ) - assert result is None - - asyncio.run(_run()) - - def test_pipeline_rejects_oversized_param(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, - {"Mcp-Param-City": "x" * (MAX_MCP_PARAM_VALUE_BYTES + 1)}, - ) - assert status == 400 - assert resp["error"]["code"] == -32600 - - asyncio.run(_run()) - - def test_http_header_fills_missing_tool_argument(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> dict: - return { - "value": input.value, - "mirrored": context.mcp_param_headers, - } - - @module(name="McpParamHttp", controllers=[EchoController]) - class McpParamModule: - pass - - @mcp_app(module=McpParamModule, server=ServerConfig(name="mcp-param-http")) - class McpParamApp: - pass - - app = asyncio.run(McpApplicationFactory.create(McpParamApp)) - http_app = app.get_combined_app(json_response=True) - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - "MCP-Protocol-Version": "2025-06-18", - } - with TestClient(http_app) as client: - filled = client.post( - "/mcp", - headers={**json_headers, "Mcp-Param-value": "from-header"}, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {}}, - }, - ) - kept = client.post( - "/mcp", - headers={**json_headers, "Mcp-Param-value": "from-header"}, - json={ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "from-body"}}, - }, - ) - assert filled.status_code == 200, filled.text - filled_body = filled.json()["result"] - filled_payload = filled_body.get("structuredContent") or json.loads( - filled_body["content"][0]["text"] - ) - assert filled_payload["value"] == "from-header" - assert filled_payload["mirrored"]["value"] == "from-header" - assert kept.status_code == 200, kept.text - kept_body = kept.json()["result"] - kept_payload = kept_body.get("structuredContent") or json.loads( - kept_body["content"][0]["text"] - ) - assert kept_payload["value"] == "from-body" - assert kept_payload["mirrored"]["value"] == "from-header" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - class TestCors: def test_cors_allow_methods(self): @@ -395,35 +373,6 @@ def test_parse_invalid_json(self): parse_jsonrpc_request(b"{bad") assert exc.value.code == PARSE_ERROR - def test_header_body_mismatch(self): - with pytest.raises(HeaderBodyMismatchError) as exc: - validate_header_body_method("tools/list", "tools/call") - assert exc.value.code == HEADER_BODY_MISMATCH - - -class TestPingFastPath: - def test_ping_response(self): - resp = build_ping_response("ping-1") - assert resp == {"jsonrpc": "2.0", "id": "ping-1", "result": {}} - - def test_header_only_ping_empty_or_non_jsonrpc_body(self): - headers = {"Mcp-Method": "ping"} - assert is_header_only_ping(b"", headers) is True - assert is_header_only_ping(b" \n", headers) is True - assert is_header_only_ping(b"not-json", headers) is True - assert is_header_only_ping(b"{}", headers) is True - - def test_header_only_ping_does_not_apply_to_other_methods(self): - assert is_header_only_ping(b"", {"Mcp-Method": "tools/call"}) is False - assert is_header_only_ping(b"", {}) is False - - def test_parsed_jsonrpc_body_is_not_header_only(self): - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - assert is_header_only_ping(body, {"Mcp-Method": "ping"}) is False - call = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "echo"}} - ).encode() - assert is_header_only_ping(call, {"Mcp-Method": "ping"}) is False class TestDiscovery: @@ -436,7 +385,7 @@ def test_discover_result_shape(self): assert result["supportedVersions"] == ["2026-07-28"] assert result["serverInfo"]["name"] == "my-stateless-mcp-server" assert result["capabilities"]["resources"]["subscribe"] is False - assert "io.modelcontextprotocol/tasks" in result["capabilities"]["extensions"] + assert "io.modelcontextprotocol/tasks" not in result["capabilities"].get("extensions", {}) assert result["resultType"] == DISCOVER_RESULT_TYPE assert isinstance(result["ttlMs"], int) and result["ttlMs"] >= 0 assert result["cacheScope"] in ("public", "private") @@ -444,362 +393,6 @@ def test_discover_result_shape(self): assert result["_meta"][MCP_CACHE_HINT_KEY]["cacheScope"] == result["cacheScope"] -class TestDispatchPipeline: - def test_handles_ping(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps({"jsonrpc": "2.0", "id": 9, "method": "ping"}).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_header_only_ping_empty_body(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - status, resp = await pipeline.handle_post(b"", {"Mcp-Method": "ping"}) - assert status == 200 - assert resp == {"jsonrpc": "2.0", "id": None, "result": {}} - assert "error" not in resp - - asyncio.run(_run()) - - def test_header_only_ping_non_jsonrpc_body(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - status, resp = await pipeline.handle_post(b"not-json", {"Mcp-Method": "ping"}) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_empty_body_without_ping_header_is_parse_error(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - status, resp = await pipeline.handle_post(b"", {"Mcp-Method": "tools/call"}) - assert status == 400 - assert resp["error"]["code"] == PARSE_ERROR - - asyncio.run(_run()) - - def test_tools_call_body_with_ping_header_is_mismatch(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "ping"}) - assert status == 400 - assert resp["error"]["code"] == HEADER_BODY_MISMATCH - - asyncio.run(_run()) - - def test_forwards_server_discover_to_engine_handler(self): - async def _run(): - payload = build_discover_result( - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - ) - - def _discover(_request): - return payload - - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION), - discover_handler=_discover, - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": "req-001", "method": SERVER_DISCOVER_METHOD, "params": {}} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - result = resp["result"] - assert result == payload - assert result["protocolVersion"] == "2026-07-28" - assert result["resultType"] == DISCOVER_RESULT_TYPE - assert MODERN_PROTOCOL_VERSION in result["supportedVersions"] - - asyncio.run(_run()) - - def test_server_discover_without_engine_handler_is_not_answered(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": "req-001", "method": SERVER_DISCOVER_METHOD, "params": {}} - ).encode() - assert await pipeline.handle_post(body, {}) is None - - asyncio.run(_run()) - - def test_passes_through_tools_call(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo"}, - } - ).encode() - assert await pipeline.handle_post( - body, {"Mcp-Name": "demo", "Mcp-Method": "tools/call"} - ) is None - - asyncio.run(_run()) - - def test_tools_call_requires_mcp_name(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject" - ) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo"}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "tools/call"}) - assert status == 400 - assert resp["error"]["code"] == -32020 - assert "Mcp-Name" in resp["error"]["message"] - - asyncio.run(_run()) - - def test_tools_call_rejects_mcp_name_mismatch(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "bar"}, - } - ).encode() - status, resp = await pipeline.handle_post( - body, {"Mcp-Name": "foo", "Mcp-Method": "tools/call"} - ) - assert status == 400 - assert resp["error"]["code"] == -32020 - assert "foo" in resp["error"]["message"] - assert "bar" in resp["error"]["message"] - - asyncio.run(_run()) - - def test_ping_does_not_require_mcp_name(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps({"jsonrpc": "2.0", "id": 9, "method": "ping"}).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_modern_reject_initialize(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2026-07-28", - "capabilities": {}, - "clientInfo": {"name": "t", "version": "1"}, - }, - } - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "initialize"}) - assert status == 200 - assert resp["error"]["code"] == -32601 - assert resp["error"]["message"] == "Method not found: initialize" - - asyncio.run(_run()) - - def test_modern_reject_initialized(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="reject", - protocol_era="modern", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "method": "notifications/initialized"} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["error"]["code"] == -32601 - assert resp["error"]["message"] == "Method not found: notifications/initialized" - - asyncio.run(_run()) - - def test_modern_reject_legacy_protocol_version(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 2, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2025-06-18", "Mcp-Method": "ping"} - ) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - - def test_modern_ignores_incoming_session_id(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 3, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {LEGACY_SESSION_HEADER: "session-1", "Mcp-Method": "ping"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_auto_ignores_incoming_session_id(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 4, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, - {LEGACY_SESSION_HEADER: "session-1", "Mcp-Method": "ping"}, - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_legacy_sessionful_pipeline_keeps_session_id(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="sessionful") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 5, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {LEGACY_SESSION_HEADER: "session-1"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_auto_accepts_initialize(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": {"protocolVersion": "2025-06-18", "capabilities": {}}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - result = resp["result"] - assert result["protocolVersion"] == "2025-06-18" - assert result["serverInfo"]["name"] == "srv" - assert "capabilities" in result - - asyncio.run(_run()) - - def test_auto_acks_initialized_without_forwarding(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - protocol_era="auto", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "method": "notifications/initialized"} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 202 - assert resp == {} - - asyncio.run(_run()) - - def test_legacy_sessionful_pipeline_forwards_initialized(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="sessionful", - protocol_era="legacy", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "method": "notifications/initialized"} - ).encode() - assert await pipeline.handle_post(body, {}) is None - - asyncio.run(_run()) - - -class TestTaskInterceptionDetection: - def test_tasks_method_prefix(self): - assert is_task_wire_interception("tasks/get", {"taskId": "x"}) - - def test_tools_call_with_task_param(self): - assert is_task_wire_interception("tools/call", {"name": "x", "task": {"ttl": 1000}}) - - def test_sync_tools_call_not_intercepted(self): - assert not is_task_wire_interception("tools/call", {"name": "x"}) - - class TestSse: def test_sse_stream_headers_disable_buffering(self): headers = build_sse_stream_headers() @@ -818,2512 +411,3 @@ def test_sse_task_status_notification(self): {"method": "notifications/tasks/status", "params": {"taskId": "abc"}} ) assert b"notifications/tasks/status" in frame - - -class TestReplayDoesNotSynthesizeDisconnect: - def test_waits_for_real_disconnect(self): - from nitrostack.transports.middleware import StatelessTransportMiddleware - - calls = {"n": 0} - - async def original_receive(): - calls["n"] += 1 - return {"type": "http.disconnect"} - - replay = StatelessTransportMiddleware._replay_receive(b"{}", original_receive) - - async def _run(): - first = await replay() - assert first == {"type": "http.request", "body": b"{}", "more_body": False} - assert calls["n"] == 0 - second = await replay() - assert second == {"type": "http.disconnect"} - assert calls["n"] == 1 - - asyncio.run(_run()) - - -class TestReplayUsesHeaderSnapshot: - def test_tools_call_replay_keeps_name_and_method(self): - from starlette.testclient import TestClient - - from nitrostack.transports.middleware import wrap_stateless_transport - - captured: dict[str, list] = {} - - async def inner(scope, receive, send): - if scope["type"] == "lifespan": - while True: - message = await receive() - if message["type"] == "lifespan.startup": - await send({"type": "lifespan.startup.complete"}) - elif message["type"] == "lifespan.shutdown": - await send({"type": "lifespan.shutdown.complete"}) - return - captured["headers"] = list(scope.get("headers") or []) - await receive() - await send( - { - "type": "http.response.start", - "status": 200, - "headers": [(b"content-type", b"application/json")], - } - ) - await send( - { - "type": "http.response.body", - "body": b'{"jsonrpc":"2.0","id":1,"result":{}}', - } - ) - - wrapped = wrap_stateless_transport( - inner, - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - ) - with TestClient(wrapped) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - "MCP-Protocol-Version": "2026-07-28", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - }, - ) - assert response.status_code == 200 - forwarded = {key.lower(): value for key, value in captured["headers"]} - assert forwarded.get(b"mcp-method") == b"tools/call" - assert forwarded.get(b"mcp-name") == b"echo" - assert forwarded.get(b"mcp-protocol-version") == b"2026-07-28" - assert b"mcp-session-id" not in forwarded - - def test_session_id_is_rejected_before_replay(self): - from starlette.testclient import TestClient - - from nitrostack.transports.middleware import wrap_stateless_transport - - called = {"inner": False} - - async def inner(scope, receive, send): - if scope["type"] == "lifespan": - while True: - message = await receive() - if message["type"] == "lifespan.startup": - await send({"type": "lifespan.startup.complete"}) - elif message["type"] == "lifespan.shutdown": - await send({"type": "lifespan.shutdown.complete"}) - return - called["inner"] = True - await send( - { - "type": "http.response.start", - "status": 200, - "headers": [(b"content-type", b"application/json")], - } - ) - await send({"type": "http.response.body", "body": b"{}"}) - - wrapped = wrap_stateless_transport( - inner, - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - ) - with TestClient(wrapped) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - LEGACY_SESSION_HEADER: "forged", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - }, - ) - assert response.status_code == 400 - assert response.json()["error"]["code"] == -32600 - assert called["inner"] is False - - -class TestOptionsScopedToMcpPath: - def test_options_mcp_is_204_health_is_forwarded(self): - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - from pydantic import BaseModel, Field - - class EchoInput(BaseModel): - value: str = Field(default="") - - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="OptionsHttp", controllers=[EchoController]) - class OptionsModule: - pass - - @mcp_app(module=OptionsModule, server=ServerConfig(name="options-http", stateless=True)) - class OptionsApp: - pass - - app = asyncio.run(McpApplicationFactory.create(OptionsApp)) - http_app = app.get_combined_app(stateless=True, json_response=True) - with TestClient(http_app) as client: - mcp_opt = client.options("/mcp") - health_opt = client.options("/mcp/health") - bare_health = client.options("/health") - oauth_opt = client.options("/oauth/v2/register") - health_preflight = client.options( - "/mcp/health", - headers={ - "Origin": "https://app.example.com", - "Access-Control-Request-Method": "GET", - }, - ) - oauth_preflight = client.options( - "/oauth/v2/register", - headers={ - "Origin": "https://app.example.com", - "Access-Control-Request-Method": "POST", - }, - ) - call = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - assert mcp_opt.status_code == 204 - assert "Access-Control-Allow-Origin" in mcp_opt.headers - assert health_opt.status_code != 204 - assert bare_health.status_code != 204 - assert oauth_opt.status_code != 204 - assert health_preflight.status_code != 204 - assert oauth_preflight.status_code != 204 - assert call.status_code == 200 - assert call.json()["result"]["content"][0]["text"] == "ok" - finally: - DIContainer.reset() - - def test_options_mcp_is_not_sidecar_204_when_cors_off(self): - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - from pydantic import BaseModel, Field - - class EchoInput(BaseModel): - value: str = Field(default="") - - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="OptionsCorsOffHttp", controllers=[EchoController]) - class OptionsCorsOffModule: - pass - - @mcp_app(module=OptionsCorsOffModule, server=ServerConfig(name="options-cors-off")) - class OptionsCorsOffApp: - pass - - app = asyncio.run(McpApplicationFactory.create(OptionsCorsOffApp)) - http_app = app.get_combined_app(stateless=True, json_response=True, enable_cors=False) - with TestClient(http_app) as client: - mcp_opt = client.options("/mcp") - assert mcp_opt.status_code != 204 - finally: - DIContainer.reset() - - def test_options_allow_headers_include_2026_mcp_names(self, monkeypatch): - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - from pydantic import BaseModel, Field - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - monkeypatch.setenv("MCP_CORS_ALLOWED_ORIGINS", "https://app.example.com") - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="CorsAllowHeadersHttp", controllers=[EchoController]) - class CorsAllowHeadersModule: - pass - - @mcp_app(module=CorsAllowHeadersModule, server=ServerConfig(name="cors-allow-headers")) - class CorsAllowHeadersApp: - pass - - app = asyncio.run(McpApplicationFactory.create(CorsAllowHeadersApp)) - http_app = app.get_combined_app(json_response=True) - with TestClient(http_app) as client: - allowed = client.options( - "/mcp", - headers={ - "Origin": "https://app.example.com", - "Access-Control-Request-Method": "POST", - "Access-Control-Request-Headers": ( - "Mcp-Name, Mcp-Method, MCP-Protocol-Version, Mcp-Param-City" - ), - }, - ) - unknown = client.options( - "/mcp", - headers={ - "Origin": "https://evil.example", - "Access-Control-Request-Method": "POST", - "Access-Control-Request-Headers": "Mcp-Name", - }, - ) - assert allowed.status_code == 204 - allow = allowed.headers.get("access-control-allow-headers", "") - assert "Mcp-Name" in allow - assert "Mcp-Method" in allow - assert "MCP-Protocol-Version" in allow - assert "Mcp-Param-City" in allow - assert allowed.headers.get("access-control-allow-origin") == "https://app.example.com" - assert unknown.headers.get("access-control-allow-origin") != "https://evil.example" - finally: - DIContainer.reset() - monkeypatch.delenv("MCP_CORS_ALLOWED_ORIGINS", raising=False) - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) - - -class TestProviderToolDiscovery: - def test_provider_tools_are_registered(self): - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.decorators import ToolConfig - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - assert ToolConfig(name="x", description="d", input_schema={}).task_support == "forbidden" - - DIContainer.reset() - try: - @injectable() - class ToolProvider: - @tool(name="from_provider", description="provider", input_schema=EchoInput) - async def from_provider(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="ProviderTools", providers=[ToolProvider], controllers=[]) - class ProviderModule: - pass - - @mcp_app(module=ProviderModule, server=ServerConfig(name="provider-tools")) - class ProviderApp: - pass - - app = asyncio.run(McpApplicationFactory.create(ProviderApp)) - assert "from_provider" in app._tools - assert app._tools["from_provider"].config.task_support == "forbidden" - finally: - DIContainer.reset() - - -class TestNitroMcpProtocolVersionEnv: - def test_modern_era_enables_stateless_without_mcp_stateless(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "2026-07-28") - monkeypatch.delenv("MCP_STATELESS", raising=False) - - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="EraHttp", controllers=[EchoController]) - class EraModule: - pass - - @mcp_app(module=EraModule, server=ServerConfig(name="era-http")) - class EraApp: - pass - - app = asyncio.run(McpApplicationFactory.create(EraApp)) - http_app = app.get_combined_app(json_response=True) - with TestClient(http_app) as client: - mcp_opt = client.options("/mcp") - call = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "ping", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "ping", - }, - ) - assert mcp_opt.status_code == 204 - assert call.status_code == 200 - assert call.json()["result"] == {} - assert app.protocol_era == "modern" - inner = getattr(http_app, "app", http_app) - assert inner.state.protocol_era == "modern" - assert inner.state.wire_mode == "reject" - assert inner.state.stateless is True - assert inner.state.http_engine == "sessionless" - assert app.mcp_server.http_engine == "sessionless" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_auto_era_keeps_era_and_does_not_force_stateless(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="AutoEraHttp", controllers=[EchoController]) - class AutoEraModule: - pass - - @mcp_app(module=AutoEraModule, server=ServerConfig(name="auto-era-http")) - class AutoEraApp: - pass - - app = asyncio.run(McpApplicationFactory.create(AutoEraApp)) - http_app = app.get_combined_app(json_response=True) - state = _http_app_state(http_app) - assert app.protocol_era == "auto" - assert state.protocol_era == "auto" - assert state.wire_mode == "stateless" - assert state.stateless is True - assert state.http_engine == "sessionless" - assert state.streamable_http_manager_count == 1 - assert app.mcp_server.http_engine == "sessionless" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_legacy_era_uses_sessionful_engine(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "legacy") - monkeypatch.delenv("MCP_STATELESS", raising=False) - - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="LegacyEngineHttp", controllers=[EchoController]) - class LegacyEngineModule: - pass - - @mcp_app(module=LegacyEngineModule, server=ServerConfig(name="legacy-engine-http")) - class LegacyEngineApp: - pass - - app = asyncio.run(McpApplicationFactory.create(LegacyEngineApp)) - http_app = app.get_combined_app(json_response=True) - state = _http_app_state(http_app) - assert app.protocol_era == "legacy" - assert state.http_engine == "sessionful" - assert state.sessionful is True - assert state.stateless is False - assert state.session_manager.stateless is False - assert app.mcp_server.http_engine == "sessionful" - assert app.mcp_server.sessionful is True - assert "echo" in app._tools - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -def _http_app_state(asgi): - current = asgi - seen: set[int] = set() - while current is not None and id(current) not in seen: - seen.add(id(current)) - state = getattr(current, "state", None) - if state is not None and getattr(state, "protocol_era", None) is not None: - return state - current = getattr(current, "app", None) - raise AssertionError("HTTP app is missing protocol era state") - - -class TestEraSessionfulCoexistence: - def _echo_app(self, monkeypatch, era_value: str): - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", era_value) - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name=f"EraCoexist{era_value.title()}", controllers=[EchoController]) - class EraModule: - pass - - @mcp_app(module=EraModule, server=ServerConfig(name=f"era-coexist-{era_value}")) - class EraApp: - pass - - return asyncio.run(McpApplicationFactory.create(EraApp)) - - def test_auto_stateless_false_does_not_start_sessionful_manager(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - app = self._echo_app(monkeypatch, "auto") - http_app = app.get_combined_app(json_response=True, stateless=False) - state = _http_app_state(http_app) - assert state.http_engine == "sessionless" - assert state.sessionful is False - assert state.session_manager.stateless is True - assert state.streamable_http_manager_count == 1 - assert app.mcp_server.sessionful is False - assert "echo" in app._tools - - with TestClient(http_app) as client: - init = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, - }, - ) - assert init.status_code == 200, init.text - assert "result" in init.json() - init_headers = {key.lower(): value for key, value in init.headers.items()} - assert LEGACY_SESSION_HEADER.lower() not in init_headers - assert not state.session_manager._server_instances - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_modern_stateless_false_still_rejects_initialize(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - app = self._echo_app(monkeypatch, "modern") - http_app = app.get_combined_app(json_response=True, stateless=False) - state = _http_app_state(http_app) - assert state.http_engine == "sessionless" - assert state.sessionful is False - assert "echo" in app._tools - - with TestClient(http_app) as client: - init = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, - }, - ) - assert init.status_code == 200 - assert init.json()["error"]["code"] == -32601 - init_headers = {key.lower(): value for key, value in init.headers.items()} - assert LEGACY_SESSION_HEADER.lower() not in init_headers - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_legacy_initialize_creates_session_without_modern_headers(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - app = self._echo_app(monkeypatch, "legacy") - http_app = app.get_combined_app(json_response=True) - state = _http_app_state(http_app) - assert state.http_engine == "sessionful" - assert state.sessionful is True - assert state.streamable_http_manager_count == 1 - assert "echo" in app._tools - - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - } - with TestClient(http_app) as client: - init = client.post( - "/mcp", - headers=json_headers, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, - }, - ) - session_id = init.headers.get("mcp-session-id") or init.headers.get( - "Mcp-Session-Id" - ) - assert init.status_code == 200, init.text - assert session_id - client.post( - "/mcp", - headers={**json_headers, LEGACY_SESSION_HEADER: session_id}, - json={"jsonrpc": "2.0", "method": "notifications/initialized"}, - ) - call = client.post( - "/mcp", - headers={**json_headers, LEGACY_SESSION_HEADER: session_id}, - json={ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - assert call.status_code == 200, call.text - assert call.json()["result"]["content"][0]["text"] == "ok" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestUnsetEnvDefault: - def _echo_app(self): - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - - class EchoInput(BaseModel): - value: str = Field(default="") - - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="UnsetEnvDefault", controllers=[EchoController]) - class UnsetEnvModule: - pass - - @mcp_app(module=UnsetEnvModule, server=ServerConfig(name="unset-env-default")) - class UnsetEnvApp: - pass - - return asyncio.run(McpApplicationFactory.create(UnsetEnvApp)) - - def test_unset_env_http_is_auto_sessionless(self, monkeypatch, caplog): - import logging - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - with caplog.at_level(logging.INFO, logger="nitrostack.core.app"): - app = self._echo_app() - http_app = app.get_combined_app(json_response=True) - state = _http_app_state(http_app) - assert app.protocol_era == "auto" - assert app.protocol_era_source == "default" - assert state.protocol_era == "auto" - assert state.http_engine == "sessionless" - assert "protocol era=auto (source=default)" in caplog.text - - with TestClient(http_app) as client: - init = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, - }, - ) - assert init.status_code == 200, init.text - assert "result" in init.json() - assert init.json()["result"]["protocolVersion"] == "2025-06-18" - init_headers = {key.lower(): value for key, value in init.headers.items()} - assert LEGACY_SESSION_HEADER.lower() not in init_headers - assert not state.session_manager._server_instances - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - os.environ.pop("MCP_STATELESS", None) - - def test_mcp_stateless_false_still_forces_legacy(self, monkeypatch, caplog): - import logging - import os - - from nitrostack.core.di import DIContainer - - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) - monkeypatch.setenv("MCP_STATELESS", "false") - DIContainer.reset() - try: - with caplog.at_level(logging.INFO, logger="nitrostack.core.app"): - app = self._echo_app() - http_app = app.get_combined_app(json_response=True) - state = _http_app_state(http_app) - assert app.protocol_era == "legacy" - assert app.protocol_era_source == "mcp_stateless" - assert state.protocol_era == "legacy" - assert state.http_engine == "sessionful" - assert "protocol era=legacy (source=mcp_stateless)" in caplog.text - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - os.environ.pop("MCP_STATELESS", None) - - -class TestAutoEraOneMcpDualClients: - def test_auto_serves_initialize_and_discover_on_one_mcp(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="DualClientHttp", controllers=[EchoController]) - class DualClientModule: - pass - - @mcp_app(module=DualClientModule, server=ServerConfig(name="dual-client-http")) - class DualClientApp: - pass - - app = asyncio.run(McpApplicationFactory.create(DualClientApp)) - http_app = app.get_combined_app(json_response=True) - state = _http_app_state(http_app) - assert state.protocol_era == "auto" - assert state.streamable_http_manager_count == 1 - assert state.session_manager.stateless is True - - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - } - modern_headers = { - **json_headers, - "MCP-Protocol-Version": MODERN_PROTOCOL_VERSION, - } - - with TestClient(http_app) as client: - init = client.post( - "/mcp", - headers=json_headers, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, - }, - ) - initialized = client.post( - "/mcp", - headers=json_headers, - json={"jsonrpc": "2.0", "method": "notifications/initialized"}, - ) - discover = client.post( - "/mcp", - headers={**modern_headers, "Mcp-Method": "server/discover"}, - json={ - "jsonrpc": "2.0", - "id": 2, - "method": "server/discover", - "params": {}, - }, - ) - call = client.post( - "/mcp", - headers={ - **json_headers, - "MCP-Protocol-Version": "2025-06-18", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - }, - json={ - "jsonrpc": "2.0", - "id": 3, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - - assert init.status_code == 200, init.text - init_body = init.json()["result"] - expected_init = app.handle_sessionless_initialize("2025-06-18") - assert init_body == expected_init - assert app.mcp_server.handle_sessionless_initialize("2025-06-18") == expected_init - assert init_body["protocolVersion"] == "2025-06-18" - assert "serverInfo" in init_body - assert "capabilities" in init_body - init_headers = {key.lower(): value for key, value in init.headers.items()} - assert LEGACY_SESSION_HEADER.lower() not in init_headers - assert not state.session_manager._server_instances - - assert initialized.status_code == 202, initialized.text - if initialized.content: - assert initialized.json() == {} - initialized_headers = { - key.lower(): value for key, value in initialized.headers.items() - } - assert LEGACY_SESSION_HEADER.lower() not in initialized_headers - assert not state.session_manager._server_instances - - assert discover.status_code == 200, discover.text - discover_body = discover.json()["result"] - expected_discover = app.handle_server_discover() - assert discover_body == expected_discover - assert app.mcp_server.handle_server_discover() == expected_discover - assert discover_body["protocolVersion"] == MODERN_PROTOCOL_VERSION - assert discover.headers.get("MCP-Protocol-Version") == MODERN_PROTOCOL_VERSION - - assert call.status_code == 200, call.text - assert call.json()["result"]["content"][0]["text"] == "ok" - assert call.headers.get("MCP-Protocol-Version") == "2025-06-18" - assert call.headers.get("Mcp-Method") == "tools/call" - call_headers = {key.lower(): value for key, value in call.headers.items()} - assert LEGACY_SESSION_HEADER.lower() not in call_headers - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestModernEraRejectsLegacyWire: - def test_modern_initialize_is_jsonrpc_error_without_session(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "modern") - monkeypatch.delenv("MCP_STATELESS", raising=False) - - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="ModernRejectHttp", controllers=[EchoController]) - class ModernRejectModule: - pass - - @mcp_app(module=ModernRejectModule, server=ServerConfig(name="modern-reject-http")) - class ModernRejectApp: - pass - - app = asyncio.run(McpApplicationFactory.create(ModernRejectApp)) - http_app = app.get_combined_app(json_response=True) - state = _http_app_state(http_app) - assert state.wire_mode == "reject" - - headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - } - initialize_body = { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, - } - initialized_body = {"jsonrpc": "2.0", "method": "notifications/initialized"} - - with TestClient(http_app) as client: - init = client.post("/mcp", headers=headers, json=initialize_body) - initialized = client.post( - "/mcp", headers=headers, json=initialized_body - ) - init_with_session = client.post( - "/mcp", - headers={**headers, LEGACY_SESSION_HEADER: "forged"}, - json=initialize_body, - ) - initialized_with_session = client.post( - "/mcp", - headers={**headers, LEGACY_SESSION_HEADER: "forged"}, - json=initialized_body, - ) - - assert init.status_code == 200 - assert init.json()["error"]["code"] == -32601 - assert init.json()["error"]["message"] == "Method not found: initialize" - init_headers = {key.lower(): value for key, value in init.headers.items()} - assert LEGACY_SESSION_HEADER.lower() not in init_headers - assert not state.session_manager._server_instances - - assert initialized.status_code == 200 - assert initialized.json()["error"]["code"] == -32601 - assert ( - initialized.json()["error"]["message"] - == "Method not found: notifications/initialized" - ) - initialized_headers = { - key.lower(): value for key, value in initialized.headers.items() - } - assert LEGACY_SESSION_HEADER.lower() not in initialized_headers - - assert init_with_session.status_code == 400 - assert init_with_session.json()["error"]["code"] == -32600 - session_init_headers = { - key.lower(): value for key, value in init_with_session.headers.items() - } - assert LEGACY_SESSION_HEADER.lower() not in session_init_headers - - assert initialized_with_session.status_code == 400 - assert initialized_with_session.json()["error"]["code"] == -32600 - assert not state.session_manager._server_instances - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestHealthAdvertisesEra: - def _health_body(self, monkeypatch, era_value: str) -> dict: - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", era_value) - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="HealthEraHttp", controllers=[EchoController]) - class HealthEraModule: - pass - - @mcp_app(module=HealthEraModule, server=ServerConfig(name="health-era-http")) - class HealthEraApp: - pass - - app = asyncio.run(McpApplicationFactory.create(HealthEraApp)) - http_app = app.get_combined_app(json_response=True) - with TestClient(http_app) as client: - response = client.get("/mcp/health") - assert response.status_code == 200 - return response.json() - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_modern_health_reports_modern_era(self, monkeypatch): - body = self._health_body(monkeypatch, "modern") - assert body["status"] == "ok" - assert body["transport"] == "streamable-http" - assert body["protocolEra"] == "modern" - assert body["protocolVersion"] == "2026-07-28" - assert body["statelessCapable"] is True - assert "stateless" in body - assert "uptimeSeconds" in body - - def test_auto_health_reports_auto_not_modern(self, monkeypatch): - body = self._health_body(monkeypatch, "auto") - assert body["protocolEra"] == "auto" - assert body["protocolEra"] != "modern" - assert body["statelessCapable"] is True - - def test_legacy_health_reports_legacy_era(self, monkeypatch): - body = self._health_body(monkeypatch, "legacy") - assert body["protocolEra"] == "legacy" - assert body["protocolVersion"] == "2025-06-18" - assert body["statelessCapable"] is False - - -class TestTrustedProxyPublicUrl: - def _http_app(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.delenv("MCP_STATELESS", raising=False) - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - DIContainer.reset() - - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="ProxyHttp", controllers=[EchoController]) - class ProxyModule: - pass - - @mcp_app(module=ProxyModule, server=ServerConfig(name="proxy-http")) - class ProxyApp: - pass - - app = asyncio.run(McpApplicationFactory.create(ProxyApp)) - return app.get_combined_app(json_response=True) - - def test_health_ignores_untrusted_forwarded_host(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - http_app = self._http_app(monkeypatch) - with TestClient(http_app, client=("8.8.8.8", 4321)) as client: - response = client.get( - "/mcp/health", - headers={ - "Host": "internal:3000", - "X-Forwarded-Host": "mcp.example.com", - "X-Forwarded-Proto": "https", - }, - ) - docs = client.get( - "/", - headers={ - "Host": "internal:3000", - "X-Forwarded-Host": "mcp.example.com", - "X-Forwarded-Proto": "https", - }, - ) - oauth = client.get( - "/.well-known/oauth-authorization-server", - headers={ - "Host": "internal:3000", - "X-Forwarded-Host": "mcp.example.com", - "X-Forwarded-Proto": "https", - }, - ) - assert response.status_code == 200 - assert "mcp.example.com" not in response.json()["publicUrl"] - assert "mcp.example.com" not in docs.text - assert "mcp.example.com" not in oauth.json()["error_description"] - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_health_honors_trusted_forwarded_host(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - monkeypatch.setenv("TRUSTED_PROXIES", "10.0.0.5") - try: - http_app = self._http_app(monkeypatch) - with TestClient(http_app, client=("10.0.0.5", 4321)) as client: - headers = { - "Host": "internal:3000", - "X-Forwarded-Host": "mcp.example.com", - "X-Forwarded-Proto": "https", - } - response = client.get("/mcp/health", headers=headers) - docs = client.get("/", headers=headers) - oauth = client.get("/.well-known/oauth-authorization-server", headers=headers) - version = client.get("/json/version", headers=headers) - assert response.status_code == 200 - assert response.json()["publicUrl"] == "https://mcp.example.com/mcp" - assert "https://mcp.example.com/mcp" in docs.text - assert "https://mcp.example.com/mcp" in oauth.json()["error_description"] - assert version.json()["publicUrl"] == "https://mcp.example.com/mcp" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - os.environ.pop("TRUSTED_PROXIES", None) - - -class TestHeaderTriggeredPing: - def _http_app(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.delenv("MCP_STATELESS", raising=False) - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - DIContainer.reset() - - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="HeaderPingHttp", controllers=[EchoController]) - class HeaderPingModule: - pass - - @mcp_app(module=HeaderPingModule, server=ServerConfig(name="header-ping-http")) - class HeaderPingApp: - pass - - app = asyncio.run(McpApplicationFactory.create(HeaderPingApp)) - return app.get_combined_app(json_response=True) - - def test_empty_body_ping_header_succeeds(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - http_app = self._http_app(monkeypatch) - with TestClient(http_app) as client: - response = client.post( - "/mcp", - headers={ - "Accept": "application/json, text/event-stream", - "Mcp-Method": "ping", - }, - content=b"", - ) - assert response.status_code == 200 - body = response.json() - assert body["result"] == {} - assert "error" not in body - assert body.get("error", {}).get("code") != PARSE_ERROR - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_tools_call_body_with_ping_header_is_mismatch(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - http_app = self._http_app(monkeypatch) - with TestClient(http_app) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "ping", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "x"}}, - }, - ) - assert response.status_code == 400 - assert response.json()["error"]["code"] == HEADER_BODY_MISMATCH - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestEnvelopeOnHandlerContext: - def test_tool_reads_trace_and_protocol_version_not_spoofed_user(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EmptyInput(BaseModel): - pass - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EnvelopeController: - @tool(name="envelope", description="read envelope", input_schema=EmptyInput) - async def envelope(self, input: EmptyInput, context: ExecutionContext) -> dict: - return { - "protocolVersion": context.protocol_version, - "trace": context.rpc_meta.trace if context.rpc_meta else None, - "user": context.user, - } - - @module(name="EnvelopeHttp", controllers=[EnvelopeController]) - class EnvelopeModule: - pass - - @mcp_app(module=EnvelopeModule, server=ServerConfig(name="envelope-http")) - class EnvelopeApp: - pass - - app = asyncio.run(McpApplicationFactory.create(EnvelopeApp)) - http_app = app.get_combined_app(json_response=True) - headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "MCP-Protocol-Version": "2025-06-18", - "Mcp-Method": "tools/call", - "Mcp-Name": "envelope", - } - with TestClient(http_app) as client: - response = client.post( - "/mcp", - headers=headers, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": { - "name": "envelope", - "arguments": {}, - "_meta": { - "trace": {"id": "http-span"}, - "userId": "spoofed", - }, - }, - }, - ) - - assert response.status_code == 200, response.text - result = response.json()["result"] - body = result.get("structuredContent") or json.loads(result["content"][0]["text"]) - assert body["protocolVersion"] == "2025-06-18" - assert body["trace"] == {"id": "http-span"} - assert body["user"] is None - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestAuthFromEnvelopeAndHeaders: - def test_tool_user_comes_from_header_jwt_not_unsigned_meta(self, monkeypatch): - import os - - from pydantic import BaseModel - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.auth.jwt import JWTService - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EmptyInput(BaseModel): - pass - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - jwt = JWTService() - DIContainer.get_instance().register_value(JWTService, jwt) - token = jwt.create_token({"sub": "alice", "tenant_id": "acme"}) - try: - @injectable() - class AuthController: - @tool(name="whoami", description="identity", input_schema=EmptyInput) - async def whoami(self, input: EmptyInput, context: ExecutionContext) -> dict: - return {"user": context.user} - - @module(name="AuthHttp", controllers=[AuthController]) - class AuthModule: - pass - - @mcp_app(module=AuthModule, server=ServerConfig(name="auth-http")) - class AuthApp: - pass - - app = asyncio.run(McpApplicationFactory.create(AuthApp)) - http_app = app.get_combined_app(json_response=True) - with TestClient(http_app) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "MCP-Protocol-Version": "2025-06-18", - "Mcp-Method": "tools/call", - "Mcp-Name": "whoami", - "Authorization": f"Bearer {token}", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": { - "name": "whoami", - "arguments": {}, - "_meta": { - "userId": "eve", - "tenantId": "evil", - "io.modelcontextprotocol/auth": {"userId": "mallory"}, - }, - }, - }, - ) - - assert response.status_code == 200, response.text - result = response.json()["result"] - body = result.get("structuredContent") or json.loads(result["content"][0]["text"]) - assert body["user"] == "alice" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestIncomingSessionIdRejection: - def _echo_app(self, monkeypatch, era_value: str): - import os - - from pydantic import BaseModel, Field - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", era_value) - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="SessionRejectHttp", controllers=[EchoController]) - class SessionRejectModule: - pass - - @mcp_app(module=SessionRejectModule, server=ServerConfig(name="session-reject-http")) - class SessionRejectApp: - pass - - return asyncio.run(McpApplicationFactory.create(SessionRejectApp)) - - def test_modern_post_with_session_id_is_rejected(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - app = self._echo_app(monkeypatch, "modern") - http_app = app.get_combined_app(json_response=True) - headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - LEGACY_SESSION_HEADER: "forged", - } - with TestClient(http_app) as client: - rejected = client.post( - "/mcp", - headers=headers, - json={"jsonrpc": "2.0", "id": 1, "method": "ping"}, - ) - allowed = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "ping", - }, - json={"jsonrpc": "2.0", "id": 2, "method": "ping"}, - ) - assert rejected.status_code == 400 - assert rejected.json()["error"]["code"] == -32600 - assert allowed.status_code == 200 - assert allowed.json()["result"] == {} - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_auto_post_with_session_id_is_rejected(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - app = self._echo_app(monkeypatch, "auto") - http_app = app.get_combined_app(json_response=True) - with TestClient(http_app) as client: - rejected = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - LEGACY_SESSION_HEADER: "forged", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - allowed = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - }, - json={ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - assert rejected.status_code == 400 - assert rejected.json()["error"]["code"] == -32600 - assert allowed.status_code == 200 - assert allowed.json()["result"]["content"][0]["text"] == "ok" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_legacy_post_accepts_session_id_after_initialize(self, monkeypatch): - import os - - from starlette.testclient import TestClient - - from nitrostack.core.di import DIContainer - - try: - app = self._echo_app(monkeypatch, "legacy") - http_app = app.get_combined_app(json_response=True) - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - } - with TestClient(http_app) as client: - init = client.post( - "/mcp", - headers=json_headers, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2025-06-18", - "capabilities": {}, - "clientInfo": {"name": "legacy-client", "version": "1.0"}, - }, - }, - ) - session_id = init.headers.get("mcp-session-id") or init.headers.get( - "Mcp-Session-Id" - ) - assert init.status_code == 200, init.text - assert session_id - client.post( - "/mcp", - headers={**json_headers, LEGACY_SESSION_HEADER: session_id}, - json={"jsonrpc": "2.0", "method": "notifications/initialized"}, - ) - call = client.post( - "/mcp", - headers={ - **json_headers, - LEGACY_SESSION_HEADER: session_id, - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - }, - json={ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - assert call.status_code == 200, call.text - assert call.json()["result"]["content"][0]["text"] == "ok" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestSessionIdNotForwarded: - def test_forwarded_scope_omits_session_header(self): - from starlette.testclient import TestClient - - from nitrostack.transports.middleware import wrap_stateless_transport - - captured: dict[str, list] = {} - - async def inner(scope, receive, send): - if scope["type"] == "lifespan": - while True: - message = await receive() - if message["type"] == "lifespan.startup": - await send({"type": "lifespan.startup.complete"}) - elif message["type"] == "lifespan.shutdown": - await send({"type": "lifespan.shutdown.complete"}) - return - captured["headers"] = list(scope.get("headers") or []) - await send( - { - "type": "http.response.start", - "status": 200, - "headers": [(b"content-type", b"application/json")], - } - ) - await send( - { - "type": "http.response.body", - "body": b'{"jsonrpc":"2.0","id":1,"result":{}}', - } - ) - - wrapped = wrap_stateless_transport( - inner, - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - wire_mode="sessionful", - ) - with TestClient(wrapped) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - LEGACY_SESSION_HEADER: "forged", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - }, - ) - assert response.status_code == 200 - assert "headers" in captured - assert all(key.lower() != b"mcp-session-id" for key, _ in captured["headers"]) - forwarded = {key.lower(): value for key, value in captured["headers"]} - assert forwarded.get(b"mcp-method") == b"tools/call" - assert forwarded.get(b"mcp-name") == b"echo" - - def test_forged_session_id_cannot_associate_two_modern_calls(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "modern") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="NoSharedSessionHttp", controllers=[EchoController]) - class NoSharedSessionModule: - pass - - @mcp_app(module=NoSharedSessionModule, server=ServerConfig(name="no-shared-session")) - class NoSharedSessionApp: - pass - - app = asyncio.run(McpApplicationFactory.create(NoSharedSessionApp)) - http_app = app.get_combined_app(json_response=True) - headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - LEGACY_SESSION_HEADER: "forged-shared", - } - body = { - "jsonrpc": "2.0", - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - } - with TestClient(http_app) as client: - first = client.post("/mcp", headers=headers, json={**body, "id": 1}) - second = client.post("/mcp", headers=headers, json={**body, "id": 2}) - assert first.status_code == 400 - assert second.status_code == 400 - assert first.json()["error"]["code"] == -32600 - assert second.json()["error"]["code"] == -32600 - state = _http_app_state(http_app) - assert not getattr(state.session_manager, "_server_instances", True) - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - def test_modern_get_mcp_rejects_session_id(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "modern") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="ModernGetSessionHttp", controllers=[EchoController]) - class ModernGetSessionModule: - pass - - @mcp_app(module=ModernGetSessionModule, server=ServerConfig(name="modern-get-session")) - class ModernGetSessionApp: - pass - - app = asyncio.run(McpApplicationFactory.create(ModernGetSessionApp)) - http_app = app.get_combined_app(json_response=True) - with TestClient(http_app) as client: - response = client.get( - "/mcp", - headers={ - "Accept": "text/event-stream", - LEGACY_SESSION_HEADER: "forged", - }, - ) - assert response.status_code == 400 - assert response.json()["error"]["code"] == -32600 - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestRequiredMcpName: - def test_http_tools_call_missing_and_mismatch_and_match(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="RequiredNameHttp", controllers=[EchoController]) - class RequiredNameModule: - pass - - @mcp_app(module=RequiredNameModule, server=ServerConfig(name="required-name-http")) - class RequiredNameApp: - pass - - app = asyncio.run(McpApplicationFactory.create(RequiredNameApp)) - http_app = app.get_combined_app(json_response=True) - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - } - call_body = { - "jsonrpc": "2.0", - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - } - with TestClient(http_app) as client: - missing = client.post( - "/mcp", - headers=json_headers, - json={**call_body, "id": 1}, - ) - mismatch = client.post( - "/mcp", - headers={**json_headers, "Mcp-Name": "foo"}, - json={**call_body, "id": 2}, - ) - matched = client.post( - "/mcp", - headers={**json_headers, "Mcp-Name": "echo"}, - json={**call_body, "id": 3}, - ) - assert missing.status_code == 200, missing.text - assert missing.json()["result"]["content"][0]["text"] == "ok" - assert mismatch.status_code == 400 - assert mismatch.json()["error"]["code"] == -32020 - assert matched.status_code == 200, matched.text - assert matched.json()["result"]["content"][0]["text"] == "ok" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestRequiredMcpMethod: - def test_pipeline_tools_call_requires_mcp_method_on_modern(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject" - ) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo"}, - } - ).encode() - missing = await pipeline.handle_post(body, {"Mcp-Name": "demo"}) - mismatch = await pipeline.handle_post( - body, {"Mcp-Name": "demo", "Mcp-Method": "tools/list"} - ) - matched = await pipeline.handle_post( - body, {"Mcp-Name": "demo", "Mcp-Method": "tools/call"} - ) - assert missing is not None - assert missing[0] == 400 - assert missing[1]["error"]["code"] == -32020 - assert mismatch is not None - assert mismatch[0] == 400 - assert mismatch[1]["error"]["code"] == -32020 - assert matched is None - - asyncio.run(_run()) - - def test_auto_tools_call_accepts_body_only_name_and_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless" - ) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo", "arguments": {}}, - } - ).encode() - legacy = await pipeline.handle_post(body, {}) - mismatch = await pipeline.handle_post( - body, {"Mcp-Method": "tools/list", "Mcp-Name": "demo"} - ) - assert legacy is None - assert mismatch is not None - assert mismatch[0] == 400 - assert mismatch[1]["error"]["code"] == -32020 - - asyncio.run(_run()) - - def test_auto_initialize_does_not_require_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": {"protocolVersion": "2025-06-18", "capabilities": {}}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"]["protocolVersion"] == "2025-06-18" - - asyncio.run(_run()) - - def test_auto_list_methods_do_not_require_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - for method in ("tools/list", "resources/list", "prompts/list"): - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": method, "params": {}} - ).encode() - result = await pipeline.handle_post(body, {}) - assert result is None, method - - asyncio.run(_run()) - - def test_modern_ping_requires_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - missing = await pipeline.handle_post(body, {}) - matched = await pipeline.handle_post(body, {"Mcp-Method": "ping"}) - assert missing is not None - assert missing[0] == 400 - assert missing[1]["error"]["code"] == -32020 - assert matched is not None - assert matched[0] == 200 - assert matched[1]["result"] == {} - - asyncio.run(_run()) - - def test_http_tools_call_missing_and_mismatch_and_match(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="RequiredMethodHttp", controllers=[EchoController]) - class RequiredMethodModule: - pass - - @mcp_app(module=RequiredMethodModule, server=ServerConfig(name="required-method-http")) - class RequiredMethodApp: - pass - - app = asyncio.run(McpApplicationFactory.create(RequiredMethodApp)) - http_app = app.get_combined_app(json_response=True) - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Name": "echo", - } - call_body = { - "jsonrpc": "2.0", - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - } - with TestClient(http_app) as client: - missing = client.post( - "/mcp", - headers=json_headers, - json={**call_body, "id": 1}, - ) - mismatch = client.post( - "/mcp", - headers={**json_headers, "Mcp-Method": "tools/list"}, - json={**call_body, "id": 2}, - ) - matched = client.post( - "/mcp", - headers={**json_headers, "Mcp-Method": "tools/call"}, - json={**call_body, "id": 3}, - ) - assert missing.status_code == 200, missing.text - assert missing.json()["result"]["content"][0]["text"] == "ok" - assert mismatch.status_code == 400 - assert mismatch.json()["error"]["code"] == -32020 - assert matched.status_code == 200, matched.text - assert matched.json()["result"]["content"][0]["text"] == "ok" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -def _contract_params(method: str) -> dict: - if mcp_name_is_required(method): - field = mcp_name_field(method) - if field == "uri": - return {"uri": "mcp://demo/item"} - return {"name": "demo"} - if method.startswith("tasks/"): - return {"taskId": "task-1"} - return {} - - -class TestSep2243AllModernMethods: - def test_table_covers_modern_surface(self): - methods = {row.method for row in MODERN_METHOD_CONTRACTS} - assert "server/discover" in methods - assert "resources/read" in methods - assert "prompts/get" in methods - assert "completion/complete" in methods - assert "tasks/get" in methods - assert "tools/call" in methods - - @pytest.mark.parametrize( - "contract", - [ - row - for row in MODERN_METHOD_CONTRACTS - if row.method not in {"initialize", "notifications/initialized"} - ], - ids=lambda row: row.method, - ) - def test_modern_missing_mcp_method_is_header_mismatch(self, contract): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": contract.method, - "params": _contract_params(contract.method), - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 400 - assert resp["error"]["code"] == HEADER_BODY_MISMATCH - - asyncio.run(_run()) - - @pytest.mark.parametrize( - "contract", - [ - row - for row in MODERN_METHOD_CONTRACTS - if row.method not in {"initialize", "notifications/initialized"} - ], - ids=lambda row: row.method, - ) - def test_modern_unsupported_protocol_version(self, contract): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - params = _contract_params(contract.method) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": contract.method, - "params": params, - } - ).encode() - headers = { - "Mcp-Method": contract.method, - "MCP-Protocol-Version": "1999-01-01", - } - if mcp_name_is_required(contract.method): - field = mcp_name_field(contract.method) - headers["Mcp-Name"] = params[field] - status, resp = await pipeline.handle_post(body, headers) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - - def test_resources_read_and_prompts_get_require_mcp_name(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject" - ) - ) - read_body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "resources/read", - "params": {"uri": "mcp://demo/item"}, - } - ).encode() - prompt_body = json.dumps( - { - "jsonrpc": "2.0", - "id": 2, - "method": "prompts/get", - "params": {"name": "demo"}, - } - ).encode() - read_missing = await pipeline.handle_post( - read_body, {"Mcp-Method": "resources/read"} - ) - prompt_missing = await pipeline.handle_post( - prompt_body, {"Mcp-Method": "prompts/get"} - ) - assert read_missing is not None - assert read_missing[0] == 400 - assert read_missing[1]["error"]["code"] == HEADER_BODY_MISMATCH - assert prompt_missing is not None - assert prompt_missing[0] == 400 - assert prompt_missing[1]["error"]["code"] == HEADER_BODY_MISMATCH - assert read_missing[1]["error"]["code"] == prompt_missing[1]["error"]["code"] - - asyncio.run(_run()) - - def test_auto_discover_still_allows_missing_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {}} - ).encode() - assert await pipeline.handle_post(body, {}) is None - - asyncio.run(_run()) - - -class TestProtocolVersionCrossCheck: - def test_http_mismatch_is_rejected_and_header_only_succeeds(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="VersionCrossCheckHttp", controllers=[EchoController]) - class VersionCrossCheckModule: - pass - - @mcp_app(module=VersionCrossCheckModule, server=ServerConfig(name="version-cross-check")) - class VersionCrossCheckApp: - pass - - app = asyncio.run(McpApplicationFactory.create(VersionCrossCheckApp)) - http_app = app.get_combined_app(json_response=True) - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - } - with TestClient(http_app) as client: - mismatch = client.post( - "/mcp", - headers={**json_headers, "MCP-Protocol-Version": "2026-07-28"}, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": { - "name": "echo", - "arguments": {"value": "ok"}, - "_meta": {"mcp": {"protocolVersion": "2025-06-18"}}, - }, - }, - ) - header_only = client.post( - "/mcp", - headers={**json_headers, "MCP-Protocol-Version": "2025-06-18"}, - json={ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - assert mismatch.status_code == 400 - assert mismatch.json()["error"]["code"] == -32020 - assert header_only.status_code == 200, header_only.text - assert header_only.json()["result"]["content"][0]["text"] == "ok" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestUnsupportedProtocolVersionHttp: - def test_http_unknown_version_is_rejected_and_supported_proceeds(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="UnsupportedVersionHttp", controllers=[EchoController]) - class UnsupportedVersionModule: - pass - - @mcp_app(module=UnsupportedVersionModule, server=ServerConfig(name="unsupported-version")) - class UnsupportedVersionApp: - pass - - app = asyncio.run(McpApplicationFactory.create(UnsupportedVersionApp)) - http_app = app.get_combined_app(json_response=True) - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - } - ping = {"jsonrpc": "2.0", "id": 1, "method": "ping"} - with TestClient(http_app) as client: - unknown = client.post( - "/mcp", - headers={**json_headers, "MCP-Protocol-Version": "1999-01-01"}, - json=ping, - ) - supported = client.post( - "/mcp", - headers={**json_headers, "MCP-Protocol-Version": "2026-07-28"}, - json={**ping, "id": 2}, - ) - legacy = client.post( - "/mcp", - headers={**json_headers, "MCP-Protocol-Version": "2025-06-18"}, - json={**ping, "id": 3}, - ) - assert unknown.status_code == 400 - assert unknown.json()["error"]["code"] == -32022 - assert unknown.json()["error"]["message"] == "Unsupported protocol version" - assert supported.status_code == 200, supported.text - assert supported.json()["result"] == {} - assert legacy.status_code == 200, legacy.text - assert legacy.json()["result"] == {} - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestResponseEchoHeaders: - def test_echo_uses_supported_request_version(self): - headers = build_mcp_echo_headers( - {"MCP-Protocol-Version": "2025-06-18", "Mcp-Method": "tools/call"}, - protocol_version=MODERN_PROTOCOL_VERSION, - supported_versions={"2026-07-28", "2025-06-18"}, - ) - assert headers["MCP-Protocol-Version"] == "2025-06-18" - assert headers["Mcp-Method"] == "tools/call" - assert handled_protocol_version( - {"MCP-Protocol-Version": "1999-01-01"}, - fallback=MODERN_PROTOCOL_VERSION, - supported={"2026-07-28", "2025-06-18"}, - ) == MODERN_PROTOCOL_VERSION - - def test_http_success_and_error_echo_headers(self, monkeypatch): - import os - - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="EchoHeadersHttp", controllers=[EchoController]) - class EchoHeadersModule: - pass - - @mcp_app(module=EchoHeadersModule, server=ServerConfig(name="echo-headers")) - class EchoHeadersApp: - pass - - app = asyncio.run(McpApplicationFactory.create(EchoHeadersApp)) - http_app = app.get_combined_app(json_response=True) - json_headers = { - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "MCP-Protocol-Version": "2025-06-18", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - } - with TestClient(http_app) as client: - success = client.post( - "/mcp", - headers=json_headers, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - mismatch = client.post( - "/mcp", - headers={**json_headers, "Mcp-Name": "other"}, - json={ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - unsupported = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "MCP-Protocol-Version": "1999-01-01", - }, - json={"jsonrpc": "2.0", "id": 3, "method": "ping"}, - ) - assert success.status_code == 200, success.text - assert success.headers.get("MCP-Protocol-Version") == "2025-06-18" - assert success.headers.get("Mcp-Method") == "tools/call" - assert mismatch.status_code == 400 - assert mismatch.json()["error"]["code"] == -32020 - assert mismatch.headers.get("MCP-Protocol-Version") == "2025-06-18" - assert mismatch.headers.get("Mcp-Method") == "tools/call" - assert unsupported.status_code == 400 - assert unsupported.json()["error"]["code"] == -32022 - assert unsupported.headers.get("MCP-Protocol-Version") == MODERN_PROTOCOL_VERSION - assert unsupported.headers.get("Mcp-Method") == "ping" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -class TestCorsExposeHeaders: - def test_http_mcp_response_exposes_echo_headers_not_session_id(self, monkeypatch): - from pydantic import BaseModel, Field - from starlette.testclient import TestClient - - from nitrostack import ExecutionContext, injectable, module, tool - from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app - from nitrostack.core.di import DIContainer - - class EchoInput(BaseModel): - value: str = Field(default="") - - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - DIContainer.reset() - try: - @injectable() - class EchoController: - @tool(name="echo", description="echo", input_schema=EchoInput) - async def echo(self, input: EchoInput, context: ExecutionContext) -> str: - return input.value - - @module(name="CorsExposeHttp", controllers=[EchoController]) - class CorsExposeModule: - pass - - @mcp_app(module=CorsExposeModule, server=ServerConfig(name="cors-expose")) - class CorsExposeApp: - pass - - app = asyncio.run(McpApplicationFactory.create(CorsExposeApp)) - http_app = app.get_combined_app(json_response=True) - origin = "https://app.example.com" - with TestClient(http_app) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Origin": origin, - "MCP-Protocol-Version": "2025-06-18", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {"value": "ok"}}, - }, - ) - preflight = client.options( - "/mcp", - headers={ - "Origin": origin, - "Access-Control-Request-Method": "POST", - }, - ) - assert response.status_code == 200, response.text - expose = response.headers.get("access-control-expose-headers", "") - assert "MCP-Protocol-Version" in expose - assert "Mcp-Method" in expose - assert "Mcp-Session-Id" not in expose - assert preflight.status_code == 204 - preflight_expose = preflight.headers.get("access-control-expose-headers", "") - assert "MCP-Protocol-Version" in preflight_expose - assert "Mcp-Method" in preflight_expose - assert "Mcp-Session-Id" not in preflight_expose - finally: - DIContainer.reset() - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) diff --git a/tests/test_mcp20_stdio.py b/tests/test_mcp20_stdio.py index 94a4b23..6773d3c 100644 --- a/tests/test_mcp20_stdio.py +++ b/tests/test_mcp20_stdio.py @@ -135,8 +135,9 @@ def test_modern_stdio_rejects_initialize(monkeypatch): }, ) ) + # Reject the handshake before it can select the legacy connection style. assert "error" in payload - assert "initialize" in payload["error"]["message"] + assert payload["error"]["code"] == -32601 def test_legacy_stdio_still_answers_initialize(monkeypatch): @@ -172,6 +173,7 @@ def test_dual_http_and_stdio_share_the_same_tools(monkeypatch): "Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Mcp-Method": "tools/list", + "MCP-Protocol-Version": MODERN_PROTOCOL_VERSION, }, json={ "jsonrpc": "2.0", diff --git a/tests/test_mcp20_task_authorization.py b/tests/test_mcp20_task_authorization.py index 3c6eb35..67e9617 100644 --- a/tests/test_mcp20_task_authorization.py +++ b/tests/test_mcp20_task_authorization.py @@ -167,7 +167,10 @@ async def owner_tool(self, input: EchoInput, context: ExecutionContext) -> str: class AuthModule: pass - @mcp_app(module=AuthModule, server=ServerConfig(name="task-auth")) + @mcp_app( + module=AuthModule, + server=ServerConfig(name="task-auth", protocol_era="legacy"), + ) class AuthApp: pass diff --git a/tests/test_mcp20_tasks.py b/tests/test_mcp20_tasks.py index da6bf1d..2e611c5 100644 --- a/tests/test_mcp20_tasks.py +++ b/tests/test_mcp20_tasks.py @@ -96,7 +96,10 @@ async def sync_only(self, input: EchoInput, context: ExecutionContext) -> str: class ForbiddenModule: pass - @mcp_app(module=ForbiddenModule, server=ServerConfig(name="tasks-forbidden")) + @mcp_app( + module=ForbiddenModule, + server=ServerConfig(name="tasks-forbidden", protocol_era="legacy"), + ) class ForbiddenApp: pass @@ -164,7 +167,10 @@ async def noop(self, input: EchoInput, context: ExecutionContext) -> str: class GetModule: pass - @mcp_app(module=GetModule, server=ServerConfig(name="tasks-get")) + @mcp_app( + module=GetModule, + server=ServerConfig(name="tasks-get", protocol_era="legacy"), + ) class GetApp: pass @@ -203,10 +209,7 @@ class ListApp: async def _run(): app = await McpApplicationFactory.create(ListApp) - handler = app.mcp_server.request_handlers[types.ListTasksRequest] - with pytest.raises(McpError) as exc: - await handler(types.ListTasksRequest(method="tasks/list", params={})) - assert exc.value.error.code == types.METHOD_NOT_FOUND + assert types.ListTasksRequest not in app.mcp_server.request_handlers asyncio.run(_run()) @@ -226,7 +229,10 @@ async def noop3(self, input: EchoInput, context: ExecutionContext) -> str: class CancelModule: pass - @mcp_app(module=CancelModule, server=ServerConfig(name="tasks-cancel")) + @mcp_app( + module=CancelModule, + server=ServerConfig(name="tasks-cancel", protocol_era="legacy"), + ) class CancelApp: pass @@ -256,7 +262,10 @@ async def slow_echo(self, input: EchoInput, context: ExecutionContext) -> str: class CreateModule: pass - @mcp_app(module=CreateModule, server=ServerConfig(name="tasks-create")) + @mcp_app( + module=CreateModule, + server=ServerConfig(name="tasks-create", protocol_era="legacy"), + ) class CreateApp: pass diff --git a/tests/test_mcp20_tool_args.py b/tests/test_mcp20_tool_args.py index f619cfe..dbd5e08 100644 --- a/tests/test_mcp20_tool_args.py +++ b/tests/test_mcp20_tool_args.py @@ -80,7 +80,7 @@ def test_strip_empty_and_none(): assert strip_tool_arguments({}) == {} -def _echo_app(seen: dict, *, task_support: str = "optional"): +def _echo_app(seen: dict, *, task_support: str = "optional", protocol_era: str = "auto"): @injectable() class EchoController: @tool( @@ -101,7 +101,7 @@ async def echo(self, input: LooseInput, context: ExecutionContext) -> dict: class EchoModule: pass - @mcp_app(module=EchoModule, server=ServerConfig(name="strip-tool-args")) + @mcp_app(module=EchoModule, server=ServerConfig(name="strip-tool-args", protocol_era=protocol_era)) class EchoApp: pass @@ -131,7 +131,7 @@ def test_handler_input_never_contains_meta(): def test_task_path_strips_arguments_before_handler(): seen: dict = {} - app = _echo_app(seen, task_support="optional") + app = _echo_app(seen, task_support="optional", protocol_era="legacy") created = asyncio.run( app._call_tool( "echo", diff --git a/tests/test_mcp22_official_http_owner.py b/tests/test_mcp22_official_http_owner.py new file mode 100644 index 0000000..bbfabfc --- /dev/null +++ b/tests/test_mcp22_official_http_owner.py @@ -0,0 +1,324 @@ +"""Regression tests for Issue #22: one official owner for ``/mcp``.""" + +import asyncio +import json +from pathlib import Path + +import httpx +import nitrostack + +from nitrostack import module +from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app + +SDK_ROOT = Path(nitrostack.__file__).resolve().parent + + +@module(name="issue22_probe", controllers=[]) +class Issue22ProbeModule: + pass + + +@mcp_app( + module=Issue22ProbeModule, + server=ServerConfig(name="issue22-probe", protocol_era="auto"), +) +class Issue22ProbeApp: + pass + + +def _request(path: str, *, method: str = "GET", payload: dict | None = None): + async def run(): + application = await McpApplicationFactory.create(Issue22ProbeApp) + http_app = application.get_combined_app(json_response=True) + transport = httpx.ASGITransport(app=http_app) + async with http_app.router.lifespan_context(http_app): + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + return await client.request( + method, + path, + headers={ + "content-type": "application/json", + "accept": "application/json, text/event-stream", + }, + content=json.dumps(payload) if payload is not None else None, + ) + + return asyncio.run(run()) + + +def test_combined_app_has_no_jsonrpc_sidecar_call(): + source = (SDK_ROOT / "core" / "app.py").read_text(encoding="utf-8") + assert "wrap_stateless_transport" not in source + assert "return http_app" in source + + +def test_sidecar_modules_and_ping_helpers_are_not_production_code(): + assert not (SDK_ROOT / "transports" / "middleware.py").exists() + assert not (SDK_ROOT / "transports" / "dispatch.py").exists() + sources = list(SDK_ROOT.rglob("*.py")) + assert sources, f"No production Python sources found in {SDK_ROOT}" + production = "\n".join( + path.read_text(encoding="utf-8") + for path in sources + ) + for symbol in ( + "wrap_stateless_transport", + "wrap_sessionless_http", + "wrap_modern_handshake_reject", + "StatelessIngressPipeline", + "build_ping_response", + "is_header_only_ping", + ): + assert symbol not in production + + +def test_health_endpoint_remains_available(): + response = _request("/mcp/health") + assert response.status_code == 200 + assert response.json()["status"] == "ok" + + +def test_official_mcp_lists_tools_without_a_default_session_id(): + response = _request( + "/mcp", + method="POST", + payload={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, + ) + assert response.status_code == 200 + assert response.headers.get("mcp-session-id") is None + assert response.json()["id"] == 1 + assert response.json()["result"]["tools"] == [] + + +def test_official_mcp_ping_is_method_not_found_without_a_default_session_id(): + response = _request( + "/mcp", + method="POST", + payload={"jsonrpc": "2.0", "id": 1, "method": "ping"}, + ) + assert response.status_code == 200 + assert response.headers.get("mcp-session-id") is None + body = response.json() + assert body["error"]["code"] == -32601 + assert "result" not in body + + +def test_official_mcp_returns_jsonrpc_error_for_unknown_method(): + response = _request( + "/mcp", + method="POST", + payload={"jsonrpc": "2.0", "id": 2, "method": "issue22/unknown"}, + ) + assert response.status_code == 200 + body = response.json() + assert body["jsonrpc"] == "2.0" + assert body["id"] == 2 + assert body["error"]["code"] == -32601 + assert "Method not found" in body["error"]["message"] + + +# --------------------------------------------------------------------------- +# Request context, transforms and CORS on the official /mcp path +# --------------------------------------------------------------------------- + +from types import SimpleNamespace + +import pytest +from pydantic import BaseModel, Field +from starlette.testclient import TestClient + +from nitrostack import ExecutionContext, injectable, tool +from nitrostack.core.di import DIContainer +from nitrostack.runtime.caller import caller_identity +from nitrostack.tasks.authorization import extract_task_access_context +from nitrostack.transforms import McpTransformBase +from nitrostack.transforms.search import RegexSearchTransform + +_HEADERS = { + "content-type": "application/json", + "accept": "application/json, text/event-stream", +} + + +class _EchoInput(BaseModel): + value: str = Field(default="") + + +class _Recorder(McpTransformBase): + name = "recorder" + + def __init__(self): + self.seen = [] + + async def transform_tools(self, tools, ctx): + self.seen.append(ctx) + return list(tools) + + +def _build(era: str, transforms=None): + DIContainer.reset() + + @injectable() + class EchoController: + @tool(name="echo", description="echo", input_schema=_EchoInput) + async def echo(self, input: _EchoInput, context: ExecutionContext) -> str: + return input.value + + @module(name=f"owner_{era}", controllers=[EchoController]) + class OwnerModule: + pass + + @mcp_app( + module=OwnerModule, + server=ServerConfig(name=f"owner-{era}", protocol_era=era), + transforms=transforms, + ) + class OwnerApp: + pass + + application = asyncio.run(McpApplicationFactory.create(OwnerApp)) + return application.get_combined_app(json_response=True) + + +def _rpc(method, params=None, id_=1): + return {"jsonrpc": "2.0", "id": id_, "method": method, "params": params or {}} + + +def test_transform_context_is_populated_over_http_for_tools_list(): + recorder = _Recorder() + app = _build("auto", transforms=[recorder]) + with TestClient(app) as client: + response = client.post( + "/mcp", + headers=_HEADERS, + json=_rpc("tools/list", {"_meta": {"userId": "mallory"}}), + ) + assert response.status_code == 200 + ctx = recorder.seen[-1] + assert ctx.execution_context is not None + assert ctx.execution_context.request_id + assert ctx.session_id is None # sessionless era mints no durable session + assert ctx.subject is None # unsigned _meta.userId is never identity + + +def test_regex_search_transform_works_end_to_end_over_http(): + app = _build("auto", transforms=[RegexSearchTransform()]) + with TestClient(app) as client: + listed = client.post("/mcp", headers=_HEADERS, json=_rpc("tools/list")) + names = {t["name"] for t in listed.json()["result"]["tools"]} + assert {"search_tools", "call_tool"} <= names + assert "echo" not in names + + called = client.post( + "/mcp", + headers=_HEADERS, + json=_rpc( + "tools/call", + {"name": "call_tool", "arguments": {"name": "echo", "arguments": {"value": "hi"}}}, + id_=2, + ), + ) + assert called.status_code == 200 + assert "hi" in json.dumps(called.json()["result"]) + + +def test_legacy_era_transform_context_carries_the_session_id(): + recorder = _Recorder() + app = _build("legacy", transforms=[recorder]) + with TestClient(app) as client: + init = client.post( + "/mcp", + headers=_HEADERS, + json=_rpc( + "initialize", + { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "t", "version": "1"}, + }, + ), + ) + session = init.headers["mcp-session-id"] + headers = {**_HEADERS, "mcp-session-id": session, "mcp-protocol-version": "2025-06-18"} + client.post( + "/mcp", headers=headers, json={"jsonrpc": "2.0", "method": "notifications/initialized"} + ) + client.post("/mcp", headers=headers, json=_rpc("tools/list", id_=2)) + assert recorder.seen[-1].session_id == session + + +def test_modern_era_rejects_the_2025_initialize_on_the_official_path(): + from tests.http_probe import envelope + app = _build("modern") + with TestClient(app) as client: + response = client.post( + "/mcp", + headers={**_HEADERS, "MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "initialize"}, + json=envelope( + "initialize", + { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "t", "version": "1"}, + }, + ), + ) + body = response.json() + assert body["error"]["code"] == -32601 + assert "initialize" in body["error"]["message"] + assert "mcp-session-id" not in response.headers + + +def test_cors_honours_the_configured_origin_allowlist(monkeypatch): + monkeypatch.setenv("MCP_CORS_ALLOWED_ORIGINS", "https://app.example.com") + app = _build("auto") + preflight_headers = { + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type, mcp-param-city", + } + with TestClient(app) as client: + allowed = client.options( + "/mcp", headers={**preflight_headers, "Origin": "https://app.example.com"} + ) + denied = client.options( + "/mcp", headers={**preflight_headers, "Origin": "https://evil.example.com"} + ) + post = client.post( + "/mcp", + headers={**_HEADERS, "Origin": "https://app.example.com"}, + json=_rpc("ping"), + ) + assert allowed.status_code == 200 + assert allowed.headers["access-control-allow-origin"] == "https://app.example.com" + assert "mcp-param-city" in allowed.headers["access-control-allow-headers"].lower() + assert denied.status_code == 400 + assert denied.headers.get("access-control-allow-origin") != "*" + assert denied.headers.get("access-control-allow-origin") != "https://evil.example.com" + assert post.headers["access-control-allow-origin"] == "https://app.example.com" + expose = post.headers["access-control-expose-headers"] + assert "Mcp-Method" in expose and "Mcp-Name" in expose + + +def test_cors_exposes_session_id_only_on_the_legacy_wire(monkeypatch): + monkeypatch.delenv("MCP_CORS_ALLOWED_ORIGINS", raising=False) + for era, exposed in (("legacy", True), ("auto", False)): + app = _build(era) + with TestClient(app) as client: + response = client.get("/mcp/health", headers={"Origin": "http://x.test"}) + assert response.status_code == 200 + expose = response.headers.get("access-control-expose-headers", "") + assert ("Mcp-Session-Id" in expose) is exposed, era + + +def test_caller_identity_ignores_session_on_sessionless_eras(): + rc = SimpleNamespace(session=SimpleNamespace(id="sess-1")) + assert caller_identity(rc, "legacy") == ("sess-1", None) + assert caller_identity(rc, "auto") == (None, None) + assert caller_identity(rc, "modern") == (None, None) + assert caller_identity(None, "legacy") == (None, None) + + +def test_task_access_uses_the_same_session_rule_as_transforms(): + rc = SimpleNamespace(session=SimpleNamespace(id="sess-1")) + assert extract_task_access_context(rc, "legacy").session_id == "sess-1" + assert extract_task_access_context(rc, "auto").session_id is None diff --git a/tests/test_mcp23_http_factory.py b/tests/test_mcp23_http_factory.py new file mode 100644 index 0000000..d222156 --- /dev/null +++ b/tests/test_mcp23_http_factory.py @@ -0,0 +1,397 @@ +"""Regression tests for Issue #23: single CORS layer, `resources.subscribe` +agreement between discover and real capability negotiation, era-driven +`/json/version`, and no private `mcp.server.runner` imports in stdio. +""" + +from __future__ import annotations + +import asyncio +import ast +import json +import os +import sys +from contextlib import asynccontextmanager +from pathlib import Path + +import anyio +import httpx +import pytest +import nitrostack +from mcp.shared.memory import create_client_server_memory_streams +from mcp.shared.message import SessionMessage +from mcp_types import PROTOCOL_VERSION_META_KEY, jsonrpc_message_adapter +from pydantic import BaseModel, Field + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from nitrostack import DIContainer, ExecutionContext, injectable, module, tool +from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app +from nitrostack.protocol.version import LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION +from nitrostack.transports.stdio import serve_stdio_streams +from nitrostack.runtime.request_ctx import stdio_connection_id +from tests.http_probe import decode, http_client, make_app, post + +CLIENT_META = { + "io.modelcontextprotocol/clientInfo": {"name": "issue23-test", "version": "1.0"}, + "io.modelcontextprotocol/clientCapabilities": {}, +} +SDK_ROOT = Path(nitrostack.__file__).resolve().parent + + +def setup_function() -> None: + DIContainer.reset() + + +def teardown_function() -> None: + DIContainer.reset() + + +class EchoInput(BaseModel): + value: str = Field(default="ok") + + +def _era_app(era: str, name: str): + @injectable() + class EchoController: + @tool(name="echo", description="echo", input_schema=EchoInput) + async def echo(self, input: EchoInput, context: ExecutionContext) -> str: + return input.value + + @module(name=f"issue23_{name}", controllers=[EchoController]) + class EchoModule: + pass + + @mcp_app(module=EchoModule, server=ServerConfig(name=name, protocol_era=era)) + class EchoApp: + pass + + return asyncio.run(McpApplicationFactory.create(EchoApp)) + + +async def _send(http_app, method: str, path: str, *, headers: dict | None = None, payload: dict | None = None): + transport = httpx.ASGITransport(app=http_app) + async with http_app.router.lifespan_context(http_app): + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + return await client.request( + method, + path, + headers=headers or {}, + content=json.dumps(payload) if payload is not None else None, + ) + + +# 1. OPTIONS /mcp: exactly one CORS policy, not two fighting layers. +def test_single_cors_layer_on_options_mcp(): + app = _era_app("auto", "issue23-cors") + http_app = app.get_combined_app(json_response=True) + response = asyncio.run( + _send( + http_app, + "OPTIONS", + "/mcp", + headers={ + "Origin": "http://example.com", + "Access-Control-Request-Method": "POST", + }, + ) + ) + allow_origin = response.headers.get_list("access-control-allow-origin") + assert len(allow_origin) == 1 + + +# 2. server/discover and NitroStackMcpServer.get_capabilities must never disagree. +@pytest.mark.parametrize("era", ["legacy", "auto", "modern"]) +def test_discover_and_capabilities_agree_on_resources_subscribe(era): + app = _era_app(era, f"issue23-subscribe-{era}") + discover = app.handle_server_discover() + caps = app.mcp_server.get_capabilities() + assert discover["capabilities"]["resources"]["subscribe"] == caps.resources.subscribe + assert caps.resources.subscribe == (era == "legacy") + extra_server = app.create_configured_mcp_server() + assert extra_server.protocol_era == era + assert extra_server.get_capabilities().resources.subscribe == (era == "legacy") + if era == "auto": + with http_client("auto", app=app) as (_, _, client): + response = post(client, "initialize", { + "protocolVersion": LEGACY_PROTOCOL_VERSION, "capabilities": {}, + "clientInfo": {"name": "issue23", "version": "1"}, + }, modern=False, version=LEGACY_PROTOCOL_VERSION) + assert response.status_code == 200 + assert decode(response)["result"]["capabilities"]["resources"]["subscribe"] is False + + +# 3. No runner implementation imports or private MCP modules in stdio.py. +def test_stdio_module_has_no_private_mcp_runner_import(): + source = (SDK_ROOT / "transports" / "stdio.py").read_text(encoding="utf-8") + tree = ast.parse(source) + modules = [] + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module: + modules.append(node.module) + if node.module == "mcp.server": + modules.extend(f"{node.module}.{alias.name}" for alias in node.names) + elif isinstance(node, ast.Import): + modules.extend(alias.name for alias in node.names) + mcp_modules = [name for name in modules if name.split(".")[0] == "mcp"] + assert mcp_modules + assert not [name for name in mcp_modules if name == "mcp.server.runner" or + name.startswith("mcp.server.runner.") or + any(part.startswith("_") for part in name.split("."))] + + +# 4. /json/version tracks era instead of a hardcoded 2025 date. +@pytest.mark.parametrize( + "era, expected_version", + [ + ("legacy", LEGACY_PROTOCOL_VERSION), + ("auto", MODERN_PROTOCOL_VERSION), + ("modern", MODERN_PROTOCOL_VERSION), + ], +) +def test_json_version_matches_era(era, expected_version): + app = _era_app(era, f"issue23-jsonversion-{era}") + http_app = app.get_combined_app(json_response=True) + response = asyncio.run(_send(http_app, "GET", "/json/version")) + assert response.status_code == 200 + assert response.json()["Protocol-Version"] == expected_version + + +# 5. Modern-era stdio boots through the public Server.run entry point. +def test_modern_stdio_serves_tool_call(): + app = _era_app("modern", "issue23-modern-stdio") + + async def roundtrip(): + async with create_client_server_memory_streams() as (client, server): + client_read, client_write = client + server_read, server_write = server + + async def run_server(): + await serve_stdio_streams(app.mcp_server, server_read, server_write, "modern") + + async with anyio.create_task_group() as tg: + tg.start_soon(run_server) + await client_write.send( + SessionMessage( + jsonrpc_message_adapter.validate_python( + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "echo", + "arguments": {"value": "hi"}, + "_meta": {PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION, **CLIENT_META}, + }, + } + ) + ) + ) + response = await asyncio.wait_for(client_read.receive(), timeout=2) + tg.cancel_scope.cancel() + return response.message.model_dump(by_alias=True, mode="json") + + payload = asyncio.run(roundtrip()) + assert "result" in payload + assert payload["result"]["content"][0]["text"] == "hi" + + +# 5b. Official notification handling must keep the connection usable, +# proven by a normal request still working +# on the same stream right after a notification. +def test_modern_stdio_notification_does_not_break_the_stream(): + app = _era_app("modern", "issue23-modern-notify") + + async def roundtrip(): + async with create_client_server_memory_streams() as (client, server): + client_read, client_write = client + server_read, server_write = server + + async def run_server(): + await serve_stdio_streams(app.mcp_server, server_read, server_write, "modern") + + async with anyio.create_task_group() as tg: + tg.start_soon(run_server) + await client_write.send( + SessionMessage( + jsonrpc_message_adapter.validate_python( + { + "jsonrpc": "2.0", + "method": "notifications/cancelled", + "params": { + "requestId": 999, + "_meta": {PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION}, + }, + } + ) + ) + ) + await client_write.send( + SessionMessage( + jsonrpc_message_adapter.validate_python( + { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "echo", + "arguments": {"value": "still-alive"}, + "_meta": {PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION, **CLIENT_META}, + }, + } + ) + ) + ) + response = await asyncio.wait_for(client_read.receive(), timeout=2) + tg.cancel_scope.cancel() + return response.message.model_dump(by_alias=True, mode="json") + + payload = asyncio.run(roundtrip()) + assert payload["result"]["content"][0]["text"] == "still-alive" + + +async def _stdio_exchange(server, era, messages, expected_responses): + """Keep one stream alive through handshake, notifications, and requests.""" + async with create_client_server_memory_streams() as (client, streams): + client_read, client_write = client + server_read, server_write = streams + async with anyio.create_task_group() as group: + group.start_soon(serve_stdio_streams, server, server_read, server_write, era) + for message in messages: + await client_write.send(SessionMessage(jsonrpc_message_adapter.validate_python(message))) + responses = [] + while len(responses) < expected_responses: + frame = await asyncio.wait_for(client_read.receive(), timeout=3) + data = frame.message.model_dump(by_alias=True, mode="json") + if "id" in data: + responses.append(data) + group.cancel_scope.cancel() + return responses + + +@pytest.mark.parametrize("era,style", [ + ("legacy", "legacy"), ("auto", "legacy"), ("auto", "modern"), ("modern", "modern"), +]) +def test_stdio_era_roundtrip_and_initialization_capabilities(era, style): + app = make_app(era) + messages = [] + if style == "legacy": + messages.extend([ + {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": LEGACY_PROTOCOL_VERSION, "capabilities": {}, + "clientInfo": {"name": "probe", "version": "1"}, + }}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + ]) + params = {"name": "echo", "arguments": {"value": "stdio"}} + if style == "modern": + params["_meta"] = {PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION, **CLIENT_META} + messages.append({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": params}) + responses = asyncio.run(_stdio_exchange(app.mcp_server, era, messages, 2 if style == "legacy" else 1)) + if style == "legacy": + assert responses[0]["result"]["capabilities"]["resources"]["subscribe"] == (era == "legacy") + assert responses[-1]["result"]["structuredContent"]["value"] == "stdio" + + +def test_modern_stdio_rejects_initialize_and_then_serves_a_request(): + app = make_app("modern") + messages = [ + {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": LEGACY_PROTOCOL_VERSION, "capabilities": {}, + "clientInfo": {"name": "probe", "version": "1"}, + }}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": { + "_meta": {PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION, **CLIENT_META}, + }}, + ] + responses = asyncio.run(_stdio_exchange(app.mcp_server, "modern", messages, 2)) + assert responses[0]["error"]["code"] == -32601 + assert responses[1]["result"]["tools"][0]["name"] == "echo" + + +def test_legacy_stdio_rejects_modern_request_without_poisoning_initialization(): + app = make_app("legacy") + messages = [ + {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": { + "_meta": {PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION, **CLIENT_META}, + }}, + {"jsonrpc": "2.0", "id": 2, "method": "initialize", "params": { + "protocolVersion": LEGACY_PROTOCOL_VERSION, "capabilities": {}, + "clientInfo": {"name": "probe", "version": "1"}, + }}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { + "name": "echo", "arguments": {"value": "legacy-after-rejection"}, + }}, + ] + responses = asyncio.run(_stdio_exchange(app.mcp_server, "legacy", messages, 3)) + assert responses[0]["error"]["code"] == -32600 + assert responses[1]["result"]["protocolVersion"] == LEGACY_PROTOCOL_VERSION + assert responses[2]["result"]["structuredContent"]["value"] == "legacy-after-rejection" + + +@pytest.mark.parametrize("meta", [None, [], {PROTOCOL_VERSION_META_KEY: "1900-01-01"}]) +def test_modern_stdio_invalid_version_does_not_select_legacy_connection(meta): + app = make_app("modern") + messages = [ + {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": meta}}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": { + "_meta": {PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION, **CLIENT_META}, + }}, + ] + responses = asyncio.run(_stdio_exchange(app.mcp_server, "modern", messages, 2)) + assert "error" in responses[0] + assert responses[0]["error"]["data"]["supportedVersions"] == [MODERN_PROTOCOL_VERSION] + assert responses[1]["result"]["tools"][0]["name"] == "echo" + + +@pytest.mark.parametrize("era", ["legacy", "auto", "modern"]) +def test_stdio_public_runner_closes_lifespan_and_stream_on_eof(era): + app = make_app(era) + events = [] + + @asynccontextmanager + async def lifespan(server): + events.append("start") + try: + yield {} + finally: + events.append("stop") + + app.mcp_server.lifespan = lifespan + + async def scenario(): + async with create_client_server_memory_streams() as (client, streams): + client_read, client_write = client + + async def serve(): + await serve_stdio_streams(app.mcp_server, *streams, era) + assert stdio_connection_id.get() is None + + task = asyncio.create_task(serve()) + try: + await client_write.aclose() + await asyncio.wait_for(task, timeout=3) + with pytest.raises(anyio.EndOfStream): + await asyncio.wait_for(client_read.receive(), timeout=3) + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert stdio_connection_id.get() is None + + asyncio.run(scenario()) + assert events == ["start", "stop"] + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_http_initialize_respects_era(era): + with http_client(era) as (_, _, client): + response = post(client, "initialize", {"protocolVersion": LEGACY_PROTOCOL_VERSION, + "capabilities": {}, "clientInfo": {"name": "probe", "version": "1"}}, + modern=False, version=LEGACY_PROTOCOL_VERSION) + assert response.status_code == 200, response.text + data = decode(response) + if era == "modern": + assert data["error"]["code"] == -32601 + else: + assert data["result"]["capabilities"]["resources"]["subscribe"] is False diff --git a/tests/test_mcp24_wire_alignment.py b/tests/test_mcp24_wire_alignment.py new file mode 100644 index 0000000..28e9fd9 --- /dev/null +++ b/tests/test_mcp24_wire_alignment.py @@ -0,0 +1,233 @@ +"""Issue #24 wire behavior through the official MCP mount and public APIs.""" + +import asyncio +import os +from unittest.mock import patch + +import mcp.types as types +from mcp import MCPError +import pytest +from pydantic import BaseModel + +from nitrostack import DIContainer, module, prompt, resource, tool +from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app +from nitrostack.core.mcp_server import NitroStackMcpServer +from nitrostack.protocol.contracts import MCP_CACHE_HINT_KEY +from nitrostack.protocol.errors import ERROR_CODE_MESSAGES, JsonRpcErrorCode +from nitrostack.protocol.version import LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION +from nitrostack.transports.http import HeaderCompatMiddleware +from tests.http_probe import decode, envelope, headers, http_client, make_app, post + + +class EchoInput(BaseModel): + value: str = "ok" + + +def wire_app(era): + DIContainer.reset() + class Operations: + @tool(name="echo", description="echo", input_schema=EchoInput, task_support="optional") + async def echo(self, input, context): + return types.CallToolResult( + content=[types.TextContent(type="text", text=input.value)], + _meta={"application/example": "preserved"}, + ) + + @resource(uri="wire://info", name="info", description="info") + async def info(self, context): + return "wire resource" + + @resource(uri="wire://items/{item}", name="item", description="item template") + async def item(self, item, context): + return item + + @prompt(name="greet", description="greet") + async def greet(self, arguments, context): + return [{"role": "user", "content": "hello"}] + + @module(name="wire-operations", providers=[Operations]) + class WireModule: + pass + + @mcp_app(module=WireModule, server=ServerConfig(name="wire-test", version="1.2.3", protocol_era=era)) + class WireApp: + pass + + with patch.dict(os.environ, {"NITRO_MCP_PROTOCOL_VERSION": era, "MCP_STATELESS": ""}): + return asyncio.run(McpApplicationFactory.create(WireApp)) + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +@pytest.mark.parametrize("method,params", [ + ("ping", {}), ("initialize", {}), ("tasks/list", {}), + ("tasks/result", {"taskId": "missing"}), + ("resources/subscribe", {"uri": "probe://info"}), + ("logging/setLevel", {"level": "info"}), +]) +def test_retired_methods_on_the_modern_wire(era, method, params): + with http_client(era) as (_, _, client): + response = post(client, method, params) + assert response.status_code == 404, response.text + assert decode(response)["error"]["code"] == -32601 + + +def test_auto_legacy_shaped_ping_is_also_retired(): + with http_client("auto") as (_, _, client): + response = client.post("/mcp", json=envelope("ping", modern=False), + headers={"Accept": "application/json, text/event-stream"}) + assert response.status_code == 200 + assert decode(response)["error"]["code"] == -32601 + + +def test_legacy_ping_still_works_after_initialization(): + with http_client("legacy") as (_, _, client): + response = post(client, "ping", modern=False, version=LEGACY_PROTOCOL_VERSION) + assert response.status_code == 200 + assert decode(response)["result"] == {} + + +@pytest.mark.parametrize("method,params", [ + ("server/discover", {}), ("tools/list", {}), + ("tools/call", {"name": "echo", "arguments": {}}), + ("resources/read", {"uri": "probe://info"}), +]) +@pytest.mark.parametrize("body_has_modern_meta", [True, False]) +@pytest.mark.parametrize("version", [None, "", " "]) +def test_modern_requests_without_a_version_header_fail_closed(method, params, body_has_modern_meta, version): + with http_client("modern") as (_, _, client): + outgoing = headers(method) + outgoing.pop("MCP-Protocol-Version") + if version is not None: + outgoing["MCP-Protocol-Version"] = version + response = client.post("/mcp", headers=outgoing, + json=envelope(method, params, modern=body_has_modern_meta)) + assert response.status_code == 400, response.text + body = decode(response) + assert body["error"]["code"] == -32020 + assert "result" not in body + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +@pytest.mark.parametrize("method,params,name", [ + ("tools/call", {"name": "echo", "arguments": {}}, "echo"), + ("resources/read", {"uri": "probe://info"}, "probe://info"), + ("prompts/get", {"name": "greet"}, "greet"), +]) +@pytest.mark.parametrize("fault", ["missing-method", "wrong-method", "missing-name", "wrong-name"]) +def test_official_transport_enforces_method_and_name_headers(era, method, params, name, fault): + with http_client(era) as (_, _, client): + outgoing = headers(method, name=name) + if fault == "missing-method": + outgoing.pop("Mcp-Method") + elif fault == "wrong-method": + outgoing["Mcp-Method"] = "tools/list" + elif fault == "missing-name": + outgoing.pop("Mcp-Name") + else: + outgoing["Mcp-Name"] = "wrong" + response = client.post("/mcp", headers=outgoing, json=envelope(method, params)) + assert response.status_code == 400, response.text + assert decode(response)["error"]["code"] == -32020 + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +@pytest.mark.parametrize("method,params", [ + ("tools/list", {}), ("tools/call", {"name": "echo", "arguments": {"value": "hello"}}), + ("resources/list", {}), ("resources/templates/list", {}), + ("resources/read", {"uri": "wire://info"}), + ("prompts/list", {}), ("prompts/get", {"name": "greet"}), +]) +@pytest.mark.parametrize("json_response", [True, False]) +def test_complete_results_use_native_result_type_and_preserve_metadata(era, method, params, json_response): + with http_client(era, app=wire_app(era), json_response=json_response) as (_, _, client): + response = post(client, method, params) + assert response.status_code == 200, response.text + result = decode(response)["result"] + assert result["resultType"] == "complete" + assert result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"] == "wire-test" + if method == "tools/call": + assert result["content"][0]["text"] == "hello" + assert result["_meta"]["application/example"] == "preserved" + if method in ("tools/list", "resources/list", "prompts/list"): + assert MCP_CACHE_HINT_KEY in result["_meta"] + if method == "resources/templates/list": + assert result["resourceTemplates"][0]["uriTemplate"] == "wire://items/{item}" + assert "mcp-session-id" not in response.headers + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_discovery_uses_one_builder_and_does_not_advertise_unimplemented_tasks(era): + app = wire_app(era) + direct = app.handle_server_discover() + assert direct["_meta"]["serverInfo"] == {"name": "wire-test", "version": "1.2.3"} + assert "io.modelcontextprotocol/tasks" not in direct["capabilities"].get("extensions", {}) + with http_client(era, app=app) as (_, _, client): + response = post(client, "server/discover") + result = decode(response)["result"] + assert result["_meta"]["serverInfo"] == direct["_meta"]["serverInfo"] + assert result["resultType"] == "complete" + assert "io.modelcontextprotocol/tasks" not in result["capabilities"].get("extensions", {}) + + +def test_auto_still_accepts_legacy_initialization_and_tool_calls(): + with http_client("auto") as (_, _, client): + initialized = post(client, "initialize", { + "protocolVersion": LEGACY_PROTOCOL_VERSION, "capabilities": {}, + "clientInfo": {"name": "legacy", "version": "1"}, + }, modern=False, version=LEGACY_PROTOCOL_VERSION) + assert "result" in decode(initialized) + called = post(client, "tools/call", {"name": "echo", "arguments": {"value": "legacy"}}, + modern=False, version=LEGACY_PROTOCOL_VERSION) + assert decode(called)["result"]["structuredContent"]["value"] == "legacy" + + +def test_missing_client_capability_code_is_public_for_the_tasks_followup(): + # Definition/export only: live capability failures belong to the tasks issue. + from nitrostack.protocol import JsonRpcErrorCode as PublicCodes + code = PublicCodes.MISSING_REQUIRED_CLIENT_CAPABILITY + assert int(code) == -32021 + assert ERROR_CODE_MESSAGES[code] == "Missing required client capability" + + +def test_header_rejection_never_reads_or_dispatches_the_body(): + async def scenario(): + async def forbidden(*args): + raise AssertionError("A missing-version rejection must not read or dispatch JSON-RPC") + sent = [] + async def send(message): + sent.append(message) + await HeaderCompatMiddleware(forbidden, require_protocol_version=True)( + {"type": "http", "method": "POST", "headers": []}, forbidden, send, + ) + assert sent[0]["status"] == 400 + asyncio.run(scenario()) + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_duplicate_version_headers_reach_official_rejection(era): + with http_client(era) as (_, _, client): + outgoing = list(headers().items()) + [("MCP-Protocol-Version", LEGACY_PROTOCOL_VERSION)] + response = client.post("/mcp", headers=outgoing, json=envelope()) + assert response.status_code == 400, response.text + assert "result" not in decode(response) + + +def test_auto_modern_envelope_cannot_bypass_version_header_requirement(): + with http_client("auto") as (_, _, client): + response = client.post("/mcp", headers={"Accept": "application/json, text/event-stream"}, + json=envelope()) + assert decode(response)["error"]["code"] == -32020 + + +def test_fresh_server_and_mrtr_results_have_correct_policy_before_http_startup(): + app = make_app("modern") + try: + server = app.create_configured_mcp_server() + assert isinstance(server, NitroStackMcpServer) and server.protocol_era == "modern" + with pytest.raises(MCPError) as exc: + asyncio.run(server._handle_ping(None, None)) + assert exc.value.error.code == -32601 + result = app._to_call_tool_result(types.CallToolResult(content=[], resultType="input_required")) + assert result.result_type == "input_required" + finally: + DIContainer.reset() diff --git a/tests/test_mcp25_hide_tasks.py b/tests/test_mcp25_hide_tasks.py new file mode 100644 index 0000000..0043e7d --- /dev/null +++ b/tests/test_mcp25_hide_tasks.py @@ -0,0 +1,220 @@ +"""Issue #25: the partial Tasks surface is hidden on the 2026 wire.""" + +import asyncio +import json + +import httpx +import mcp.types as types +import pytest +from mcp import MCPError +from pydantic import BaseModel + +from nitrostack import ExecutionContext, injectable, module, tool +from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app +from nitrostack.core.di import DIContainer +from nitrostack.core.errors import TaskNotFoundError + + +class TaskInput(BaseModel): + value: str = "" + + +@injectable() +class HideTasksController: + @tool( + name="taskable", + description="taskable", + input_schema=TaskInput, + task_support="optional", + ) + async def taskable(self, input: TaskInput, context: ExecutionContext) -> str: + return "ok" + + +@module(name="hide_tasks", controllers=[HideTasksController]) +class HideTasksModule: + pass + + +def _app(era: str): + @mcp_app(module=HideTasksModule, server=ServerConfig(name="hide-tasks", protocol_era=era)) + class App: + pass + + return asyncio.run(McpApplicationFactory.create(App)) + + +def setup_function() -> None: + DIContainer.reset() + + +def teardown_function() -> None: + DIContainer.reset() + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_capabilities_and_handlers_hide_tasks(era): + app = _app(era) + server = app.mcp_server + assert server is not None + assert server.has_task_support is False + assert server.get_capabilities(protocol_version="2026-07-28").tasks is None + assert types.GetTaskRequest not in server.request_handlers + assert types.CancelTaskRequest not in server.request_handlers + assert types.GetTaskPayloadRequest not in server.request_handlers + + +def test_legacy_keeps_the_existing_in_process_task_handlers(): + app = _app("legacy") + server = app.mcp_server + assert server is not None + assert server.has_task_support is True + assert types.GetTaskRequest in server.request_handlers + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_task_augmented_tool_call_is_rejected_without_creating_a_task(era): + app = _app(era) + + async def run(): + with pytest.raises(MCPError) as exc_info: + await app._call_tool( + "taskable", + {}, + task=types.TaskMetadata(ttl=60_000), + ) + assert getattr(exc_info.value, "error", None).code == types.INVALID_PARAMS + with pytest.raises(TaskNotFoundError): + await app.task_manager.get_task("task_does_not_exist") + + asyncio.run(run()) + + +def _http_request(app, payload: dict, *, extra_headers: dict[str, str] | None = None): + async def run(): + http_app = app.get_combined_app(json_response=True) + transport = httpx.ASGITransport(app=http_app) + async with http_app.router.lifespan_context(http_app): + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + headers = { + "content-type": "application/json", + "accept": "application/json, text/event-stream", + } + headers.update(extra_headers or {}) + return await client.post( + "/mcp", + headers=headers, + content=json.dumps(payload), + ) + + return asyncio.run(run()) + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_discover_does_not_advertise_tasks(era): + response = _http_request( + _app(era), + { + "jsonrpc": "2.0", + "id": 1, + "method": "server/discover", + "params": { + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + } + }, +}, + extra_headers={ + "Mcp-Method": "server/discover", + "MCP-Protocol-Version": "2026-07-28", + }, + ) + assert response.status_code == 200 + body = response.json() + if "error" in body: + # Modern discovery is optional in auto; when present it must still + # agree with the low-level capabilities and never advertise Tasks. + assert body["error"]["code"] == -32601 + return + capabilities = body["result"].get("capabilities", {}) + assert "tasks" not in capabilities + assert "io.modelcontextprotocol/tasks" not in capabilities.get("extensions", {}) + + +@pytest.mark.parametrize("method", ["tasks/get", "tasks/list", "tasks/result", "tasks/cancel"]) +def test_2026_task_methods_are_method_not_found(method): + response = _http_request( + _app("auto"), + {"jsonrpc": "2.0", "id": 1, "method": method, "params": {}}, + ) + assert response.status_code == 200 + body = response.json() + assert body["error"]["code"] == -32601 + + +def test_2026_task_augmented_http_call_is_not_a_task_result(): + response = _http_request( + _app("auto"), + { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "taskable", + "arguments": {}, + "task": {"ttl": 60_000}, + }, + }, + ) + assert response.status_code == 200 + body = response.json() + assert body["error"]["code"] == -32602 + assert "resultType" not in body.get("result", {}) + + +def _tools_list_http(era: str) -> dict: + """Run a real tools/list over the mounted /mcp app and return the tool named ``taskable``.""" + response = _http_request( + _app(era), + { + "jsonrpc": "2.0", "id": 3, "method": "tools/list", + "params": {"_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": {"name": "hide-tasks-test", "version": "1"}, + "io.modelcontextprotocol/clientCapabilities": {}, + }}, + }, + extra_headers={"Mcp-Method": "tools/list", "MCP-Protocol-Version": "2026-07-28"}, + ) + assert response.status_code == 200, response.text + tools = response.json()["result"]["tools"] + return next(t for t in tools if t["name"] == "taskable") + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_tool_definitions_do_not_advertise_task_support(era): + """Regression: tools/list used to keep task_support="optional" while tasks were off.""" + app = _app(era) + for entry in app._tools.values(): + definition = app._build_tool_definition(entry) + assert definition.execution is None + assert "task_support" not in (definition.meta or {}) + assert "taskSupport" not in json.dumps(definition.model_dump(by_alias=True, exclude_none=True)) + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_tools_list_over_http_does_not_advertise_task_support(era): + tool_json = _tools_list_http(era) + assert "execution" not in tool_json + assert "task_support" not in tool_json.get("_meta", {}) + assert "taskSupport" not in json.dumps(tool_json) + + +def test_legacy_tool_definitions_still_advertise_task_support(): + app = _app("legacy") + definitions = {e.config.name: app._build_tool_definition(e) for e in app._tools.values()} + taskable = definitions["taskable"] + assert taskable.execution is not None + assert taskable.execution.task_support == "optional" + assert (taskable.meta or {}).get("task_support") == "optional" diff --git a/tests/test_mcp26_wire.py b/tests/test_mcp26_wire.py new file mode 100644 index 0000000..19ef35c --- /dev/null +++ b/tests/test_mcp26_wire.py @@ -0,0 +1,168 @@ +import asyncio +import json + +import mcp.types as types +import pytest +from mcp import MCPError +from pydantic import BaseModel +from starlette.testclient import TestClient + +from nitrostack import ExecutionContext, injectable, module, tool +from nitrostack.protocol.errors import JsonRpcErrorCode +from nitrostack.testing import NitroTestingModule + +MODERN_VERSION = "2026-07-28" + + +class In(BaseModel): + q: str = "" + + +@injectable() +class C: + @tool(name="alpha", description="first", input_schema=In, task_support="optional") + async def alpha(self, input: In, context: ExecutionContext) -> str: + return "a" + + +@module(name="m", controllers=[C]) +class M: + pass + + +def make_app(monkeypatch, era): + monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", era) + monkeypatch.delenv("MCP_STATELESS", raising=False) + harness = asyncio.run(NitroTestingModule.create(M)) + return harness.app + + +def envelope(extra=None): + meta = { + "io.modelcontextprotocol/protocolVersion": MODERN_VERSION, + "io.modelcontextprotocol/clientCapabilities": {}, + } + params = dict(extra or {}) + params["_meta"] = {**params.get("_meta", {}), **meta} + return params + + +def rpc(client, method, params=None, *, headers=None, id_=1, envelope=True): + base = { + "Accept": "application/json, text/event-stream", + "Content-Type": "application/json", + } + base.update(headers or {}) + p = dict(params or {}) + if envelope: + meta = dict(p.get("_meta") or {}) + meta.setdefault("io.modelcontextprotocol/protocolVersion", MODERN_VERSION) + meta.setdefault("io.modelcontextprotocol/clientCapabilities", {}) + p["_meta"] = meta + body = {"jsonrpc": "2.0", "id": id_, "method": method, "params": p} + return client.post("/mcp", content=json.dumps(body), headers=base) + +def body_of(resp): + ctype = resp.headers.get("content-type", "") + if "text/event-stream" in ctype: + for line in resp.text.splitlines(): + if line.startswith("data:"): + return json.loads(line[5:].strip()) + return {} + try: + return resp.json() + except ValueError: + return {} + + +def modern_headers(method, name=None): + h = {"MCP-Protocol-Version": MODERN_VERSION, "Mcp-Method": method} + if name: + h["Mcp-Name"] = name + return h + + +def error_code(payload): + return (payload.get("error") or {}).get("code") + + +def exc_code(exc): + err = getattr(exc, "error", None) + return getattr(err, "code", getattr(exc, "code", None)) + + +@pytest.mark.parametrize("era", ["modern", "auto"]) +def test_ping_is_method_not_found(monkeypatch, era): + app = make_app(monkeypatch, era) + with TestClient(app.get_combined_app()) as client: + resp = rpc(client, "ping", headers=modern_headers("ping")) + assert error_code(body_of(resp)) == -32601 + +def test_ping_still_answered_on_legacy(monkeypatch): + app = make_app(monkeypatch, "legacy") + app.protocol_era = "legacy" + + async def go(): + entry = app.mcp_server._request_handlers["ping"] + return await entry.handler(None, None) + + result = asyncio.run(go()) + assert isinstance(result, types.EmptyResult) + + +@pytest.mark.parametrize("era", ["modern", "auto"]) +def test_discover_carries_server_info_in_meta(monkeypatch, era): + app = make_app(monkeypatch, era) + with TestClient(app.get_combined_app()) as client: + resp = rpc(client, "server/discover", headers=modern_headers("server/discover")) + assert resp.status_code == 200 + assert "mcp-session-id" not in {k.lower() for k in resp.headers} + result = body_of(resp)["result"] + info = result["_meta"]["io.modelcontextprotocol/serverInfo"] + assert info["name"] and info["version"] + assert result["resultType"] == "complete" + + +def test_discover_keeps_cache_hint_in_meta(monkeypatch): + app = make_app(monkeypatch, "modern") + result = app.handle_server_discover() + assert "io.modelcontextprotocol/serverInfo" in result["_meta"] + assert len(result["_meta"]) >= 2 # serverInfo plus the existing cache hint + + +def test_initialize_is_not_served_on_modern(monkeypatch): + app = make_app(monkeypatch, "modern") + with TestClient(app.get_combined_app()) as client: + resp = rpc( + client, + "initialize", + {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "1"}}, + headers=modern_headers("initialize"), + ) + assert error_code(body_of(resp)) == -32601 + + +def test_tools_call_without_mcp_method_header_fails_closed(monkeypatch): + app = make_app(monkeypatch, "modern") + with TestClient(app.get_combined_app()) as client: + resp = rpc( + client, + "tools/call", + {"name": "alpha", "arguments": {}}, + headers={"MCP-Protocol-Version": MODERN_VERSION}, + ) + assert resp.status_code >= 400 or error_code(body_of(resp)) == -32020 + + +def test_missing_client_capability_code_is_defined(): + assert -32021 in {int(member.value) for member in JsonRpcErrorCode} + + + +def test_task_call_still_works_when_tasks_available(monkeypatch): + app = make_app(monkeypatch, "legacy") + + async def go(): + return await app._call_tool("alpha", {}, task=types.TaskMetadata(ttl=1000)) + + assert isinstance(asyncio.run(go()), types.CreateTaskResult) diff --git a/tests/test_oauth_client.py b/tests/test_oauth_client.py new file mode 100644 index 0000000..0cd6344 --- /dev/null +++ b/tests/test_oauth_client.py @@ -0,0 +1,418 @@ +"""Issue #68 client lifecycle, discovery trust, and single-flight refresh tests.""" + +import asyncio +import base64 +import json +import logging +import traceback +import urllib.error +import urllib.parse +import urllib.request +from unittest.mock import AsyncMock + +import pytest + +from nitrostack import ( + AuthorizationFlow, ClientRegistration, FileTokenStore, MemoryTokenStore, OAuth2Client, + OAuth2ClientConfig, OAuthClientError, StoredToken, get_well_known_metadata_uris, + parse_www_authenticate_header, +) +from nitrostack.auth import cimd +from nitrostack.auth.pkce import generate_code_challenge, is_valid_code_verifier + +from tests.support.oauth_client import ( + ACCESS, REFRESH, SECRET, ENDPOINT, client, install_transport, response, saved, +) + + +@pytest.mark.asyncio +async def test_client_credentials_are_encoded_saved_and_redacted(monkeypatch): + oauth = client() + send = install_transport(monkeypatch, oauth, response({"access_token": ACCESS, "refresh_token": REFRESH})) + result = await oauth.get_client_credentials_token("alice", scope="read", resource="https://resource.example") + assert isinstance(result, StoredToken) and await oauth.store.get_token("alice") == result + request = send.call_args.args[0] + params = urllib.parse.parse_qs(request.body.decode()) + assert params == {"grant_type": ["client_credentials"], "client_id": ["client:id"], + "scope": ["read"], "resource": ["https://resource.example"]} + assert base64.b64decode(request.headers["Authorization"][6:]).decode() == ( + urllib.parse.quote_plus("client:id", safe="") + ":" + urllib.parse.quote_plus(SECRET, safe="") + ) + assert request.timeout == 10 and request.pinned_ip is None + assert all(secret not in repr(request) + repr(result) + repr(oauth.config) for secret in (ACCESS, REFRESH, SECRET)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("encryption_key", [None, "encryption-key"]) +async def test_client_persists_and_refreshes_after_file_store_reopening(tmp_path, monkeypatch, encryption_key): + path = tmp_path / "tokens.json" + config = OAuth2ClientConfig(client_id="client", client_secret=SECRET, token_endpoint=ENDPOINT) + oauth = OAuth2Client(config, store=FileTokenStore(path, encryption_key)) + install_transport(monkeypatch, oauth, response({"access_token": ACCESS, "refresh_token": REFRESH, "expires_in": 0})) + await oauth.get_client_credentials_token("alice", scope="read", resource="https://resource.example") + reopened = OAuth2Client(config, store=FileTokenStore(path, encryption_key)) + install_transport(monkeypatch, reopened, response({"access_token": "replacement"})) + token = await reopened.refresh_token("alice") + assert token.access_token == "replacement" and token.refresh_token == REFRESH + assert token.resource == "https://resource.example" + assert await reopened.store.get_token("alice") == token + + +@pytest.mark.asyncio +async def test_authorization_url_pkce_state_and_public_code_exchange(monkeypatch): + oauth = client(client_secret=None) + flow = await oauth.start_authorization_flow(scope="read", resource="https://resource.example") + second = await oauth.start_authorization_flow() + assert isinstance(flow, AuthorizationFlow) and flow.state != second.state + assert is_valid_code_verifier(flow.code_verifier) + assert generate_code_challenge(flow.code_verifier) == flow.code_challenge + query = urllib.parse.parse_qs(urllib.parse.urlsplit(flow.authorization_url).query) + assert query["state"] == [flow.state] and query["audience"] == ["api"] + assert query["code_challenge_method"] == ["S256"] + assert flow.code_verifier not in flow.authorization_url + assert "scope" not in urllib.parse.parse_qs(urllib.parse.urlsplit(second.authorization_url).query) + assert flow.code_verifier not in repr(flow) and flow.state not in repr(flow) + send = install_transport(monkeypatch, oauth) + token = await oauth.exchange_code_for_token("alice", code="one-time-code", code_verifier=flow.code_verifier) + request = send.call_args.args[0] + assert "Authorization" not in request.headers + assert urllib.parse.parse_qs(request.body.decode())["code_verifier"] == [flow.code_verifier] + assert await oauth.store.get_token("alice") == token + + +@pytest.mark.asyncio +async def test_refresh_is_single_flight_and_preserves_rotation_fields(monkeypatch): + oauth = client() + previous = await saved(oauth) + entered, release = asyncio.Event(), asyncio.Event() + calls = [] + + async def send(request): + calls.append(request) + entered.set() + await release.wait() + return response({"access_token": "replacement"}) + + monkeypatch.setattr(oauth, "_send", send) + tasks = [asyncio.create_task(oauth.refresh_token("alice")) for _ in range(50)] + await asyncio.wait_for(entered.wait(), 2) + await asyncio.sleep(0) + assert len(calls) == 1 + release.set() + results = await asyncio.gather(*tasks) + assert all(result is results[0] for result in results) + assert results[0].access_token == "replacement" + assert results[0].refresh_token == previous.refresh_token + assert results[0].scope == previous.scope and results[0].resource == previous.resource + assert await oauth.store.get_token("alice") == results[0] + assert oauth._refresh_tasks == {} + + +@pytest.mark.asyncio +async def test_different_keys_refresh_independently_and_one_waiter_can_cancel(monkeypatch): + oauth = client() + await saved(oauth, "alice", "alice-refresh") + await saved(oauth, "bob", "bob-refresh") + both_started, release = asyncio.Event(), asyncio.Event() + calls = [] + + async def send(request): + calls.append(urllib.parse.parse_qs(request.body.decode())["refresh_token"][0]) + if len(calls) == 2: + both_started.set() + await release.wait() + return response() + + monkeypatch.setattr(oauth, "_send", send) + cancelled = asyncio.create_task(oauth.refresh_token("alice")) + survivor = asyncio.create_task(oauth.refresh_token("alice")) + bob = asyncio.create_task(oauth.refresh_token("bob")) + await asyncio.wait_for(both_started.wait(), 2) + cancelled.cancel() + with pytest.raises(asyncio.CancelledError): + await cancelled + assert not survivor.done() + release.set() + await asyncio.gather(survivor, bob) + assert sorted(calls) == ["alice-refresh", "bob-refresh"] + + +@pytest.mark.asyncio +async def test_refresh_shared_failure_can_retry_without_losing_credentials(monkeypatch): + oauth = client() + previous = await saved(oauth) + release = asyncio.Event() + calls = [] + + async def send(request): + calls.append(request) + await release.wait() + return response({"error": "invalid_grant", "error_description": ACCESS + REFRESH}, status=400) + + monkeypatch.setattr(oauth, "_send", send) + tasks = [asyncio.create_task(oauth.refresh_token("alice")) for _ in range(20)] + await asyncio.sleep(0) + await asyncio.sleep(0) + release.set() + errors = await asyncio.gather(*tasks, return_exceptions=True) + assert len(calls) == 1 and all(isinstance(error, OAuthClientError) for error in errors) + assert all(error is errors[0] for error in errors) + assert "invalid_grant" in str(errors[0]) and ACCESS not in repr(errors[0]) + assert await oauth.store.get_token("alice") == previous + send = install_transport(monkeypatch, oauth, response({"access_token": "new", "refresh_token": "rotated"})) + result = await oauth.refresh_token("alice") + assert send.await_count == 1 and result.refresh_token == "rotated" + + +@pytest.mark.asyncio +async def test_persistence_failure_does_not_claim_refresh_success(monkeypatch): + oauth = client() + previous = await saved(oauth) + install_transport(monkeypatch, oauth) + monkeypatch.setattr(oauth.store, "save_token", AsyncMock(side_effect=OSError(ACCESS))) + with pytest.raises(OAuthClientError) as exc: + await oauth.refresh_token("alice") + assert ACCESS not in str(exc.value) + assert await oauth.store.get_token("alice") == previous + + +@pytest.mark.asyncio +async def test_revocation_waits_for_refresh_and_removes_rotated_credential(monkeypatch): + oauth = client() + await saved(oauth) + entered, release = asyncio.Event(), asyncio.Event() + revoked = [] + + async def send(request): + if request.url == ENDPOINT: + entered.set() + await release.wait() + return response({"access_token": "new-access", "refresh_token": "new-refresh"}) + revoked.append(urllib.parse.parse_qs(request.body.decode())["token"][0]) + return response(raw=b"") + + monkeypatch.setattr(oauth, "_send", send) + refresh = asyncio.create_task(oauth.refresh_token("alice")) + await asyncio.wait_for(entered.wait(), 2) + revoke = asyncio.create_task(oauth.revoke_token("alice")) + await asyncio.sleep(0) + assert revoked == [] + release.set() + await asyncio.gather(refresh, revoke) + assert revoked == ["new-refresh"] + assert await oauth.store.get_token("alice") is None + + +@pytest.mark.asyncio +async def test_all_waiters_can_cancel_without_leaking_unhandled_failures(monkeypatch): + oauth = client() + await saved(oauth) + entered, release = asyncio.Event(), asyncio.Event() + errors = [] + loop = asyncio.get_running_loop() + original_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda loop, context: errors.append(context)) + + async def send(request): + entered.set() + await release.wait() + raise OSError(ACCESS) + + monkeypatch.setattr(oauth, "_send", send) + try: + waiter = asyncio.create_task(oauth.refresh_token("alice")) + await asyncio.wait_for(entered.wait(), 2) + shared = oauth._refresh_tasks["alice"] + waiter.cancel() + with pytest.raises(asyncio.CancelledError): + await waiter + assert not shared.cancelled() + release.set() + with pytest.raises(OAuthClientError): + await shared + await asyncio.sleep(0) + assert oauth._refresh_tasks == {} and errors == [] + finally: + loop.set_exception_handler(original_handler) + + +@pytest.mark.asyncio +async def test_revocation_success_failure_and_registration(monkeypatch): + oauth = client() + await saved(oauth) + send = install_transport(monkeypatch, oauth, response(raw=b"", status=200)) + await oauth.revoke_token("alice") + assert await oauth.store.get_token("alice") is None + assert urllib.parse.parse_qs(send.call_args.args[0].body.decode())["token"] == [REFRESH] + await saved(oauth) + install_transport(monkeypatch, oauth, response({"error": "invalid_client"}, status=401)) + with pytest.raises(OAuthClientError): + await oauth.revoke_token("alice", token_type_hint="access_token") + assert await oauth.store.get_token("alice") is not None + send = install_transport(monkeypatch, oauth, response({"client_id": "registered", "client_secret": SECRET})) + result = await oauth.register_client({"redirect_uris": ["http://127.0.0.1/callback"]}) + assert isinstance(result, ClientRegistration) and result.client_secret == SECRET + assert SECRET not in repr(result) + assert result.to_dict()["client_secret"] == SECRET + assert json.loads(send.call_args.args[0].body)["redirect_uris"] == ["http://127.0.0.1/callback"] + + +@pytest.mark.asyncio +async def test_errors_logs_and_transport_representations_do_not_leak(monkeypatch, caplog, capsys): + oauth = client() + caplog.set_level(logging.DEBUG) + send = install_transport(monkeypatch, oauth, response({"error": ACCESS, "error_description": SECRET}, status=401)) + with pytest.raises(OAuthClientError) as exc: + await oauth.get_client_credentials_token("alice") + rendered = "".join(traceback.format_exception(exc.type, exc.value, exc.tb)) + logging.getLogger(__name__).debug("client=%r config=%r request=%r error=%r", oauth, oauth.config, + send.call_args.args[0], exc.value) + output = rendered + caplog.text + str(capsys.readouterr()) + assert all(secret not in output for secret in (ACCESS, REFRESH, SECRET)) + install_transport(monkeypatch, oauth, OSError(ACCESS + SECRET)) + with pytest.raises(OAuthClientError) as exc: + await oauth.get_client_credentials_token("alice") + assert all(secret not in "".join(traceback.format_exception(exc.type, exc.value, exc.tb)) for secret in (ACCESS, SECRET)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("raw", [b"not-json", b"[]", b"null", b'{}', b'{"access_token":null}', + b'{"access_token":"token","expires_in":-1}']) +async def test_invalid_token_responses_are_not_saved(monkeypatch, raw): + oauth = client() + install_transport(monkeypatch, oauth, response(raw=raw)) + with pytest.raises(OAuthClientError): + await oauth.get_client_credentials_token("alice") + assert await oauth.store.list_keys() == [] + + +@pytest.mark.asyncio +async def test_discovery_pins_unknown_urls_and_does_not_require_pkce_for_client_credentials(monkeypatch): + oauth = OAuth2Client({"client_id": "client", "client_secret": SECRET, "issuer": "https://issuer.example"}) + safe = AsyncMock(return_value="8.8.8.8") + monkeypatch.setattr(cimd, "assert_safe_fetch_target", safe) + metadata = {"issuer": "https://issuer.example", "token_endpoint": ENDPOINT, + "authorization_endpoint": "https://issuer.example/authorize"} + send = install_transport(monkeypatch, oauth, response(metadata), response()) + assert await oauth.discover_authorization_server_metadata() == metadata + result = await oauth.get_client_credentials_token("alice") + assert result.access_token == ACCESS + assert safe.await_count == 2 + assert all(call.args[0].pinned_ip == "8.8.8.8" for call in send.call_args_list) + with pytest.raises(OAuthClientError, match="PKCE"): + await oauth.start_authorization_flow(redirect_uri="http://127.0.0.1/callback") + + +@pytest.mark.asyncio +async def test_discovery_failure_preserves_previous_metadata_and_explicit_endpoint_wins(monkeypatch): + oauth = client() + monkeypatch.setattr(cimd, "assert_safe_fetch_target", AsyncMock(return_value="8.8.8.8")) + valid = {"issuer": "https://issuer.example", "token_endpoint": "https://discovered.example/token"} + send = install_transport(monkeypatch, oauth, response(valid)) + await oauth.discover_authorization_server_metadata() + assert oauth._endpoint("token_endpoint") == ENDPOINT + install_transport(monkeypatch, oauth, response({"issuer": "https://wrong.example"}), + response(raw=b"[]")) + with pytest.raises(OAuthClientError): + await oauth.discover_authorization_server_metadata() + assert oauth._metadata == valid + + +@pytest.mark.asyncio +async def test_protected_resource_challenge_and_well_known_fallback(monkeypatch): + oauth = client() + safe = AsyncMock(return_value="8.8.8.8") + monkeypatch.setattr(cimd, "assert_safe_fetch_target", safe) + resource = "https://resource.example/reports" + metadata = {"resource": resource, "authorization_servers": ["https://issuer.example"]} + send = install_transport(monkeypatch, oauth, + response({}, status=401, headers={"WWW-Authenticate": 'Bearer resource_metadata="https://metadata.example/info"'}), + response(metadata)) + assert await oauth.discover_protected_resource_metadata(resource) == metadata + assert send.call_args_list[1].args[0].url == "https://metadata.example/info" + send = install_transport(monkeypatch, oauth, response({}, status=404), response(metadata)) + assert await oauth.discover_protected_resource_metadata(resource) == metadata + assert send.call_args_list[1].args[0].url.endswith("/.well-known/oauth-protected-resource/reports") + + +@pytest.mark.asyncio +async def test_operator_configured_loopback_metadata_avoids_ssrf_exception_flags(monkeypatch): + issuer = "http://127.0.0.1:9876" + oauth = OAuth2Client({"issuer": issuer, "token_endpoint": issuer + "/token", + "authorization_server_metadata_url": issuer + "/.well-known/oauth-authorization-server"}) + guard = AsyncMock(side_effect=AssertionError("must not fetch untrusted URLs")) + monkeypatch.setattr(cimd, "assert_safe_fetch_target", guard) + send = install_transport(monkeypatch, oauth, response({"issuer": issuer, "token_endpoint": issuer + "/token"})) + await oauth.discover_authorization_server_metadata() + guard.assert_not_called() + assert send.call_args.args[0].pinned_ip is None + + +@pytest.mark.asyncio +async def test_untrusted_private_dns_is_rejected_before_credentials_are_sent(monkeypatch): + oauth = client(token_endpoint=None) + oauth._metadata = {"token_endpoint": "https://internal.example/token"} + monkeypatch.setattr(cimd.socket, "getaddrinfo", lambda *args, **kwargs: [(2, 1, 6, "", ("10.0.0.1", 0))]) + send = install_transport(monkeypatch, oauth) + with pytest.raises(OAuthClientError): + await oauth.get_client_credentials_token("alice") + send.assert_not_called() + + +def test_metadata_helpers_and_snake_case_only(): + assert get_well_known_metadata_uris("https://resource.example/reports") == [ + "https://resource.example/.well-known/oauth-protected-resource/reports", + "https://resource.example/.well-known/oauth-protected-resource", + ] + parsed = parse_www_authenticate_header('Basic realm="other", bEaReR realm="a,b", resource_metadata="https://safe.example/info"') + assert parsed["realm"] == "a,b" and parsed["resource_metadata"] == "https://safe.example/info" + assert parse_www_authenticate_header('Basic realm="other"') is None + assert not hasattr(client(), "refreshToken") + assert not hasattr(MemoryTokenStore(), "getToken") + + +@pytest.mark.asyncio +async def test_supplied_state_and_discovered_pkce_support(monkeypatch): + oauth = client() + oauth._metadata = {"code_challenge_methods_supported": ["S256"]} + flow = await oauth.start_authorization_flow(state="caller-state") + assert flow.state == "caller-state" and flow.code_challenge_method == "S256" + with pytest.raises(OAuthClientError): + await oauth.start_authorization_flow(state="") + with pytest.raises(OAuthClientError): + await oauth.exchange_code_for_token("alice", code="code", code_verifier="bad") + with pytest.raises(OAuthClientError): + await oauth.refresh_token("missing") + with pytest.raises(OAuthClientError): + await oauth.refresh_token("") + assert isinstance(OAuth2Client({}).store, MemoryTokenStore) + + +@pytest.mark.asyncio +async def test_configured_protected_metadata_and_failed_document_do_not_leak(monkeypatch): + metadata_url = "https://operator.example/resource-metadata" + oauth = client(protected_resource_metadata_url=metadata_url) + guard = AsyncMock(side_effect=AssertionError("operator endpoint must be trusted")) + monkeypatch.setattr(cimd, "assert_safe_fetch_target", guard) + metadata = {"resource": "https://resource.example/", "authorization_servers": ["https://issuer.example"]} + send = install_transport(monkeypatch, oauth, response(metadata)) + assert await oauth.discover_protected_resource_metadata("https://resource.example/") == metadata + assert send.call_args.args[0].url == metadata_url + guard.assert_not_called() + install_transport(monkeypatch, oauth, response({"resource": "https://wrong.example/"})) + with pytest.raises(OAuthClientError): + await oauth.discover_protected_resource_metadata("https://resource.example/") + + +@pytest.mark.parametrize("options", [{"timeout_seconds": 0}, {"timeout_seconds": float("inf")}, + {"max_response_bytes": 0}, {"max_response_bytes": True}]) +def test_invalid_client_limits(options): + with pytest.raises(OAuthClientError): + OAuth2Client({}, **options) + + +@pytest.mark.parametrize("url", ["http://public.example/token", "https://user:secret@public.example/token", + "https://public.example/token#fragment", "https://public.example:bad/token"]) +def test_invalid_operator_url_is_rejected(url): + with pytest.raises(OAuthClientError): + client(token_endpoint=url) diff --git a/tests/test_oauth_client_followups.py b/tests/test_oauth_client_followups.py new file mode 100644 index 0000000..187b7f4 --- /dev/null +++ b/tests/test_oauth_client_followups.py @@ -0,0 +1,242 @@ +"""OAuth usability, revocation fallback, and automatic refresh regressions.""" + +import asyncio +from unittest.mock import AsyncMock + +import pytest + +from nitrostack import OAuthClientError, StoredToken +from tests.support.oauth_client import ( + ACCESS, REFRESH, SECRET, client, install_transport, response, saved, +) + + +@pytest.mark.asyncio +async def test_secret_wrapper_deferred_unwrap(monkeypatch, caplog, capsys): + import pickle + from nitrostack import SecretValue + secret = SecretValue(SECRET) + original = SecretValue.unwrap + calls = [] + def unwrap(self): + calls.append(1) + return original(self) + monkeypatch.setattr(SecretValue, "unwrap", unwrap) + oauth = client(client_secret=secret) + assert oauth.config.client_secret is secret and calls == [] + send = install_transport(monkeypatch, oauth) + await oauth.get_client_credentials_token("alice") + assert len(calls) == 1 + plain = client() + plain_send = install_transport(monkeypatch, plain) + await plain.get_client_credentials_token("alice") + assert send.call_args.args[0].headers == plain_send.call_args.args[0].headers + for unusable in (pickle.loads(pickle.dumps(secret)),): + broken = client(client_secret=unusable) + transport = install_transport(monkeypatch, broken) + with pytest.raises(OAuthClientError) as exc: + await broken.get_client_credentials_token("alice") + transport.assert_not_awaited() + assert SECRET not in str(exc.value) + repr(exc.value) + assert SECRET not in repr(oauth.config) + caplog.text + str(capsys.readouterr()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["missing", "http", "network"]) +@pytest.mark.parametrize("fallback", [False, True]) +async def test_local_revocation_fallback(monkeypatch, failure, fallback): + oauth = client(revocation_endpoint=None) if failure == "missing" else client() + previous = await saved(oauth) + send = install_transport(monkeypatch, oauth, response({"error": "server_error"}, status=500)) + if failure == "network": + send.side_effect = OSError(SECRET) + if fallback: + await oauth.revoke_token("alice", local_fallback=True) + assert await oauth.store.get_token("alice") is None + else: + with pytest.raises(OAuthClientError): + await oauth.revoke_token("alice") + assert await oauth.store.get_token("alice") == previous + assert send.await_count == (0 if failure == "missing" else 1) + + +@pytest.mark.asyncio +async def test_fallback_does_not_hide_validation_storage_or_cancellation(monkeypatch): + oauth = client(revocation_endpoint=None) + previous = await saved(oauth) + with pytest.raises(OAuthClientError): + await oauth.revoke_token("alice", token_type_hint="bad", local_fallback=True) + assert await oauth.store.get_token("alice") == previous + monkeypatch.setattr(oauth.store, "delete_token", AsyncMock(side_effect=OSError(SECRET))) + with pytest.raises(OAuthClientError) as exc: + await oauth.revoke_token("alice", local_fallback=True) + assert SECRET not in str(exc.value) + oauth = client() + previous = await saved(oauth) + send = install_transport(monkeypatch, oauth) + send.side_effect = asyncio.CancelledError() + with pytest.raises(asyncio.CancelledError): + await oauth.revoke_token("alice", local_fallback=True) + assert await oauth.store.get_token("alice") == previous + + +@pytest.mark.asyncio +async def test_get_access_token_boundaries_and_explicit_refresh(monkeypatch): + monkeypatch.setattr("nitrostack.auth.token_store.time.time", lambda: 1000) + oauth = client() + send = install_transport(monkeypatch, oauth) + await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 1030001, REFRESH)) + assert await oauth.get_access_token("alice") == ACCESS + send.assert_not_awaited() + await oauth.refresh_token("alice") + assert send.await_count == 1 + await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 1030000, REFRESH)) + await oauth.get_access_token("alice") + assert send.await_count == 2 + with pytest.raises(OAuthClientError): + await oauth.get_access_token("missing") + await saved(oauth, refresh=None) + with pytest.raises(OAuthClientError): + await oauth.get_access_token("alice") + + +@pytest.mark.asyncio +async def test_get_access_token_coalesces_cancellation_and_delayed_read(monkeypatch): + oauth = client() + await saved(oauth) + entered, release = asyncio.Event(), asyncio.Event() + calls = [] + async def send(request): + calls.append(request) + entered.set() + await release.wait() + return response({"access_token": "new", "refresh_token": "rotated"}) + monkeypatch.setattr(oauth, "_send", send) + tasks = [asyncio.create_task(oauth.get_access_token("alice")) for _ in range(50)] + await asyncio.wait_for(entered.wait(), 2) + tasks[0].cancel() + with pytest.raises(asyncio.CancelledError): + await tasks[0] + release.set() + assert await asyncio.gather(*tasks[1:]) == ["new"] * 49 + assert await oauth.get_access_token("alice") == "new" + assert len(calls) == 1 + assert oauth._refresh_tasks == {} and oauth._force_refresh == {} + assert (await oauth.store.get_token("alice")).refresh_token == "rotated" + + +@pytest.mark.asyncio +async def test_auto_refresh_rechecks_after_lock_and_explicit_call_forces(monkeypatch): + oauth = client() + send = install_transport(monkeypatch, oauth) + await saved(oauth) + lock = oauth._key_lock("alice") + async with lock: + pending = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.sleep(0) + await oauth.store.save_token("alice", StoredToken("fresh", "Bearer", 10**15, REFRESH)) + assert await pending == "fresh" + send.assert_not_awaited() + async with lock: + automatic = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.sleep(0) + explicit = asyncio.create_task(oauth.refresh_token("alice")) + await asyncio.sleep(0) + await asyncio.gather(automatic, explicit) + assert send.await_count == 1 + + +@pytest.mark.asyncio +async def test_get_access_token_failure_retry_and_persistence(monkeypatch): + oauth = client() + previous = await saved(oauth) + install_transport(monkeypatch, oauth, response({"error": "invalid_grant"}, status=400)) + with pytest.raises(OAuthClientError): + await oauth.get_access_token("alice") + assert await oauth.store.get_token("alice") == previous + send = install_transport(monkeypatch, oauth) + monkeypatch.setattr(oauth.store, "save_token", AsyncMock(side_effect=OSError(SECRET))) + with pytest.raises(OAuthClientError): + await oauth.get_access_token("alice") + assert send.await_count == 1 and await oauth.store.get_token("alice") == previous + +@pytest.mark.asyncio +async def test_explicit_refresh_during_slow_valid_token_read(monkeypatch): + oauth = client() + await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 10**15, REFRESH)) + entered, release = asyncio.Event(), asyncio.Event() + original = oauth.store.get_token + async def slow_read(key): + entered.set() + await release.wait() + return await original(key) + monkeypatch.setattr(oauth.store, "get_token", slow_read) + send = install_transport(monkeypatch, oauth) + automatic = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.wait_for(entered.wait(), 2) + explicit = asyncio.create_task(oauth.refresh_token("alice")) + await asyncio.sleep(0) + release.set() + await asyncio.gather(automatic, explicit) + assert send.await_count == 1 + + +@pytest.mark.asyncio +async def test_local_fallback_waits_for_active_refresh(monkeypatch): + oauth = client(revocation_endpoint=None) + await saved(oauth) + entered, release = asyncio.Event(), asyncio.Event() + async def send(request): + entered.set() + await release.wait() + return response({"access_token": "rotated-access", "refresh_token": "rotated-refresh"}) + monkeypatch.setattr(oauth, "_send", send) + pending = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.wait_for(entered.wait(), 2) + revoke = asyncio.create_task(oauth.revoke_token("alice", local_fallback=True)) + await asyncio.sleep(0) + assert not revoke.done() + release.set() + await asyncio.gather(pending, revoke) + assert await oauth.store.get_token("alice") is None + + +@pytest.mark.asyncio +async def test_helper_shared_failures_independent_keys_and_retry(monkeypatch): + oauth = client() + await saved(oauth) + await saved(oauth, "bob") + entered, release = asyncio.Event(), asyncio.Event() + count = 0 + async def send(request): + nonlocal count + count += 1 + if count == 2: + entered.set() + await release.wait() + return response({"error": "invalid_grant", "error_description": SECRET}, status=400) + monkeypatch.setattr(oauth, "_send", send) + tasks = [asyncio.create_task(oauth.get_access_token("alice")) for _ in range(20)] + tasks.append(asyncio.create_task(oauth.get_access_token("bob"))) + await asyncio.wait_for(entered.wait(), 2) + release.set() + results = await asyncio.gather(*tasks, return_exceptions=True) + assert count == 2 and all(isinstance(result, OAuthClientError) for result in results) + assert all(result is results[0] for result in results[:20]) + assert SECRET not in repr(results) + assert oauth._refresh_tasks == {} and oauth._force_refresh == {} + install_transport(monkeypatch, oauth) + assert await oauth.get_access_token("alice") == ACCESS + + +@pytest.mark.asyncio +async def test_helper_rejects_immediately_expired_replacement_and_storage_failure(monkeypatch): + oauth = client() + await saved(oauth) + install_transport(monkeypatch, oauth, response({"access_token": ACCESS, "expires_in": "0"})) + with pytest.raises(OAuthClientError, match="expiry"): + await oauth.get_access_token("alice") + monkeypatch.setattr(oauth.store, "get_token", AsyncMock(side_effect=OSError(SECRET))) + with pytest.raises(OAuthClientError) as exc: + await oauth.get_access_token("alice") + assert SECRET not in str(exc.value) diff --git a/tests/test_oauth_client_transport.py b/tests/test_oauth_client_transport.py new file mode 100644 index 0000000..8006bc9 --- /dev/null +++ b/tests/test_oauth_client_transport.py @@ -0,0 +1,177 @@ +"""Exercise the urllib seam, DNS pins, TLS identity, and bounded IO.""" + +import asyncio +import io +import ssl +import threading +import traceback +import urllib.error +import urllib.request +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from nitrostack import OAuth2Client, OAuthClientError +from nitrostack.auth import cimd +from nitrostack.auth.client import _Response + +ENDPOINT = "https://issuer.example:8443/token" +SECRET = "TRANSPORT_SENTINEL_DO_NOT_LOG" + + +class WireResponse(io.BytesIO): + def __init__(self, body, *, status=200, headers=None): + super().__init__(body) + self.code = status + self.headers = headers or {} + + +def make_client(**limits): + return OAuth2Client({"client_id": "client", "client_secret": SECRET, "token_endpoint": ENDPOINT}, **limits) + + +@pytest.mark.asyncio +async def test_real_urllib_seam_carries_form_headers_and_timeout(monkeypatch): + oauth = make_client(timeout_seconds=4) + opener = MagicMock() + opener.open.return_value = WireResponse(b'{"access_token":"ok"}') + builder = MagicMock(return_value=opener) + monkeypatch.setattr(cimd, "_build_fetch_opener", builder) + result = await oauth.get_client_credentials_token("alice") + assert result.access_token == "ok" + outgoing = opener.open.call_args.args[0] + assert outgoing.full_url == ENDPOINT and outgoing.get_method() == "POST" + assert outgoing.get_header("Content-type") == "application/x-www-form-urlencoded" + assert outgoing.get_header("Authorization").startswith("Basic ") + assert opener.open.call_args.kwargs["timeout"] == 4 + builder.assert_called_once_with(ENDPOINT, None) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("body,headers", [ + (b"x" * 33, {}), (b"{}", {"Content-Length": "33"}), + (b"{}", {"Content-Length": "-1"}), (b"{}", {"Content-Length": "not-a-number"}), +]) +async def test_urllib_limits_response_before_parsing(monkeypatch, body, headers): + oauth = make_client(max_response_bytes=32) + opener = MagicMock() + opener.open.return_value = WireResponse(body, headers=headers) + monkeypatch.setattr(cimd, "_build_fetch_opener", lambda *args: opener) + with pytest.raises(OAuthClientError): + await oauth.get_client_credentials_token("alice") + assert await oauth.store.list_keys() == [] + + +@pytest.mark.asyncio +async def test_async_fake_transport_cannot_bypass_response_limit(monkeypatch): + oauth = make_client(max_response_bytes=32) + monkeypatch.setattr(oauth, "_send", AsyncMock(return_value=_Response(200, {}, b"x" * 33))) + with pytest.raises(OAuthClientError, match="response size"): + await oauth.get_client_credentials_token("alice") + + +@pytest.mark.asyncio +async def test_blocking_transport_runs_on_worker_thread(monkeypatch): + oauth = make_client() + loop = asyncio.get_running_loop() + entered, release = asyncio.Event(), threading.Event() + thread_ids = [] + + def blocking(request): + thread_ids.append(threading.get_ident()) + loop.call_soon_threadsafe(entered.set) + assert release.wait(3) + return _Response(200, {}, b'{"access_token":"ok"}') + + monkeypatch.setattr(oauth, "_send_sync", blocking) + task = asyncio.create_task(oauth.get_client_credentials_token("alice")) + try: + await asyncio.wait_for(entered.wait(), 2) + assert thread_ids == [thread_ids[0]] and thread_ids[0] != threading.get_ident() + finally: + release.set() + await task + + +@pytest.mark.asyncio +async def test_timeout_and_http_error_bodies_are_sanitized(monkeypatch): + oauth = make_client() + opener = MagicMock() + monkeypatch.setattr(cimd, "_build_fetch_opener", lambda *args: opener) + for failure in [TimeoutError(SECRET), urllib.error.HTTPError( + ENDPOINT + "?token=" + SECRET, 401, SECRET, {}, + io.BytesIO(b'{"error":"invalid_client","error_description":"' + SECRET.encode() + b'"}'), + )]: + opener.open.side_effect = failure + with pytest.raises(OAuthClientError) as exc: + await oauth.get_client_credentials_token("alice") + rendered = "".join(traceback.format_exception(exc.type, exc.value, exc.tb)) + assert SECRET not in rendered + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [301, 302, 303, 307, 308]) +async def test_redirect_responses_are_terminal_not_followed(monkeypatch, status): + oauth = make_client() + send = AsyncMock(return_value=_Response(status, {"Location": "http://127.0.0.1/private"}, b"")) + monkeypatch.setattr(oauth, "_send", send) + with pytest.raises(OAuthClientError) as exc: + await oauth.get_client_credentials_token("alice") + assert exc.value.status == status and send.await_count == 1 + request = urllib.request.Request(ENDPOINT) + with pytest.raises(urllib.error.HTTPError): + cimd._NoRedirectHandler().redirect_request(request, None, status, "redirect", {}, "http://127.0.0.1/private") + + +@pytest.mark.asyncio +async def test_untrusted_target_uses_checked_ip_and_disables_proxy_redirection(monkeypatch): + oauth = OAuth2Client({"client_id": "client", "client_secret": SECRET}) + oauth._metadata = {"token_endpoint": ENDPOINT} + guard = AsyncMock(return_value="8.8.8.8") + monkeypatch.setattr(cimd, "assert_safe_fetch_target", guard) + send = AsyncMock(return_value=_Response(200, {}, b'{"access_token":"ok"}')) + monkeypatch.setattr(oauth, "_send", send) + await oauth.get_client_credentials_token("alice") + guard.assert_awaited_once_with(ENDPOINT, require_non_root_path=False) + assert send.call_args.args[0].pinned_ip == "8.8.8.8" + builder = MagicMock() + monkeypatch.setattr(urllib.request, "build_opener", builder) + cimd._build_fetch_opener(ENDPOINT, "8.8.8.8") + handlers = builder.call_args.args + assert any(isinstance(handler, cimd._NoRedirectHandler) for handler in handlers) + assert any(isinstance(handler, urllib.request.ProxyHandler) and handler.proxies == {} for handler in handlers) + secure = next(handler for handler in handlers if isinstance(handler, cimd._PinnedHTTPSHandler)) + assert secure._hostname == "issuer.example" and secure._port == 8443 + + +def test_pinned_tls_connection_keeps_port_and_hostname(monkeypatch): + sock = MagicMock() + sock.getpeername.return_value = ("8.8.8.8", 8443) + connect = MagicMock(return_value=sock) + monkeypatch.setattr(cimd.socket, "create_connection", connect) + context = ssl.create_default_context() + assert context.check_hostname and context.verify_mode == ssl.CERT_REQUIRED + wrap = MagicMock(return_value=sock) + monkeypatch.setattr(context, "wrap_socket", wrap) + connection = cimd._PinnedHTTPSConnection("issuer.example", "8.8.8.8", port=8443, context=context) + connection.connect() + assert connect.call_args.args[0] == ("8.8.8.8", 8443) + wrap.assert_called_once_with(sock, server_hostname="issuer.example") + sock.getpeername.return_value = ("127.0.0.1", 8443) + with pytest.raises(cimd.CimdFetchError): + connection.connect() + assert sock.close.called + + +@pytest.mark.asyncio +async def test_generic_root_url_validation_does_not_weaken_cimd(monkeypatch): + url = "https://public.example/" + assert cimd.validate_fetch_url(url) == url + with pytest.raises(cimd.CimdValidationError, match="non-root"): + cimd.validate_client_identifier_url(url) + with pytest.raises(cimd.CimdValidationError, match="non-root"): + await cimd.assert_safe_fetch_target(url) + monkeypatch.setattr(cimd.socket, "getaddrinfo", lambda *args, **kwargs: [(2, 1, 6, "", ("8.8.8.8", 0))]) + assert await cimd.assert_safe_fetch_target(url, require_non_root_path=False) == "8.8.8.8" + with pytest.raises(cimd.CimdValidationError): + cimd.validate_fetch_url("https://public.example/%2e%2e/private") diff --git a/tests/test_oauth_discovery.py b/tests/test_oauth_discovery.py index 55b5d88..6fa12d7 100644 --- a/tests/test_oauth_discovery.py +++ b/tests/test_oauth_discovery.py @@ -94,3 +94,162 @@ def test_warn_if_oauth_fail_open_writes_once(monkeypatch, capsys): assert "OAuth is configured" in err assert oauth._oauth_fail_open_warned is True oauth._oauth_fail_open_warned = False + + +def test_discovery_server_busy_port_with_retry(capsys): + port = _free_port() + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + blocker.bind(("127.0.0.1", port)) + blocker.listen(1) + + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + service.start_discovery_server() + assert service.bound_port is not None + assert service.bound_port != port + assert service.get_port() == service.bound_port + assert service._server is not None + + err = capsys.readouterr().err + assert f'"port": {service.bound_port}' in err + + with urllib.request.urlopen( + f"http://127.0.0.1:{service.bound_port}/.well-known/oauth-protected-resource", + timeout=1.0, + ) as resp: + body = json.loads(resp.read().decode("utf-8")) + assert body["resource"] == "http://localhost:3000/mcp" + finally: + service.stop_discovery_server() + blocker.close() + + +def test_discovery_server_retries_exhausted(capsys): + import pytest + + port = _free_port() + blockers = [] + for p in (port, port + 1): + b = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + b.bind(("127.0.0.1", p)) + b.listen(1) + blockers.append(b) + + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + discovery_max_retries=1, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + with pytest.raises(OSError): + service.start_discovery_server() + assert service._server is None + assert service.bound_port is None + assert service.get_port() is None + err = capsys.readouterr().err + assert f"Failed to start OAuth Discovery Server on port {port}" in err + finally: + service.stop_discovery_server() + for b in blockers: + b.close() + + +def test_discovery_server_auto_retry_disabled_surfaces_bind_failure(capsys, monkeypatch): + import pytest + + port = _free_port() + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + blocker.bind(("127.0.0.1", port)) + blocker.listen(1) + + monkeypatch.setenv("OAUTH_DISCOVERY_AUTO_RETRY", "false") + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + with pytest.raises(OSError): + service.start_discovery_server() + assert service._server is None + assert service.bound_port is None + err = capsys.readouterr().err + assert f"Failed to start OAuth Discovery Server on port {port}" in err + finally: + service.stop_discovery_server() + blocker.close() + + +def test_discovery_server_reports_actual_bound_port(capsys): + port = _free_port() + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + service.start_discovery_server() + assert service.bound_port == port + assert service.get_port() == port + err = capsys.readouterr().err + assert f'"port": {port}' in err + finally: + service.stop_discovery_server() + assert service.bound_port is None + assert service.get_port() is None + + +def test_discovery_server_port_overflow_surfaces_oserror(capsys): + import pytest + + port = 65535 + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + blocker.bind(("127.0.0.1", port)) + blocker.listen(1) + except OSError: + pytest.skip("Port 65535 unavailable for test") + + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + discovery_auto_retry=True, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + with pytest.raises(OSError): + service.start_discovery_server() + assert service._server is None + assert service.bound_port is None + err = capsys.readouterr().err + assert f"Failed to start OAuth Discovery Server on port {port}" in err + finally: + service.stop_discovery_server() + blocker.close() + + +def test_discovery_server_invalid_max_retries_falls_back_to_default(monkeypatch): + monkeypatch.setenv("OAUTH_DISCOVERY_MAX_RETRIES", "abc") + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=3005, + ) + service = DIContainer.get_instance().resolve(OAuthService) + assert service.discovery_max_retries == 50 diff --git a/tests/test_pack_include_env.py b/tests/test_pack_include_env.py new file mode 100644 index 0000000..26e1309 --- /dev/null +++ b/tests/test_pack_include_env.py @@ -0,0 +1,50 @@ +"""Pack --include-env behaviour (merged from main).""" + +from __future__ import annotations + +from pathlib import Path +import zipfile + +from nitrostack.cli.pack import pack_project + + +def _mini_project(tmp_path: Path) -> Path: + (tmp_path / "main.py").write_text("VALUE = 1\n", encoding="utf-8") + (tmp_path / "app_module.py").write_text("NAME = 'demo'\n", encoding="utf-8") + (tmp_path / "requirements.txt").write_text("nitrostack\n", encoding="utf-8") + (tmp_path / ".env.example").write_text("PORT=8000\n", encoding="utf-8") + (tmp_path / ".env").write_text("SECRET=should-never-pack\n", encoding="utf-8") + (tmp_path / "notes.txt").write_text("keep me\n", encoding="utf-8") + return tmp_path + + +def test_pack_include_env_dry_run_lists_env_without_printing_contents(tmp_path: Path, capsys): + project = _mini_project(tmp_path) + (project / ".env.local").write_text("TOKEN=local-secret\n", encoding="utf-8") + result = pack_project(str(project), dry_run=True, include_env=True) + assert result["dry_run"] is True + assert ".env" in result["files"] + assert ".env.local" in result["files"] + captured = capsys.readouterr().out + assert "Warning: Including .env files in the wheel (use with caution!)" in captured + assert ".env" in captured + assert ".env.local" in captured + assert "SECRET=should-never-pack" not in captured + assert "TOKEN=local-secret" not in captured + + +def test_pack_include_env_puts_env_in_wheel_without_printing_contents(tmp_path: Path, capsys): + project = _mini_project(tmp_path) + result = pack_project(str(project), dry_run=False, include_env=True) + captured = capsys.readouterr().out + assert "Warning: Including .env files in the wheel (use with caution!)" in captured + assert "SECRET=should-never-pack" not in captured + + wheel = Path(result["wheel"]) + with zipfile.ZipFile(wheel) as zf: + names = zf.namelist() + assert any(n == ".env" or n.endswith("/.env") for n in names) + env_data = next( + zf.read(n).decode("utf-8") for n in names if n == ".env" or n.endswith("/.env") + ) + assert "SECRET=should-never-pack" in env_data \ No newline at end of file diff --git a/tests/test_pr12_review.py b/tests/test_pr12_review.py index b1c1ef0..e701ed7 100644 --- a/tests/test_pr12_review.py +++ b/tests/test_pr12_review.py @@ -40,7 +40,8 @@ def boom(_data): assert "expensive" in text -def test_custom_meta_merges_widget_meta(): +def test_custom_meta_merges_widget_meta(monkeypatch): + monkeypatch.setenv("NITROSTACK_APP_MODE", "universal") host = _Host() component = Component(id="sample", name="Sample", html="

ok

") result = types.CallToolResult( diff --git a/tests/test_project_templates.py b/tests/test_project_templates.py new file mode 100644 index 0000000..fd6f94d --- /dev/null +++ b/tests/test_project_templates.py @@ -0,0 +1,251 @@ +"""Issue #76: real generated projects, CLI lifecycle, and distributable templates.""" +from __future__ import annotations + +import io +import importlib.util +import json +import os +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import shutil +import subprocess +import sys +import sysconfig +import tarfile +import zipfile + +import pytest + +from nitrostack.cli.main import OFFICIAL_TEMPLATES, _prompt_template, _resolve_template + +ROOT = Path(__file__).resolve().parents[1] +PROBE = ROOT / "tests" / "support" / "project_templates_probe.py" +TEMPLATES = [("python-enterprise-search", "enterprise-search"), ("python-code-mode", "code-mode")] +PACK_TEMPLATES = [ + ("python-starter", "starter"), + ("python-pizzaz", "pizzaz"), + ("python-oauth", "flight-booking"), + *TEMPLATES, +] + + +def run(args, cwd, *, python=None, installed=False): + env = dict(os.environ, NITROSTACK_SKIP_UV_LOCK="1", PYTHONIOENCODING="utf-8") + env["PYTHONPATH"] = "" if installed else str(ROOT) + for key in ("NITRO_MCP_PROTOCOL_VERSION", "MCP_STATELESS", "MCP_TRANSPORT_TYPE"): + env.pop(key, None) + result = subprocess.run([str(python or sys.executable), str(PROBE), *args], cwd=cwd, env=env, + input="", text=True, encoding="utf-8", capture_output=True, timeout=45) + assert result.returncode == 0, result.stdout + result.stderr + return result.stdout + + +@pytest.mark.parametrize("choice,expected", [("4", "python-enterprise-search"), ("5", "python-code-mode"), ("python-enterprise-search", "python-enterprise-search"), ("python-code-mode", "python-code-mode")]) +def test_new_template_prompt_choices(choice, expected, monkeypatch): + stdin = io.StringIO(choice + "\n") + stdin.isatty = lambda: True # prompts read only from a TTY + monkeypatch.setattr(sys, "stdin", stdin) + assert _prompt_template() == expected + assert OFFICIAL_TEMPLATES[expected] in {"enterprise-search", "code-mode"} + + +@pytest.mark.parametrize("alias", ["enterprise-search", "code-mode"]) +def test_unprefixed_template_aliases_are_not_accepted(alias): + with pytest.raises(SystemExit): + _resolve_template(alias) + + +def test_new_templates_in_cli_help(tmp_path): + output = run(["cli", "init", "--help"], tmp_path) + assert all(name in output for name, _ in TEMPLATES) + + +@pytest.mark.parametrize("name,kind", PACK_TEMPLATES) +def test_packed_wheel_includes_main_and_app_module(name, kind, tmp_path): + run(["cli", "init", "pack-demo", "--template", name, "--skip-install"], tmp_path) + project = tmp_path / "pack-demo" + run(["cli", "pack"], project) + [wheel] = (project / "dist").glob("*.whl") + with zipfile.ZipFile(wheel) as archive: + names = archive.namelist() + assert "main.py" in names and "app_module.py" in names + + +@pytest.mark.parametrize("name,kind", TEMPLATES) +def test_generated_project_lifecycle(name, kind, tmp_path): + output = run(["cli", "init", "demo", "--template", name, "--skip-install"], tmp_path) + assert "Preview widgets" not in output and "openNow" not in output + project = tmp_path / "demo" + for filename in ("pyproject.toml", "requirements.txt", ".python-version", "uv.toml", "README.md", ".env.example", ".env", ".gitignore", "main.py", "app_module.py"): + assert (project / filename).is_file(), filename + assert (project / ".python-version").read_text().strip() == "3.12" + assert "No issues found" in run(["cli", "validate"], project) + run([kind], project) + if kind == "code-mode": + run(["cleanup"], project) + run(["cli", "upgrade", "--version", "0.4.2", "--allow-downgrade"], project) + assert "No issues found" in run(["cli", "validate"], project) + from nitrostack.cli.vendor import vendored_version + assert vendored_version(str(project)) == "0.4.2" + requirements = (project / "requirements.txt").read_text() + if kind == "code-mode": + assert "quickjs>=1.19.4" in requirements + assert "quickjs>=1.19.4" in (project / "pyproject.toml").read_text() + run(["cli", "pack"], project) + [wheel] = (project / "dist").glob("*.whl") + with zipfile.ZipFile(wheel) as archive: + names = archive.namelist() + assert "main.py" in names and "app_module.py" in names + assert "modules/inventory.py" in names + assert not any(Path(name).name == ".env" for name in names) + if kind == "code-mode": + assert "scripts/sample-batch.js" in names + metadata = archive.read(next(name for name in names if name.endswith(".dist-info/METADATA"))).decode() + assert "Requires-Dist: nitrostack" in metadata + if kind == "code-mode": + assert "quickjs>=1.19.4" in metadata.replace(" ", "") + + +@pytest.mark.parametrize("name,kind", TEMPLATES) +def test_generated_entrypoint_stdio_roundtrip_and_shutdown(name, kind, tmp_path): + run(["cli", "init", "wire-demo", "--template", name, "--skip-install"], tmp_path) + project = tmp_path / "wire-demo" + env = dict(os.environ, PYTHONPATH=str(ROOT), MCP_TRANSPORT_TYPE="stdio", + NITRO_MCP_PROTOCOL_VERSION="auto", PYTHONIOENCODING="utf-8") + env.pop("MCP_STATELESS", None) + process = subprocess.Popen([sys.executable, "main.py"], cwd=project, env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding="utf-8") + reader = ThreadPoolExecutor(max_workers=1) + meta = { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": {"name": "template-wire-test", "version": "1"}, + "io.modelcontextprotocol/clientCapabilities": {}, + } + + def rpc(request_id, method, params): + process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request_id, "method": method, + "params": {**params, "_meta": meta}}) + "\n") + process.stdin.flush() + line = reader.submit(process.stdout.readline).result(timeout=15) + response = json.loads(line) + assert response["id"] == request_id + assert "error" not in response, response + return response["result"] + + try: + listed = rpc(1, "tools/list", {}) + names = {tool["name"] for tool in listed["tools"]} + if kind == "enterprise-search": + assert "search_tools" in names and "finance_list_invoices" not in names + result = rpc(2, "tools/call", {"name": "call_tool", "arguments": { + "name": "finance_list_invoices", "arguments": {"overdue_only": True}, + }}) + assert json.loads(result["content"][0]["text"])["invoices"][0]["id"] == "INV-001" + else: + assert names == {"search", "get_schema", "execute"} + if sys.platform == "win32" and importlib.util.find_spec("quickjs") is None: + result = rpc(2, "tools/call", {"name": "get_schema", "arguments": {"name": "inventory_check_stock"}}) + data = json.loads(result["content"][0]["text"]) + assert data["schemas"]["inventory_check_stock"]["inputSchema"]["required"] == ["sku"] + else: + result = rpc(2, "tools/call", {"name": "execute", "arguments": { + "code": (project / "scripts" / "sample-batch.js").read_text(), + }}) + data = json.loads(result["content"][0]["text"]) + assert data["success"] is True and data["value"]["total_units"] == 18 + process.stdin.close() + assert process.wait(timeout=15) == 0, process.stderr.read() + assert process.stdout.read() == "" + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + reader.shutdown() + for stream in (process.stdin, process.stdout, process.stderr): + stream.close() + + +@pytest.fixture(scope="module") +def sdk_distribution(tmp_path_factory): + base = tmp_path_factory.mktemp("sdk-templates") + source = base / "source" + source.mkdir() + shutil.copytree(ROOT / "nitrostack", source / "nitrostack", ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + for filename in ("pyproject.toml", "README.md", "LICENSE"): + if (ROOT / filename).is_file(): + shutil.copy2(ROOT / filename, source / filename) + dist = base / "dist" + dist.mkdir() + code = "from setuptools.build_meta import build_wheel, build_sdist; import sys; dest = sys.argv[1]; build_wheel(dest); build_sdist(dest)" + result = subprocess.run([sys.executable, "-c", code, str(dist)], cwd=source, capture_output=True, text=True, timeout=60) + assert result.returncode == 0, result.stdout + result.stderr + return base, next(dist.glob("*.whl")), next(dist.glob("*.tar.gz")) + + +def test_sdk_wheel_and_sdist_contain_complete_templates(sdk_distribution): + _, wheel, sdist = sdk_distribution + required = {f"nitrostack/templates/{kind}/{file}" for _, kind in TEMPLATES + for file in (".python-version", ".env.example", ".gitignore", "README.md", "uv.toml", "requirements.txt", "pyproject.toml", "modules/inventory.py")} + required.add("nitrostack/templates/code-mode/scripts/sample-batch.js") + with zipfile.ZipFile(wheel) as archive: + assert required <= set(archive.namelist()) + with tarfile.open(sdist) as archive: + members = {name.split("/", 1)[1] for name in archive.getnames() if "/" in name} + assert required <= members + + +def test_installed_sdk_wheel_scaffolds_both_templates(sdk_distribution): + base, wheel, _ = sdk_distribution + envdir = base / "installed" + # Use the base interpreter: managed Python 3.10 venvs can otherwise write + # another venv's bin directory as their standard-library home. + base_python = Path(sys.base_prefix) / ("python.exe" if os.name == "nt" else "bin/python3") + result = subprocess.run([str(base_python), "-m", "venv", "--system-site-packages", str(envdir)], + capture_output=True, text=True, timeout=45) + assert result.returncode == 0, result.stdout + result.stderr + python = envdir / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + env = dict(os.environ, PYTHONPATH="", PIP_DISABLE_PIP_VERSION_CHECK="1") + result = subprocess.run([str(python), "-m", "pip", "install", "--no-index", "--no-deps", "--ignore-installed", str(wheel)], env=env, cwd=base, capture_output=True, text=True, timeout=45) + assert result.returncode == 0, result.stdout + result.stderr + # A venv created from another venv inherits the base interpreter's site, + # not the parent's installed dependencies. Share only that dependency path; + # the SDK wheel itself must resolve from the new environment below. + site = subprocess.run([str(python), "-c", "import sysconfig; print(sysconfig.get_paths()['purelib'])"], + env=env, cwd=base, text=True, capture_output=True, check=True, timeout=10) + (Path(site.stdout.strip()) / "test_dependencies.pth").write_text( + f"import site; site.addsitedir({sysconfig.get_paths()['purelib']!r})\n" + ) + check = subprocess.run([str(python), "-c", "import nitrostack; print(nitrostack.__file__)"], env=env, cwd=base, text=True, capture_output=True, timeout=10) + assert str(envdir).casefold() in check.stdout.casefold(), check.stdout + check.stderr + for name, _ in TEMPLATES: + target = base / name + run(["cli", "init", name, "--template", name, "--skip-install"], base, python=python, installed=True) + assert "No issues found" in run(["cli", "validate"], target, python=python, installed=True) + + +def test_upgrade_preserves_vendored_source_assignment(): + from nitrostack.cli.upgrade import find_current_spec, replace_nitrostack_spec + from nitrostack.cli._shared import loads_toml + for key in ("nitrostack", '\"nitrostack\"'): + source = f'[tool.uv.sources]\n{key} = {{path = "vendor/nitrostack"}}\n' + assert find_current_spec(source) is None + assert replace_nitrostack_spec(source, "nitrostack==0.3.2") == (source, 0) + project = '[project]\nname="demo"\ndependencies=["nitrostack", "quickjs>=1.19.4"]\n' + source + updated, count = replace_nitrostack_spec(project, "nitrostack==0.3.2") + parsed = loads_toml(updated) + assert count == 1 + assert parsed["tool"]["uv"]["sources"]["nitrostack"] == {"path": "vendor/nitrostack"} + assert parsed["project"]["dependencies"] == ["nitrostack==0.3.2", "quickjs>=1.19.4"] + + +def test_validation_checks_application_but_not_vendored_sdk(tmp_path): + from nitrostack.cli.validators import validate_project + (tmp_path / "pyproject.toml").write_text('[project]\nname="demo"\ndependencies=["nitrostack"]\n') + sdk = tmp_path / "vendor" / "nitrostack" + sdk.mkdir(parents=True) + (sdk / "helper.py").write_text('from nitrostack import mcp_app\ndef helper():\n @mcp_app(module=None)\n class DynamicApp: pass\n') + (tmp_path / "bad_application.py").write_text('from nitrostack import module\n@module(name="broken", imports=["not-a-class"])\nclass InvalidRoot: pass\n') + issues = validate_project(str(tmp_path)) + assert any(issue.severity == "error" and issue.path == "bad_application.py" for issue in issues) + assert not any("vendor" in (issue.path or "") for issue in issues) diff --git a/tests/test_readme_examples.py b/tests/test_readme_examples.py index 0e004fd..843fa98 100644 --- a/tests/test_readme_examples.py +++ b/tests/test_readme_examples.py @@ -146,3 +146,24 @@ async def run(): assert (service.units, service.api_key) == ("metric", "k") asyncio.run(run()) + + +_README_TEST_BLOCKS = re.findall( + r"\n```python\n(.*?)```", + README, + re.S, +) + + +def test_readme_has_marked_examples(): + assert _README_TEST_BLOCKS + + +@pytest.mark.parametrize("source", _README_TEST_BLOCKS) +def test_readme_marked_example_runs(source): + namespace: dict = {"__name__": "readme_example"} + exec(compile(source, "README.md", "exec"), namespace) + tests = [fn for name, fn in namespace.items() if name.startswith("test_") and callable(fn)] + assert tests + for fn in tests: + asyncio.run(fn()) diff --git a/tests/test_secret_value.py b/tests/test_secret_value.py new file mode 100644 index 0000000..f1c7d1a --- /dev/null +++ b/tests/test_secret_value.py @@ -0,0 +1,515 @@ +"""Issue #69: ``SecretValue`` keeps secrets out of logs, repr, pickles and serialized output.""" + +from __future__ import annotations + +import base64 +import copy +import io +import json +import logging +import pickle +import traceback +import warnings + +import pytest +from pydantic import BaseModel + +from nitrostack import ConfigService, DIContainer, SecretValue, is_secret_value, unwrap_secret +from nitrostack.auth.api_key import ApiKeyModule, ApiKeyService +from nitrostack.auth.jwt import JWTModule, JWTService +from nitrostack.auth.oauth import OAuthModule, OAuthService +from nitrostack.auth.oauth_module import build_registration_response +from nitrostack.auth.secret import REDACTED + +RAW = "s3cr3t-value-that-must-not-leak-0123456789" + + +def _secret(value: str = RAW) -> SecretValue: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return SecretValue.from_value(value, allow_hardcoded=True, reason="test") + + +def setup_function() -> None: + DIContainer.reset() + + +def teardown_function() -> None: + DIContainer.reset() + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +def test_from_env_reads_the_variable_and_marks_the_source(monkeypatch): + monkeypatch.setenv("MY_SECRET", RAW) + secret = SecretValue.from_env("MY_SECRET") + assert secret.unwrap() == RAW + assert secret.is_from_environment() is True + + +def test_from_env_raises_when_missing_and_optional_returns_none(monkeypatch): + monkeypatch.delenv("MISSING_SECRET", raising=False) + with pytest.raises(ValueError, match="MISSING_SECRET"): + SecretValue.from_env("MISSING_SECRET") + assert SecretValue.from_env_optional("MISSING_SECRET") is None + monkeypatch.setenv("MISSING_SECRET", "") + assert SecretValue.from_env_optional("MISSING_SECRET") is None + + +def test_the_missing_variable_error_never_contains_a_value(monkeypatch): + monkeypatch.delenv("MISSING_SECRET", raising=False) + with pytest.raises(ValueError) as exc: + SecretValue.from_env("MISSING_SECRET") + assert RAW not in str(exc.value) + + +def test_hardcoded_values_need_explicit_permission(): + with pytest.raises(ValueError, match="allow_hardcoded"): + SecretValue.from_value(RAW) + with pytest.warns(UserWarning, match="hardcoded"): + secret = SecretValue.from_value(RAW, allow_hardcoded=True, reason="unit test") + assert secret.unwrap() == RAW + assert secret.is_from_environment() is False + + +def test_empty_and_non_string_values_are_rejected(): + with pytest.raises(ValueError): + SecretValue("") + with pytest.raises(TypeError): + SecretValue(12345) # type: ignore[arg-type] + + +def test_short_secrets_warn_but_still_work(): + with pytest.warns(UserWarning, match="shorter than 16"): + secret = SecretValue("short") + assert secret.unwrap() == "short" + + +# --------------------------------------------------------------------------- +# Acceptance criteria: the raw value never appears +# --------------------------------------------------------------------------- + + +def test_str_repr_and_fstring_are_redacted(): + secret = _secret() + assert str(secret) == REDACTED + assert repr(secret) == REDACTED + assert f"{secret}" == REDACTED + assert f"{secret!r}" == REDACTED + assert "%s %r" % (secret, secret) == f"{REDACTED} {REDACTED}" + assert "{}".format(secret) == REDACTED + assert RAW not in f"{secret:>40}" + + +def test_containers_holding_a_secret_do_not_leak_in_repr(): + secret = _secret() + assert RAW not in repr({"key": secret}) + assert RAW not in repr([secret]) + assert RAW not in repr((secret,)) + + +def test_there_is_no_instance_dict_to_dump(): + with pytest.raises(TypeError): + vars(_secret()) + + +def test_logging_never_contains_the_raw_value(caplog): + secret = _secret() + logger = logging.getLogger("secret-test") + stream = io.StringIO() + handler = logging.StreamHandler(stream) + handler.setFormatter(logging.Formatter("%(levelname)s %(message)s %(args)s")) + logger.addHandler(handler) + logger.setLevel(logging.DEBUG) + try: + with caplog.at_level(logging.DEBUG, logger="secret-test"): + logger.info("token is %s", secret) + logger.info("token is %r", secret) + logger.info(f"token is {secret}") + logger.info("token is %(s)s", {"s": secret}) + try: + raise RuntimeError(f"failed with {secret}") + except RuntimeError: + logger.exception("boom with %s", secret) + finally: + logger.removeHandler(handler) + assert RAW not in stream.getvalue() + assert RAW not in caplog.text + assert all(RAW not in record.getMessage() for record in caplog.records) + assert REDACTED in caplog.text + + +def test_tracebacks_do_not_contain_the_raw_value(): + secret = _secret() + + def fail(): + local_secret = secret # noqa: F841 - shows up in captured locals + raise RuntimeError(f"bad secret {secret!r}") + + try: + fail() + except RuntimeError as exc: + # capture_locals belongs to TracebackException (format_exception() has no such argument). + captured = traceback.TracebackException(type(exc), exc, exc.__traceback__, capture_locals=True) + text = "".join(captured.format()) + assert RAW not in text + assert REDACTED in text + + +def test_pickle_never_contains_the_raw_value(): + secret = _secret() + for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1): + blob = pickle.dumps(secret, protocol=protocol) + assert RAW.encode() not in blob + assert RAW.encode() not in base64.b64encode(blob) + + +def test_an_unpickled_secret_has_no_value_instead_of_a_fake_one(): + restored = pickle.loads(pickle.dumps(_secret())) + assert is_secret_value(restored) + with pytest.raises(ValueError, match="redacted during serialization"): + restored.unwrap() + assert bool(restored) is False + assert restored != _secret() + + +class Settings(BaseModel): + name: str + api_secret: SecretValue + + +def test_pydantic_serialization_is_redacted(): + model = Settings(name="svc", api_secret=_secret()) + assert RAW not in model.model_dump_json() + assert REDACTED in model.model_dump_json() + assert model.model_dump()["api_secret"] == REDACTED + assert RAW not in json.dumps(model.model_dump()) + assert RAW not in repr(model) + assert RAW not in str(model) + assert RAW not in json.dumps(model.model_json_schema()) + + +def test_pydantic_accepts_a_secret_or_a_string_and_keeps_the_value(): + from_secret = Settings(name="a", api_secret=_secret()) + from_text = Settings(name="b", api_secret=RAW) + assert from_secret.api_secret.unwrap() == RAW + assert from_text.api_secret.unwrap() == RAW + assert isinstance(from_text.api_secret, SecretValue) + with pytest.raises(ValueError): + Settings(name="c", api_secret=123) # type: ignore[arg-type] + + +def test_a_bare_secret_is_not_json_serializable_rather_than_leaking(): + with pytest.raises(TypeError): + json.dumps({"secret": _secret()}) + + +def test_json_default_hook_that_uses_str_still_redacts(): + assert RAW not in json.dumps({"secret": _secret()}, default=str) + + +# --------------------------------------------------------------------------- +# Equality, hashing, copying +# --------------------------------------------------------------------------- + + +def test_equality_compares_values_in_constant_time(monkeypatch): + calls: list[tuple[bytes, bytes]] = [] + real = __import__("hmac").compare_digest + + def spy(a, b): + calls.append((a, b)) + return real(a, b) + + monkeypatch.setattr("nitrostack.auth.secret.hmac.compare_digest", spy) + assert _secret() == _secret() + assert _secret() == RAW + assert _secret() != _secret("another-long-secret-value-xyz") + assert _secret() != "different" + assert len(calls) == 4 + + +def test_equality_with_other_types_is_false(): + assert (_secret() == 123) is False + assert (_secret() != 123) is True + + +def test_equal_secrets_hash_equal_and_the_hash_is_not_the_plain_hash(): + assert hash(_secret()) == hash(_secret()) + assert hash(_secret()) != hash(RAW) + assert len({_secret(), _secret()}) == 1 + + +def test_copy_and_deepcopy_keep_the_value(): + secret = _secret() + assert copy.copy(secret).unwrap() == RAW + nested = copy.deepcopy({"k": [secret]}) + assert nested["k"][0].unwrap() == RAW + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def test_is_secret_value_and_unwrap_secret(): + secret = _secret() + assert is_secret_value(secret) is True + assert is_secret_value(RAW) is False + assert unwrap_secret(secret) == RAW + assert unwrap_secret(RAW) == RAW # plain strings are still accepted + with pytest.raises(TypeError): + unwrap_secret(None) # type: ignore[arg-type] + with pytest.raises(TypeError): + unwrap_secret(123) # type: ignore[arg-type] + + +# --------------------------------------------------------------------------- +# Modules accept a SecretValue and still accept a plain str +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_jwt_module_accepts_secret_and_str(wrap, monkeypatch): + monkeypatch.delenv("JWT_SECRET", raising=False) + JWTModule.for_root(secret=_secret() if wrap else RAW, audience="mcp") + service = DIContainer.get_instance().resolve(JWTService) + assert service.get_secret() == RAW + token = service.create_token({"sub": "u1"}) + assert service.verify_token(token)["sub"] == "u1" + assert RAW not in token # the secret signs the token, it is not inside it + + +def test_jwt_explicit_secret_wins_over_the_environment(monkeypatch): + monkeypatch.setenv("JWT_SECRET", "from-environment-secret-value") + service = JWTService(secret=_secret()) + assert service.get_secret() == RAW + + +def test_jwt_still_uses_the_environment_when_no_secret_is_given(monkeypatch): + monkeypatch.setenv("JWT_SECRET", "from-environment-secret-value") + assert JWTService().get_secret() == "from-environment-secret-value" + + +def test_jwt_service_repr_does_not_contain_the_secret(): + assert RAW not in repr(JWTService(secret=_secret())) + assert RAW not in str(JWTService(secret=_secret())) + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_api_key_module_accepts_secret_and_str(wrap, monkeypatch): + for name in ("API_KEY", "API_KEY_1"): + monkeypatch.delenv(name, raising=False) + ApiKeyModule.for_root(keys=[_secret() if wrap else RAW]) + service = DIContainer.get_instance().resolve(ApiKeyService) + assert service.validate(RAW) is True + assert service.validate("wrong") is False + + +def test_api_key_explicit_keys_add_to_environment_keys(monkeypatch): + monkeypatch.setenv("API_KEY", "env-key-value") + service = ApiKeyService(keys=[_secret()]) + assert service.validate("env-key-value") is True + assert service.validate(RAW) is True + + +def test_api_key_hashed_mode_works_with_a_secret_key(): + service = ApiKeyService(hashed=True, keys=[SecretValue("x" * 16)]) + assert service.validate("anything") is False + hashed = service.hash_key("plain") + assert ApiKeyService(hashed=True, keys=[_secret(hashed)]).validate("plain") is True + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_oauth_registration_response_returns_the_real_client_secret(wrap): + service = OAuthService( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + enable_client_registration=True, + static_client_id="client-1", + static_client_secret=_secret() if wrap else RAW, + ) + body = build_registration_response(service) + assert body["client_secret"] == RAW + assert body["token_endpoint_auth_method"] == "client_secret_post" + if wrap: + assert RAW not in repr(service.static_client_secret) + + +def test_oauth_without_a_client_secret_is_a_public_client(): + service = OAuthService( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + enable_client_registration=True, + static_client_id="client-1", + ) + body = build_registration_response(service) + assert body["client_secret"] == "" + assert body["token_endpoint_auth_method"] == "none" + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_oauth_introspection_sends_the_real_secret_in_basic_auth(wrap, monkeypatch): + monkeypatch.delenv("INTROSPECTION_CLIENT_SECRET", raising=False) + service = OAuthService( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + token_introspection_endpoint="http://auth.example.test/introspect", + token_introspection_client_id="svc", + token_introspection_client_secret=_secret() if wrap else RAW, + ) + seen = {} + + class FakeResponse: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return b'{"active": true}' + + def fake_urlopen(request, timeout=0): + seen["auth"] = request.get_header("Authorization") + return FakeResponse() + + monkeypatch.setattr("nitrostack.auth.oauth.urllib.request.urlopen", fake_urlopen) + import asyncio + + result = asyncio.run(service._introspect_via_endpoint("tok")) + assert result == {"active": True} + sent = base64.b64decode(seen["auth"].split(" ", 1)[1]).decode() + assert sent == f"svc:{RAW}" + + +def test_oauth_module_for_root_accepts_secret_values(): + OAuthModule.for_root( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + token_introspection_client_secret=_secret(), + static_client_secret=_secret(), + ) + service = DIContainer.get_instance().resolve(OAuthService) + assert is_secret_value(service.static_client_secret) + assert RAW not in repr(service.static_client_secret) + + +def test_config_service_keeps_secret_defaults_redacted(tmp_path): + config = ConfigService( + env_file_path=str(tmp_path / "missing.env"), + defaults={"DB_PASSWORD": _secret(), "PLAIN": "x"}, + ) + assert is_secret_value(config.get("DB_PASSWORD")) + assert RAW not in str(config.get("DB_PASSWORD")) + assert config.get_secret("DB_PASSWORD").unwrap() == RAW + + +def test_config_service_get_secret_wraps_plain_strings(tmp_path): + config = ConfigService(env_file_path=str(tmp_path / "missing.env"), defaults={"TOKEN": RAW}) + secret = config.get_secret("TOKEN") + assert is_secret_value(secret) + assert RAW not in f"{secret}" + assert secret.unwrap() == RAW + + +def test_config_service_get_secret_missing_empty_and_required(tmp_path): + config = ConfigService( + env_file_path=str(tmp_path / "missing.env"), + defaults={"EMPTY": ""}, + ignore_env_file=True, + ) + assert config.get_secret("NOPE_NOT_SET_ANYWHERE") is None + assert config.get_secret("EMPTY") is None + fallback = _secret() + assert config.get_secret("NOPE_NOT_SET_ANYWHERE", fallback) is fallback + with pytest.raises(KeyError): + config.get_secret_or_throw("NOPE_NOT_SET_ANYWHERE") + + +# --- Review follow-ups (PR #93) --------------------------------------------------------- + +def test_secret_passed_as_source_is_rejected(): + with pytest.raises(ValueError): + SecretValue(RAW, source=RAW) + with pytest.raises(ValueError): + SecretValue(RAW, source=f"prefix-{RAW}") + + +def test_pickle_never_carries_a_custom_source(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + secret = SecretValue(RAW, source="part-of-s3cr3t-value") + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + data = pickle.dumps(secret, protocol=protocol) + assert b"s3cr3t" not in data + assert pickle.loads(data).source == "custom" + + +def test_pickle_keeps_known_source_labels(): + assert pickle.loads(pickle.dumps(_secret())).source == "explicit" + assert pickle.loads(pickle.dumps(SecretValue(RAW))).source == "env" + + +def test_redacted_secret_is_not_replaced_by_environment_variable(monkeypatch): + monkeypatch.setenv("INTROSPECTION_CLIENT_SECRET", "ENV-VALUE-0123456789") + monkeypatch.setenv("OAUTH_CLIENT_SECRET", "ENV-VALUE-0123456789") + gone = pickle.loads(pickle.dumps(_secret())) + assert not gone + service = OAuthService( + "https://r", ["https://a"], ["x"], + token_introspection_client_secret=gone, static_client_secret=gone, + ) + assert service.token_introspection_client_secret is gone + assert service.static_client_secret is gone + with pytest.raises(ValueError): + build_registration_response(service, {}) + + +def test_oauth_still_falls_back_to_environment_when_not_given(monkeypatch): + monkeypatch.setenv("INTROSPECTION_CLIENT_SECRET", "ENV-VALUE-0123456789") + service = OAuthService("https://r", ["https://a"], ["x"]) + assert service.token_introspection_client_secret == "ENV-VALUE-0123456789" + + +class _LeakySource(str): + """A ``str`` subclass that equals "env" but drags a secret into its pickle state.""" + + def __new__(cls, text, leaked): + obj = super().__new__(cls, text) + obj.leaked = leaked + return obj + + def __reduce__(self): + return (str, (str(self),), {"leaked": self.leaked}) + + def __hash__(self): + return hash("env") + + def __eq__(self, other): + return other == "env" or str.__eq__(self, other) + + +def test_pickle_ignores_state_carried_by_a_str_subclass_source(): + leaked = "sk-live-top-secret" + for label in ("env", "config", "explicit"): + secret = SecretValue("v-" + leaked, source=_LeakySource(label, leaked)) + blob = pickle.dumps(secret) + assert leaked.encode() not in blob + assert pickle.loads(blob).source == label + + +def test_subclass_with_a_fake_equality_cannot_pick_a_safe_label(): + leaked = "sk-live-top-secret" + # Compares equal to "env" but its real text is the secret. + secret = SecretValue("v-" + leaked, source=_LeakySource(leaked, leaked)) + blob = pickle.dumps(secret) + assert leaked.encode() not in blob + assert pickle.loads(blob).source == "custom" diff --git a/tests/test_security_config.py b/tests/test_security_config.py new file mode 100644 index 0000000..65d1621 --- /dev/null +++ b/tests/test_security_config.py @@ -0,0 +1,53 @@ +"""eMudhra/emSign remediation: lockfile, dependency floor and CI workflow guards.""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest +from packaging.version import Version + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from nitrostack.cli.install import SECURE_PIP_SPEC # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +MIN_CERTIFI = Version("2026.10.19") + + +def test_lock_resolves_fixed_certifi(): + data = tomllib.loads((ROOT / "uv.lock").read_text(encoding="utf-8")) + versions = [Version(p["version"]) for p in data["package"] if p["name"] == "certifi"] + assert versions, "certifi missing from uv.lock" + assert all(v >= MIN_CERTIFI for v in versions), versions + + +def test_pyproject_declares_certifi_floor(): + data = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8")) + assert "certifi>=2026.10.19" in data["project"]["dependencies"] + + +def test_requirements_declares_certifi_floor(): + lines = (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines() + assert "certifi>=2026.10.19" in [line.strip() for line in lines] + + +@pytest.mark.parametrize( + "name, later_command", + [ + ("test.yml", 'pip install -e ".[dev]"'), + ], +) + +def test_workflow_bootstraps_secure_pip_before_other_installs(name, later_command): + text = (ROOT / ".github" / "workflows" / name).read_text(encoding="utf-8") + assert SECURE_PIP_SPEC in text, "workflow pip spec must match install.SECURE_PIP_SPEC" + assert 'python -m pip install --upgrade "certifi>=2026.10.19"' in text + assert "pip install --upgrade pip" not in text + assert text.index(SECURE_PIP_SPEC) < text.index(later_command) diff --git a/tests/test_spillover.py b/tests/test_spillover.py new file mode 100644 index 0000000..25dc634 --- /dev/null +++ b/tests/test_spillover.py @@ -0,0 +1,390 @@ +"""Issue #67: bounded results, caller isolation, and safe spillover stores.""" + +import asyncio +import gc +import json +from types import SimpleNamespace +from unittest.mock import MagicMock + +import mcp.types as types +import pytest +from pydantic import BaseModel + +from nitrostack import ( + AuthContext, DataSpilloverInterceptor, DIContainer, ExecutionContext, + FileSpilloverStore, MemorySpilloverStore, PayloadTooLargeError, + ResourceNotFoundError, generate_preview, module, tool, use_interceptors, +) +from nitrostack.core.app import McpApplication +from nitrostack.core.interceptors.data_spillover import ( + SpilloverRegistry, SpilloverResult, caller_owner, +) +from nitrostack.protocol.mrtr import InputRequiredResult +from nitrostack.runtime.request_ctx import RequestContext, request_ctx + + +@pytest.fixture(autouse=True) +def reset_container(): + DIContainer.reset() + yield + DIContainer.reset() + + +@pytest.fixture(params=["memory", "file"]) +def store(request, tmp_path): + cls = MemorySpilloverStore if request.param == "memory" else FileSpilloverStore + args = () if request.param == "memory" else (tmp_path / "results",) + return cls(*args, max_bytes=4096, max_total_bytes=16384, ttl_seconds=10) + + +def test_store_roundtrip_owner_delete(store): + async def scenario(): + key = await store.put(b'{"answer":42}', owner="alice", mime_type="application/json") + assert await store.get(key, owner="bob") is None + assert not await store.delete(key, owner="bob") + entry = await store.get(key, owner="alice") + assert entry.payload == b'{"answer":42}' + assert entry.mime_type == "application/json" + assert await store.delete(key, owner="alice") + assert await store.get(key, owner="alice") is None + asyncio.run(scenario()) + + +def test_store_expiry_and_payload_limit(store, monkeypatch): + clock = [1000.0] + monkeypatch.setattr("nitrostack.core.interceptors.spillover.time.time", lambda: clock[0]) + async def scenario(): + key = await store.put(b"hello", owner="alice", mime_type="text/plain") + with pytest.raises(PayloadTooLargeError): + await store.put(b"x" * 4097, owner="alice", mime_type="text/plain") + clock[0] += 10 + assert await store.cleanup_expired() == 1 + assert await store.get(key, owner="alice") is None + asyncio.run(scenario()) + + +def test_memory_lru_and_total_capacity(): + store = MemorySpilloverStore(max_bytes=8, max_total_bytes=8) + async def scenario(): + first = await store.put(b"1111", owner="a", mime_type="text/plain") + second = await store.put(b"2222", owner="a", mime_type="text/plain") + await store.get(first, owner="a") + await store.put(b"3333", owner="a", mime_type="text/plain") + assert await store.get(second, owner="a") is None + assert await store.get(first, owner="a") is not None + assert store._size == 8 + asyncio.run(scenario()) + + +def test_file_capacity_restart_cleanup(tmp_path, monkeypatch): + clock = [1000.0] + monkeypatch.setattr("nitrostack.core.interceptors.spillover.time.time", lambda: clock[0]) + store = FileSpilloverStore(tmp_path, max_total_bytes=300, ttl_seconds=5) + async def scenario(): + key = await store.put(b"x" * 80, owner="a", mime_type="text/plain") + with pytest.raises(ValueError, match="capacity"): + await store.put(b"x" * 80, owner="a", mime_type="text/plain") + reopened = FileSpilloverStore(tmp_path, max_total_bytes=300) + assert (await reopened.get(key, owner="a")).payload == b"x" * 80 + assert list(tmp_path.glob("*.tmp")) == [] + clock[0] += 5 + FileSpilloverStore(tmp_path) + assert list(tmp_path.glob("*.json")) == [] + asyncio.run(scenario()) + + +@pytest.mark.parametrize("key", ["../escape", "..\\escape", "%2e%2e%2fescape", "/etc/passwd", "C:\\escape", "x?y"]) +def test_file_rejects_unsafe_ids(tmp_path, key): + store = FileSpilloverStore(tmp_path) + async def scenario(): + with pytest.raises(ValueError): + await store.get(key, owner="a") + with pytest.raises(ValueError): + await store.delete(key, owner="a") + asyncio.run(scenario()) + + +def test_file_rejects_symlink_escape(tmp_path): + root = tmp_path / "results" + store = FileSpilloverStore(root) + outside = tmp_path / "private.json" + outside.write_text("private") + try: + (root / ("a" * 32 + ".json")).symlink_to(outside) + except OSError: + pytest.skip("Creating symlinks requires OS privileges") + with pytest.raises(ValueError, match="escapes"): + asyncio.run(store.get("a" * 32, owner="a")) + assert outside.read_text() == "private" + + +def test_concurrent_store_operations(store): + async def scenario(): + keys = await asyncio.gather(*[ + store.put(str(i).encode(), owner="a", mime_type="text/plain") for i in range(20) + ]) + assert len(set(keys)) == 20 + entries = await asyncio.gather(*[store.get(key, owner="a") for key in keys]) + assert [entry.payload for entry in entries] == [str(i).encode() for i in range(20)] + asyncio.run(scenario()) + + +@pytest.mark.parametrize("value", [list(range(20)), {str(i): i for i in range(20)}, "é" * 10000, + [{"huge": "x" * 10000}], {"huge": ["x" * 10000]}], + ids=["list", "dict", "unicode", "nested-list", "nested-dict"]) +def test_previews_are_bounded(value): + preview = generate_preview(value) + assert preview["count"] == len(value) + assert preview["truncated"] + assert len(json.dumps(preview, ensure_ascii=False).encode()) <= 2048 + + +def test_threshold_boundary_and_full_payload(store): + interceptor = DataSpilloverInterceptor(threshold_bytes=4, store=store) + context = ExecutionContext(request_id="1", auth=AuthContext(subject="alice"), logger=MagicMock()) + async def scenario(): + for value in ["éé", {"a": 1}, [1, 2]]: + async def handler(): + return value + result = await interceptor.intercept(context, handler) + if value == "éé": + assert result is value + else: + assert isinstance(result, SpilloverResult) + entry = await store.get(result.resource_uri.rsplit("/", 1)[1], owner=caller_owner(context)) + assert json.loads(entry.payload) == value + assert result.original_size_bytes == len(entry.payload) + async def unicode_handler(): + return "ééé" + assert (await interceptor.intercept(context, unicode_handler)).original_size_bytes == 6 + asyncio.run(scenario()) + + +def test_control_results_and_missing_identity(): + interceptor = DataSpilloverInterceptor(threshold_bytes=1) + context = ExecutionContext(request_id="1", logger=MagicMock()) + async def scenario(): + controls = [types.CallToolResult(content=[], isError=True), + {"resultType": "input_required", "message": "more"}, + InputRequiredResult(input_requests=[], request_state={}, message="more")] + for value in controls: + async def handler(): + return value + assert await interceptor.intercept(context, handler) is value + async def large(): + return "large" + with pytest.raises(PermissionError): + await interceptor.intercept(context, large) + asyncio.run(scenario()) + + +class Session: + pass + + +class ToolInput(BaseModel): + text: str = "large result" + + +def make_app(interceptor, *, task_support="forbidden", output_schema=None): + class Tools: + @tool(name="large", description="Test spillover", input_schema=ToolInput, + task_support=task_support, output_schema=output_schema) + @use_interceptors(interceptor) + async def large(self, input, context): + return {"text": input.text} + @module(name="spillover-test", providers=[Tools]) + class Root: + pass + return McpApplication(Root) + + +async def call(app, rc, text="large result", task=None): + token = request_ctx.set(rc) + try: + if task is not None: + return await app._call_tool("large", {"text": text}, task=task) + handler = app.mcp_server.request_handlers[types.CallToolRequest] + return (await handler(types.CallToolRequest( + method="tools/call", params=types.CallToolRequestParams(name="large", arguments={"text": text}), + ))).root + finally: + request_ctx.reset(token) + + +async def read(app, rc, uri): + token = request_ctx.set(rc) + try: + handler = app.mcp_server.request_handlers[types.ReadResourceRequest] + return (await handler(types.ReadResourceRequest( + method="resources/read", params=types.ReadResourceRequestParams(uri=uri), + ))).root.contents[0].text + finally: + request_ctx.reset(token) + + +def test_mcp_resource_roundtrip_and_session_isolation(store): + app = make_app(DataSpilloverInterceptor(threshold_bytes=1, store=store)) + alice = RequestContext(session=Session()) + bob = RequestContext(session=Session()) + async def scenario(): + result = await call(app, alice) + assert not result.is_error + data = result.structured_content + assert result.content[1].type == "resource_link" + assert json.loads(await read(app, alice, data["resource_uri"])) == {"text": "large result"} + for caller in [bob, None]: + with pytest.raises(ResourceNotFoundError): + await read(app, caller, data["resource_uri"]) + with pytest.raises(ResourceNotFoundError): + await read(app, alice, "resource://data-spillover/../escape") + assert data["original_size_bytes"] == len(b'{"text":"large result"}') + asyncio.run(scenario()) + + +def test_principal_tenant_issuer_isolation(monkeypatch): + payloads = { + "alice": {"sub": "alice", "iss": "issuer", "tenant_id": "one"}, + "bob": {"sub": "bob", "iss": "issuer", "tenant_id": "one"}, + "tenant": {"sub": "alice", "iss": "issuer", "tenant_id": "two"}, + "issuer": {"sub": "alice", "iss": "other", "tenant_id": "one"}, + } + monkeypatch.setattr("nitrostack.auth.request.verify_bearer_payload", payloads.get) + app = make_app(DataSpilloverInterceptor(threshold_bytes=1)) + def rc(token): + return RequestContext(request=SimpleNamespace(headers={"authorization": "Bearer " + token}), + session=Session(), meta={"userId": "alice", "tenantId": "one"}) + async def scenario(): + result = await call(app, rc("alice")) + uri = result.structured_content["resource_uri"] + assert json.loads(await read(app, rc("alice"), uri)) == {"text": "large result"} + for other in ["bob", "tenant", "issuer", "invalid"]: + with pytest.raises(ResourceNotFoundError): + await read(app, rc(other), uri) + assert (await call(app, rc("invalid"))).is_error + asyncio.run(scenario()) + + +def test_class_decorator_custom_prefix_and_schema(): + class Configured(DataSpilloverInterceptor): + def __init__(self): + super().__init__(threshold_bytes=1, resource_uri_prefix="resource://custom/") + schema = {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]} + app = make_app(Configured, output_schema=schema) + async def scenario(): + rc = RequestContext(session=Session()) + result = await call(app, rc) + assert result.structured_content["resource_uri"].startswith("resource://custom/") + definition = app._build_tool_definition(app._tools["large"]) + original = definition.output_schema["anyOf"][0] + assert all(original[key] == value for key, value in schema.items()) + assert definition.output_schema["anyOf"][1]["required"] == ["preview", "resource_uri", "original_size_bytes"] + asyncio.run(scenario()) + + +def test_registry_conflicts_and_session_cleanup(): + registry = SpilloverRegistry() + interceptor = DataSpilloverInterceptor() + registry.register(interceptor) + registry.register(interceptor) + with pytest.raises(ValueError, match="Conflicting"): + registry.register(DataSpilloverInterceptor()) + rc = RequestContext(session=Session()) + assert registry.session_key(rc) == registry.session_key(rc) + del rc + gc.collect() + assert registry._sessions == {} + + +def test_mcp_expiry_and_store_errors(store, monkeypatch): + clock = [1000.0] + monkeypatch.setattr("nitrostack.core.interceptors.spillover.time.time", lambda: clock[0]) + app = make_app(DataSpilloverInterceptor(threshold_bytes=1, store=store)) + rc = RequestContext(session=Session()) + async def scenario(): + result = await call(app, rc) + uri = result.structured_content["resource_uri"] + clock[0] += 10 + with pytest.raises(ResourceNotFoundError): + await read(app, rc, uri) + oversized = await call(app, rc, text="x" * 5000) + assert oversized.is_error + assert "max_bytes" in oversized.content[0].text + assert "x" * 5000 not in oversized.content[0].text + asyncio.run(scenario()) + + +def test_models_mcp_results_and_widget_bypass(store): + interceptor = DataSpilloverInterceptor(threshold_bytes=1, store=store) + context = ExecutionContext(request_id="1", auth=AuthContext(subject="alice"), logger=MagicMock()) + app = make_app(interceptor) + async def scenario(): + for value in [ToolInput(text="full"), types.CallToolResult( + content=[types.TextContent(type="text", text="full")], structuredContent={"text": "full"}, + )]: + async def handler(): + return value + spilled = await interceptor.intercept(context, handler) + payload = await store.get(spilled.resource_uri.rsplit("/", 1)[1], owner=caller_owner(context)) + assert json.loads(payload.payload) == value.model_dump(mode="json", by_alias=True, exclude_none=True) + component = MagicMock() + result = app._to_call_tool_result(spilled, component, context) + assert result.structured_content["resource_uri"] == spilled.resource_uri + component.transformer.assert_not_called() + asyncio.run(scenario()) + + +def test_background_task_spills_and_can_be_read(monkeypatch): + # Task augmentation is supported on the legacy wire, not MCP 2026. + monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "legacy") + app = make_app(DataSpilloverInterceptor(threshold_bytes=1), task_support="optional") + rc = RequestContext(session=Session()) + async def scenario(): + result = await call(app, rc, task=types.TaskMetadata(ttl=60000)) + for _ in range(100): + entry = await app.task_manager._store.get(result.task.task_id) + if entry.result is not None: + break + await asyncio.sleep(0.01) + assert entry.result is not None + stored = entry.result + data = stored.structured_content if isinstance(stored, types.CallToolResult) else stored["structuredContent"] + assert json.loads(await read(app, rc, data["resource_uri"])) == {"text": "large result"} + asyncio.run(scenario()) + + +def test_opaque_oauth_identity_reads_resources(monkeypatch): + from nitrostack.auth.oauth import OAuthService + from unittest.mock import AsyncMock + + monkeypatch.setattr("nitrostack.auth.request.verify_bearer_payload", lambda token: None) + service = MagicMock() + service.introspect_token = AsyncMock(return_value={"active": True, "sub": "alice", "iss": "oauth"}) + DIContainer.get_instance().register_value(OAuthService, service) + app = make_app(DataSpilloverInterceptor(threshold_bytes=1)) + rc = RequestContext(request=SimpleNamespace(headers={"authorization": "Bearer opaque"})) + async def scenario(): + result = await call(app, rc) + uri = result.structured_content["resource_uri"] + assert json.loads(await read(app, rc, uri)) == {"text": "large result"} + service.introspect_token.return_value = {"active": False} + with pytest.raises(ResourceNotFoundError): + await read(app, rc, uri) + asyncio.run(scenario()) + + +def test_file_symlink_check_without_os_privileges(tmp_path, monkeypatch): + from pathlib import Path + + store = FileSpilloverStore(tmp_path) + monkeypatch.setattr(Path, "is_symlink", lambda path: path.name == "a" * 32 + ".json") + with pytest.raises(ValueError, match="escapes"): + asyncio.run(store.get("a" * 32, owner="a")) + + +@pytest.mark.parametrize("kwargs", [{"threshold_bytes": -1}, {"threshold_bytes": 0.5}, + {"resource_uri_prefix": "../results/"}, + {"resource_uri_prefix": "resource://results/?x/"}]) +def test_invalid_interceptor_configuration(kwargs): + with pytest.raises(ValueError): + DataSpilloverInterceptor(**kwargs) diff --git a/tests/test_spillover_transport.py b/tests/test_spillover_transport.py new file mode 100644 index 0000000..f5670f8 --- /dev/null +++ b/tests/test_spillover_transport.py @@ -0,0 +1,265 @@ +"""Independent spillover verification through official HTTP and stdio transports.""" + +import asyncio +from concurrent.futures import ThreadPoolExecutor +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from types import SimpleNamespace + +import anyio +from mcp.shared.memory import create_client_server_memory_streams +from mcp.shared.message import SessionMessage +from mcp_types import jsonrpc_message_adapter +import pytest + +from nitrostack import DIContainer +from nitrostack.auth.jwt import JWTModule, JWTService +from nitrostack.runtime.request_ctx import stdio_connection_id +from nitrostack.transports.stdio import serve_stdio_streams +from tests.spillover_transport_support import MODERN_META, HttpPeer, build_app, http_app, large_value + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(autouse=True) +def clean_context(monkeypatch): + DIContainer.reset() + for key in ("NITRO_MCP_PROTOCOL_VERSION", "MCP_STATELESS"): + monkeypatch.delenv(key, raising=False) + yield + DIContainer.reset() + + +@pytest.fixture(params=["memory", "file"]) +def backend(request): + return request.param + + +def envelope(response): + result = response["result"] + assert result.get("isError", False) is False + data = result["structuredContent"] + assert len(json.dumps(data["preview"], ensure_ascii=False).encode()) <= 2048 + assert result["content"][1]["type"] == "resource_link" + assert result["content"][1]["uri"] == data["resource_uri"] + return data + + +def assert_full(peer, data, value): + expected = (value if isinstance(value, str) else json.dumps( + value, ensure_ascii=False, separators=(",", ":"), + )).encode() + assert data["original_size_bytes"] == len(expected) + contents = peer.read(data["resource_uri"])["result"]["contents"][0] + assert contents["text"].encode() == expected + assert contents["mimeType"] == ("text/plain" if isinstance(value, str) else "application/json") + + +def test_anonymous_http_roundtrip_and_session_isolation(backend, tmp_path): + with http_app(backend, tmp_path, threshold=16) as client: + alice, bob = HttpPeer(client), HttpPeer(client) + value = {"rows": ["é🚀" * 100]} + data = envelope(alice.call(value)) + assert_full(alice, data, value) + assert "error" in bob.read(data["resource_uri"]) + original = bob.headers["mcp-session-id"] + bob.headers["mcp-session-id"] = "not-server-issued" + response = client.post("/mcp", headers=bob.headers, json={ + "jsonrpc": "2.0", "id": 99, "method": "resources/read", + "params": {"uri": data["resource_uri"]}, + }) + assert response.status_code == 404 + bob.headers["mcp-session-id"] = original + # Expired/deleted transport sessions cannot recover anonymous payloads. + deleted = client.delete("/mcp", headers=alice.headers) + assert deleted.status_code == 200 + assert "error" in HttpPeer(client).read(data["resource_uri"]) + + +@pytest.mark.parametrize("era", ["legacy", "modern", "auto"]) +def test_verified_identity_reconnect_and_auth_isolation(backend, tmp_path, monkeypatch, era): + monkeypatch.setenv("JWT_SECRET", "spillover-wire-regression-secret") + JWTModule.for_root(secret_env_var="JWT_SECRET") + jwt = DIContainer.get_instance().resolve(JWTService) + claims = {"sub": "alice", "iss": "issuer-a", "client_id": "client-a", "tenant_id": "tenant-a"} + token = jwt.create_token(claims) + with http_app(backend, tmp_path, era=era, threshold=16) as client: + alice = HttpPeer(client, era, token) + data = envelope(alice.call("private-value" * 100)) + assert_full(HttpPeer(client, era, token), data, "private-value" * 100) + for field in ("sub", "iss", "client_id", "tenant_id"): + other = jwt.create_token({**claims, field: "another"}) + assert "error" in HttpPeer(client, era, other).read(data["resource_uri"]) + invalid = HttpPeer(client, era, "invalid-signature") + assert "error" in invalid.read(data["resource_uri"]) + assert invalid.call("private-value" * 100)["result"]["isError"] is True + assert "error" in HttpPeer(client, era).read(data["resource_uri"]) + + +@pytest.mark.parametrize("era", ["modern", "auto"]) +def test_anonymous_sessionless_cannot_create_owner(backend, tmp_path, era): + with http_app(backend, tmp_path, era=era, threshold=16) as client: + peer = HttpPeer(client, era) + denied = peer.call("private-value" * 100)["result"] + assert denied["isError"] is True + assert "structuredContent" not in denied + # Unsigned metadata is not a substitute for a trusted transport identity. + denied = peer.rpc("tools/call", { + "name": "payload", "arguments": {"value": "private-value" * 100}, + "_meta": {"sessionId": "forged", "userId": "alice"}, + }) + assert denied["result"]["isError"] is True + + +def test_expired_missing_and_malformed_uris(backend, tmp_path, monkeypatch): + clock = [1000.0] + monkeypatch.setattr("nitrostack.core.interceptors.spillover.time", SimpleNamespace(time=lambda: clock[0])) + with http_app(backend, tmp_path, threshold=16) as client: + peer = HttpPeer(client) + data = envelope(peer.call("private-value" * 100)) + clock[0] += 301 + for uri in (data["resource_uri"], "resource://data-spillover/" + "0" * 32, + "resource://data-spillover/../escape", "resource://data-spillover/%2e%2e%2fescape"): + response = peer.read(uri) + assert "error" in response + assert "private-value" not in json.dumps(response) + + +def test_custom_prefix_and_background_task(backend, tmp_path): + with http_app(backend, tmp_path, threshold=16, prefix="resource://reports/") as client: + peer = HttpPeer(client) + value = "task-result" * 100 + response = peer.call(value, task={"ttl": 60000})["result"] + task_id = response["structuredContent"]["task"]["taskId"] + for _ in range(100): + result = peer.rpc("tasks/get", {"taskId": task_id}) + assert "result" in result, result + if result["result"]["status"] == "completed": + break + time.sleep(0.01) + else: + pytest.fail("Spillover task did not complete") + completed = result["result"]["result"] + data = envelope({"result": completed}) + assert data["resource_uri"].startswith("resource://reports/") + assert_full(peer, data, value) + + +CASES = ["threshold", "threshold-plus-one", "1MiB", "5MiB", "10MiB", + "unicode", "escaped", "rows", "dictionary", "nested", "too-large", "20MiB"] + + +@pytest.mark.parametrize("case", CASES) +def test_large_payloads_over_http(backend, tmp_path, case): + value = large_value(case) + with http_app(backend, tmp_path) as client: + peer = HttpPeer(client) + response = peer.rpc("tools/call", {"name": "payload", "arguments": {"case": case}}) + if case == "threshold": + result = response["result"] + assert result["content"][0]["text"] == value + assert "resource_uri" not in result.get("structuredContent", {}) + elif case in ("too-large", "20MiB"): + result = response["result"] + assert result["isError"] is True + assert "max_bytes" in result["content"][0]["text"] + assert len(json.dumps(result)) < 2048 + else: + data = envelope(response) + assert_full(peer, data, value) + assert "error" in HttpPeer(client).read(data["resource_uri"]) + + +class StdioPeer: + def __init__(self, backend, root): + self.process = subprocess.Popen( + [sys.executable, str(ROOT / "tests" / "spillover_transport_support.py"), backend, str(root)], + cwd=ROOT, env={**os.environ, "PYTHONPATH": str(ROOT)}, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding="utf-8", + ) + self.reader = ThreadPoolExecutor(max_workers=1) + self.next_id = 1 + + def rpc(self, method, params): + self.process.stdin.write(json.dumps({ + "jsonrpc": "2.0", "id": self.next_id, "method": method, + "params": {**params, "_meta": MODERN_META}, + }) + "\n") + self.process.stdin.flush() + line = self.reader.submit(self.process.stdout.readline).result(timeout=10) + response = json.loads(line) + assert response["id"] == self.next_id + self.next_id += 1 + return response + + def close(self, *, clean=False): + try: + if clean: + self.process.stdin.close() + self.process.wait(timeout=10) + assert self.process.returncode == 0, self.process.stderr.read() + assert self.process.stdout.read() == "" + finally: + if self.process.poll() is None: + self.process.kill() + self.process.wait(timeout=5) + self.reader.shutdown() + for stream in (self.process.stdin, self.process.stdout, self.process.stderr): + stream.close() + + +def test_stdio_roundtrip_connection_isolation_and_shutdown(backend, tmp_path): + # Both processes use one disk root sequentially to prove persistence does not + # let a later stdio connection inherit anonymous ownership of an earlier one. + first = StdioPeer(backend, tmp_path) + try: + value = "stdio-result" * 100 + data = envelope(first.rpc("tools/call", {"name": "payload", "arguments": {"value": value}})) + result = first.rpc("resources/read", {"uri": data["resource_uri"]}) + assert result["result"]["contents"][0]["text"] == value + first.close(clean=True) + finally: + first.close() + second = StdioPeer(backend, tmp_path) + try: + assert "error" in second.rpc("resources/read", {"uri": data["resource_uri"]}) + second.close(clean=True) + finally: + second.close() + + +def test_stdio_identity_is_reset_after_shutdown_and_not_inherited_by_other_task(tmp_path): + async def scenario(): + app = build_app("memory", tmp_path, era="auto", threshold=16) + async with create_client_server_memory_streams() as (client, server): + client_read, client_write = client + seen = [] + + async def serve(): + await serve_stdio_streams(app.mcp_server, *server, "auto") + seen.append(stdio_connection_id.get()) + + async with anyio.create_task_group() as group: + group.start_soon(serve) + await client_write.send(SessionMessage(jsonrpc_message_adapter.validate_python({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { + "name": "payload", "arguments": {"value": "x" * 100}, "_meta": MODERN_META, + }, + }))) + response = await asyncio.wait_for(client_read.receive(), 5) + assert "resource_uri" in response.message.model_dump_json() + assert stdio_connection_id.get() is None + # The same app can serve HTTP concurrently without borrowing the + # anonymous identity belonging to this stdio connection. + from starlette.testclient import TestClient + with TestClient(app.get_combined_app(json_response=True)) as http: + assert HttpPeer(http, "auto").call("x" * 100)["result"]["isError"] is True + await client_write.aclose() + assert seen == [None] + assert stdio_connection_id.get() is None + asyncio.run(scenario()) diff --git a/tests/test_starter_calculator_hardening.py b/tests/test_starter_calculator_hardening.py new file mode 100644 index 0000000..0bc3d21 --- /dev/null +++ b/tests/test_starter_calculator_hardening.py @@ -0,0 +1,40 @@ +"""Starter calculator input limits (TS #368).""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +import importlib.util +import os + +_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +_PATH = os.path.join(_ROOT, "nitrostack", "templates", "starter", "modules", "calculator", "calculator_tools.py") +_spec = importlib.util.spec_from_file_location("starter_calc_hardening", _PATH) +_mod = importlib.util.module_from_spec(_spec) +assert _spec and _spec.loader +_spec.loader.exec_module(_mod) +CalculateInput = _mod.CalculateInput +ConvertTemperatureInput = _mod.ConvertTemperatureInput + + +def test_calculate_rejects_non_finite_operands(): + with pytest.raises(ValidationError): + CalculateInput(operation="add", a=float("inf"), b=1.0) + + +def test_convert_temperature_rejects_invalid_filename(): + with pytest.raises(ValidationError): + ConvertTemperatureInput(file_name="../evil.txt", value=20.0, from_unit="celsius", to_unit="fahrenheit") + + +def test_convert_temperature_accepts_safe_optional_file_fields(): + model = ConvertTemperatureInput( + file_name="reading.csv", + file_type="text/csv", + file_content="MjU=", + value=25.0, + from_unit="celsius", + to_unit="fahrenheit", + ) + assert model.file_name == "reading.csv" \ No newline at end of file diff --git a/tests/test_tasks.py b/tests/test_tasks.py index b1dad3c..08bde04 100644 --- a/tests/test_tasks.py +++ b/tests/test_tasks.py @@ -471,7 +471,7 @@ class TestTasksModule: async def _mcp_task_flow(): - harness = await NitroTestingModule.create(TestTasksModule) + harness = await NitroTestingModule.create(TestTasksModule, protocol_era="legacy") req = types.CallToolRequest( method="tools/call", diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py new file mode 100644 index 0000000..17e7ef3 --- /dev/null +++ b/tests/test_telemetry.py @@ -0,0 +1,281 @@ +"""PostHog CLI telemetry: exact payloads, opt-out, and stub ingest.""" +from __future__ import annotations + +import importlib +import io +import json +import os +import sys +import threading +import zlib +from http.server import BaseHTTPRequestHandler, HTTPServer +from unittest.mock import MagicMock, patch + +import pytest + +from nitrostack.cli import telemetry as telemetry_mod +from nitrostack.cli.telemetry import ( + identify_from_cloud_login, + maybe_print_first_run_notice, + resolved_posthog_api_key, + shutdown_telemetry, + track_command_invoked, + track_deploy_completed, + track_deploy_failed, + track_event, + track_init_completed, +) + + +@pytest.fixture(autouse=True) +def reset_telemetry_state(): + """Isolate module globals between tests.""" + telemetry_mod._client = None # noqa: SLF001 + telemetry_mod._posthog_unavailable = False # noqa: SLF001 + telemetry_mod._anonymous_distinct_id = None # noqa: SLF001 + telemetry_mod._distinct_id_override = None # noqa: SLF001 + telemetry_mod._shutdown_done = False # noqa: SLF001 + yield + telemetry_mod._client = None # noqa: SLF001 + telemetry_mod._posthog_unavailable = False # noqa: SLF001 + telemetry_mod._anonymous_distinct_id = None # noqa: SLF001 + telemetry_mod._distinct_id_override = None # noqa: SLF001 + telemetry_mod._shutdown_done = False # noqa: SLF001 + + +@pytest.fixture +def telemetry_env(monkeypatch, tmp_path): + monkeypatch.setenv("NITROSTACK_POSTHOG_KEY", "phc_test_stub_key") + monkeypatch.setenv("NITROSTACK_POSTHOG_HOST", "https://stub.example") + monkeypatch.setenv("NITROSTACK_ENVIRONMENT", "development") + monkeypatch.delenv("DO_NOT_TRACK", raising=False) + monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False) + monkeypatch.delenv("CI", raising=False) + monkeypatch.delenv("GITHUB_ACTIONS", raising=False) + cfg = tmp_path / ".config" / "nitrostack" + cfg.mkdir(parents=True) + flag = cfg / ".telemetry_first_run_notice_shown" + flag.write_text("1\n", encoding="utf-8") + monkeypatch.setenv("HOME", str(tmp_path)) + importlib.reload(telemetry_mod) + yield + importlib.reload(telemetry_mod) + + +def _track_with_mock_client(telemetry_env, monkeypatch): + """Return a MagicMock wired as the telemetry PostHog client.""" + mock = MagicMock() + monkeypatch.setattr(telemetry_mod, "get_distinct_id", lambda: "test-distinct-id") + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + return mock + + +def test_opt_out_do_not_track(telemetry_env, monkeypatch): + mock = _track_with_mock_client(telemetry_env, monkeypatch) + track_event("cli_command_invoked", {"command": "baseline"}) + assert mock.capture.call_count == 1 + + monkeypatch.setenv("DO_NOT_TRACK", "1") + importlib.reload(telemetry_mod) + mock.reset_mock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_event("cli_command_invoked", {"command": "x"}) + mock.capture.assert_not_called() + + +def test_opt_out_telemetry_flag_sends_nothing(telemetry_env, monkeypatch): + mock = _track_with_mock_client(telemetry_env, monkeypatch) + track_event("cli_command_invoked", {"command": "baseline"}) + assert mock.capture.call_count == 1 + + monkeypatch.setenv("NITROSTACK_TELEMETRY", "0") + importlib.reload(telemetry_mod) + mock.reset_mock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_event("cli_command_invoked", {"command": "x"}) + mock.capture.assert_not_called() + + +def test_ci_default_off_without_explicit_enable(telemetry_env, monkeypatch): + mock = _track_with_mock_client(telemetry_env, monkeypatch) + track_event("cli_command_invoked", {"command": "baseline"}) + assert mock.capture.call_count == 1 + + monkeypatch.setenv("CI", "true") + monkeypatch.delenv("NITROSTACK_TELEMETRY", raising=False) + importlib.reload(telemetry_mod) + mock.reset_mock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_event("cli_command_invoked", {"command": "x"}) + mock.capture.assert_not_called() + + +def test_posthog_missing_is_silent_noop(telemetry_env, monkeypatch): + import builtins + + real_import = builtins.__import__ + + def guarded_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "posthog": + raise ImportError("posthog not installed") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr(builtins, "__import__", guarded_import) + importlib.reload(telemetry_mod) + track_event("cli_command_invoked", {"command": "x"}) + assert telemetry_mod._posthog_unavailable is True # noqa: SLF001 + track_event("cli_command_invoked", {"command": "y"}) + + +def test_builtin_posthog_key_used_when_env_unset(monkeypatch): + """Built-in public project key when NITROSTACK_POSTHOG_KEY is unset (no network).""" + monkeypatch.delenv("NITROSTACK_POSTHOG_KEY", raising=False) + assert resolved_posthog_api_key() == telemetry_mod.DEFAULT_POSTHOG_PROJECT_KEY + + +def test_track_event_payload_exact(telemetry_env, monkeypatch): + mock = MagicMock() + monkeypatch.setattr(telemetry_mod, "get_distinct_id", lambda: "abc123deadbeef") + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_event("cli_command_invoked", {"command": "validate"}) + mock.capture.assert_called_once() + call_kw = mock.capture.call_args.kwargs + assert call_kw["distinct_id"] == "abc123deadbeef" + assert call_kw["event"] == "cli_command_invoked" + props = call_kw["properties"] + assert props["product"] == "python_sdk" + assert props["surface"] == "terminal" + assert props["environment"] == "development" + assert props["command"] == "validate" + assert "app_version" in props + assert "python_version" in props + assert props["sdk_version"] == props["app_version"] + assert "os_platform" in props + assert "os_arch" in props + + +def test_cli_command_invoked_helper(telemetry_env, monkeypatch): + mock = MagicMock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_command_invoked("pack") + mock.capture.assert_called_once() + assert mock.capture.call_args.kwargs["event"] == "cli_command_invoked" + assert mock.capture.call_args.kwargs["properties"]["command"] == "pack" + + +def test_cli_init_completed_properties(telemetry_env, monkeypatch): + mock = MagicMock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_init_completed( + template="python-starter", + skip_install=True, + duration_ms=42, + has_custom_description=False, + ) + props = mock.capture.call_args.kwargs["properties"] + assert mock.capture.call_args.kwargs["event"] == "cli_init_completed" + assert props["template"] == "python-starter" + assert props["skip_install"] is True + assert props["duration_ms"] == 42 + assert props["has_custom_description"] is False + + +def test_cli_deploy_completed_and_failed(telemetry_env, monkeypatch): + mock = MagicMock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_deploy_completed() + assert mock.capture.call_args_list[-1].kwargs["event"] == "cli_deploy_completed" + track_deploy_failed(error_code="RuntimeError") + assert mock.capture.call_args_list[-1].kwargs["properties"]["error_code"] == "RuntimeError" + + +def test_identify_login_emits_alias_identify_group_and_event(telemetry_env, monkeypatch): + mock = MagicMock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + monkeypatch.setattr(telemetry_mod, "_anonymous_id_from_machine", lambda: "anonhex1234567890") + identify_from_cloud_login( + user_id="user-cloud-1", + email="person@example.com", + organization_id="org-42", + ) + mock.alias.assert_called_once_with(previous_id="anonhex1234567890", distinct_id="user-cloud-1") + mock.identify.assert_called_once_with( + distinct_id="user-cloud-1", + properties={"email": "person@example.com"}, + ) + mock.group_identify.assert_called_once() + g_call = mock.group_identify.call_args + assert g_call.args[0] == "organization" + assert g_call.args[1] == "org-42" + assert g_call.kwargs.get("distinct_id") == "user-cloud-1" + login_capture = [ + c + for c in mock.capture.call_args_list + if c.kwargs.get("event") == "cli_login_completed" + ] + assert len(login_capture) == 1 + p = login_capture[0].kwargs["properties"] + assert p["user_email"] == "person@example.com" + assert p["cloud_user_id"] == "user-cloud-1" + + +def _decode_post_body(handler: BaseHTTPRequestHandler) -> bytes: + length = int(handler.headers.get("Content-Length", "0")) + raw = handler.rfile.read(length) + if handler.headers.get("Content-Encoding") == "gzip": + return zlib.decompress(raw, 16 + zlib.MAX_WBITS) + return raw + + +def test_stub_batch_server_records_payload(telemetry_env, monkeypatch): + """End-to-end: PostHog client to local HTTP stub (no real PostHog).""" + bodies: list[bytes] = [] + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + path = self.path.split("?", 1)[0].rstrip("/") + if path not in ("/batch", "/capture", "/e", "/i/v0/e"): + self.send_error(404) + return + bodies.append(_decode_post_body(self)) + self.send_response(200) + self.end_headers() + + def log_message(self, *args): + pass + + server = HTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + host = f"http://127.0.0.1:{server.server_port}" + monkeypatch.setenv("NITROSTACK_POSTHOG_HOST", host) + + importlib.reload(telemetry_mod) + + track_command_invoked("validate") + shutdown_telemetry(timeout=5.0) + server.shutdown() + thread.join(timeout=2.0) + + assert len(bodies) >= 1 + outer = json.loads(bodies[0].decode("utf-8")) + batch = outer.get("batch") if isinstance(outer, dict) else outer + assert isinstance(batch, list) + events = [x for x in batch if isinstance(x, dict) and x.get("event") == "cli_command_invoked"] + assert len(events) == 1 + props = events[0]["properties"] + assert props["command"] == "validate" + assert props["product"] == "python_sdk" + + +def test_maybe_print_skips_when_disabled(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path)) + importlib.reload(telemetry_mod) + buf = io.StringIO() + with ( + patch.dict(os.environ, {"DO_NOT_TRACK": "1"}, clear=False), + patch.object(sys, "stderr", buf), + ): + importlib.reload(telemetry_mod) + maybe_print_first_run_notice() + assert buf.getvalue() == "" diff --git a/tests/test_testing_module_overrides.py b/tests/test_testing_module_overrides.py new file mode 100644 index 0000000..00b8fcb --- /dev/null +++ b/tests/test_testing_module_overrides.py @@ -0,0 +1,356 @@ +"""Issue #74: provider overrides, teardown and mocks in NitroTestingModule.""" + +from __future__ import annotations + +import asyncio +import gc +import warnings +from unittest.mock import MagicMock + +import pytest + +from pydantic import BaseModel + +from nitrostack import DIContainer, ExecutionContext, injectable, module, tool +from nitrostack.testing import MockLogger, NitroTestingModule, create_mock_context, flush_tasks + +BUILT = [] + + +class LookupInput(BaseModel): + key: str + + +@injectable() +class Repo: + def __init__(self): + BUILT.append("real") + + def get(self, key): + return f"real-{key}" + + +class FakeRepo: + def __init__(self): + self.destroyed = 0 + + def get(self, key): + return f"fake-{key}" + + def on_module_destroy(self): + self.destroyed += 1 + + +@injectable(deps=[Repo]) +class Service: + def __init__(self, repo): + self.repo = repo + self.destroyed = 0 + + @tool(name="lookup", description="look up", input_schema=LookupInput) + async def lookup(self, input: LookupInput, context: ExecutionContext) -> str: + return self.repo.get(input.key) + + async def on_module_destroy(self): + self.destroyed += 1 + + +@module(name="svc", providers=[Repo, Service]) +class AppModule: + pass + + +@pytest.fixture(autouse=True) +def fresh(): + DIContainer.reset() + BUILT.clear() + yield + DIContainer.reset() + + +@pytest.mark.asyncio +async def test_override_instance_is_used_and_original_never_built(): + fake = FakeRepo() + app = await NitroTestingModule.create(AppModule, overrides={Repo: fake}) + assert await app.call_tool("lookup", {"input": {"key": "a"}}) == "fake-a" + assert BUILT == [] + await app.close() + + +@pytest.mark.asyncio +async def test_override_factory_sync_and_async(): + async def make(): + return FakeRepo() + + for override in (FakeRepo, make, lambda: FakeRepo()): + DIContainer.reset() + async with await NitroTestingModule.create(AppModule, overrides={Repo: override}) as app: + assert await app.call_tool("lookup", {"input": {"key": "z"}}) == "fake-z" + assert BUILT == [] + + +@pytest.mark.asyncio +async def test_without_override_real_provider_used(): + async with await NitroTestingModule.create(AppModule) as app: + assert await app.call_tool("lookup", {"input": {"key": "a"}}) == "real-a" + assert BUILT == ["real"] + + +@pytest.mark.asyncio +async def test_close_runs_hooks_once_even_when_called_twice(): + fake = FakeRepo() + app = await NitroTestingModule.create(AppModule, overrides={Repo: fake}) + service = DIContainer.get_instance().resolve(Service) + await app.close() + await app.close() + assert fake.destroyed == 1 + assert service.destroyed == 1 + + +@pytest.mark.asyncio +async def test_async_with_closes_and_close_inside_is_idempotent(): + fake = FakeRepo() + async with await NitroTestingModule.create(AppModule, overrides={Repo: fake}) as app: + await app.close() + assert fake.destroyed == 1 + + +@pytest.mark.asyncio +async def test_close_restores_overrides_so_next_test_is_clean(): + async with await NitroTestingModule.create(AppModule, overrides={Repo: FakeRepo()}): + pass + assert not DIContainer.get_instance().has_value(Repo) + + +@pytest.mark.asyncio +async def test_failing_hook_does_not_stop_other_hooks(): + fake = FakeRepo() + + def boom(): + raise RuntimeError("hook failed") + + fake.on_module_destroy = boom + app = await NitroTestingModule.create(AppModule, overrides={Repo: fake}) + service = DIContainer.get_instance().resolve(Service) + with pytest.raises(RuntimeError, match="hook failed"): + await app.close() + assert service.destroyed == 1 + await app.close() # already closed: no second raise + + +@pytest.mark.asyncio +async def test_magicmock_override_is_not_mistaken_for_a_tool(): + mock = MagicMock() + mock.get.return_value = "mocked" + async with await NitroTestingModule.create(AppModule, overrides={Repo: mock}) as app: + assert await app.call_tool("lookup", {"input": {"key": "a"}}) == "mocked" + mock.on_module_destroy.assert_not_called() + + +@pytest.mark.asyncio +async def test_failed_create_restores_overrides(): + @injectable() + class Boom: + def __init__(self): + raise RuntimeError("cannot build") + + @module(name="bad", providers=[Repo, Boom]) + class Bad: + pass + + with pytest.raises(Exception): + await NitroTestingModule.create(Bad, overrides={Repo: FakeRepo()}) + assert not DIContainer.get_instance().has_value(Repo) + + +def test_mock_logger(): + log = MockLogger() + log.info("started up", {"a": 1}) + log.warn("careful") + assert log.has_log("info", "started") + assert log.has_log("warning", "careful") + assert not log.has_log("error", "started") + log.clear() + assert not log.has_log("info", "started") + + +def test_create_mock_context(): + ctx = create_mock_context(tool_name="lookup", metadata={"k": 1}) + assert ctx.request_id == "test-request" and ctx.tool_name == "lookup" + assert isinstance(ctx.logger, MockLogger) + ctx.logger.error("bad thing") + assert ctx.logger.has_log("error", "bad") + + +@pytest.mark.asyncio +async def test_flush_tasks_lets_background_work_finish(): + done = [] + + async def inner(): + await asyncio.sleep(0) + done.append(2) + + async def outer(): + asyncio.get_running_loop().create_task(inner()) + done.append(1) + + asyncio.get_running_loop().create_task(outer()) + await flush_tasks() + assert done == [1, 2] + + +@pytest.mark.asyncio +async def test_no_resource_warning(): + with warnings.catch_warnings(): + warnings.simplefilter("error") + async with await NitroTestingModule.create(AppModule, overrides={Repo: FakeRepo()}) as app: + await app.call_tool("lookup", {"input": {"key": "a"}}) + gc.collect() + + +@pytest.mark.nitro_app(module=AppModule) +@pytest.mark.asyncio +async def test_nitro_client_fixture(nitro_client): + assert await nitro_client.call_tool("lookup", {"input": {"key": "q"}}) == "real-q" + + +@pytest.mark.asyncio +async def test_second_harness_does_not_reuse_service_holding_old_fake(): + first, second = FakeRepo(), FakeRepo() + second.get = lambda key: f"second-{key}" + async with await NitroTestingModule.create(AppModule, overrides={Repo: first}) as app: + assert await app.call_tool("lookup", {"input": {"key": "a"}}) == "fake-a" + async with await NitroTestingModule.create(AppModule, overrides={Repo: second}) as app: + assert await app.call_tool("lookup", {"input": {"key": "a"}}) == "second-a" + # And without overrides, nothing from the earlier harnesses is left behind. + async with await NitroTestingModule.create(AppModule) as app: + assert await app.call_tool("lookup", {"input": {"key": "a"}}) == "real-a" + + +@pytest.mark.asyncio +async def test_teardown_order_covers_indirect_dependencies_consumers_first(): + order = [] + + @injectable() + class Leaf: + def on_module_destroy(self): + order.append("leaf") + + @injectable(deps=[Leaf]) + class Middle: + def __init__(self, leaf): + self.leaf = leaf + + def on_module_destroy(self): + order.append("middle") + + @injectable(deps=[Middle]) + class Top: + def __init__(self, middle): + self.middle = middle + + def on_module_destroy(self): + order.append("top") + + # Only Top is declared on the module; Leaf and Middle are reached through DI. + @module(name="chain", providers=[Top]) + class Chain: + pass + + async with await NitroTestingModule.create(Chain): + pass + assert order == ["top", "middle", "leaf"] + + +@pytest.mark.asyncio +async def test_failing_override_factory_rolls_back_earlier_overrides(): + def broken(): + raise RuntimeError("factory failed") + + before = dict(DIContainer.get_instance()._instances) + with pytest.raises(RuntimeError, match="factory failed"): + await NitroTestingModule.create(AppModule, overrides={Repo: FakeRepo(), "other": broken}) + assert DIContainer.get_instance()._instances == before + assert not DIContainer.get_instance().has_value(Repo) + + +@pytest.fixture +def nitro_app(): + return AppModule + + +@pytest.mark.asyncio +async def test_nitro_client_resolves_nitro_app_fixture_dynamically(nitro_client): + assert await nitro_client.call_tool("lookup", {"input": {"key": "f"}}) == "real-f" + + +@pytest.mark.asyncio +async def test_consumer_cached_before_create_is_rebuilt_with_the_override(): + container = DIContainer.get_instance() + original_service = container.resolve(Service) # built earlier, holds the real Repo + original_repo = container.resolve(Repo) + assert original_service.repo is original_repo + fake = FakeRepo() + async with await NitroTestingModule.create(AppModule, overrides={Repo: fake}) as app: + # 1. The override is applied to the rebuilt consumer. + assert await app.call_tool("lookup", {"input": {"key": "a"}}) == "fake-a" + rebuilt = container.resolve(Service) + assert rebuilt is not original_service + assert rebuilt.repo is fake + # 2. The rebuilt service and the override were shut down exactly once. + assert rebuilt.destroyed == 1 + assert fake.destroyed == 1 + # 3. The originals are back by identity and were never shut down. + assert container.resolve(Service) is original_service + assert container.resolve(Repo) is original_repo + assert original_service.destroyed == 0 + + +@pytest.mark.asyncio +async def test_indirect_consumer_cached_before_create_is_rebuilt(): + order = [] + + @injectable(deps=[Service]) + class Outer: + def __init__(self, service): + self.service = service + self.destroyed = 0 + + def on_module_destroy(self): + self.destroyed += 1 + order.append("outer") + + container = DIContainer.get_instance() + original_outer = container.resolve(Outer) + original_service = original_outer.service + original_repo = container.resolve(Repo) + + fake = FakeRepo() + fake_destroy = fake.on_module_destroy + fake.on_module_destroy = lambda: (order.append("fake"), fake_destroy())[1] + service_destroy = Service.on_module_destroy + + async def tracked_destroy(self): + order.append("service") + await service_destroy(self) + + Service.on_module_destroy = tracked_destroy + try: + async with await NitroTestingModule.create(AppModule, overrides={Repo: fake}): + # 1. The override reaches the indirect consumer. + rebuilt_outer = container.resolve(Outer) + rebuilt_service = rebuilt_outer.service + assert rebuilt_outer is not original_outer + assert rebuilt_service is not original_service + assert rebuilt_outer.service.repo.get("x") == "fake-x" + finally: + Service.on_module_destroy = service_destroy + + # 2. Every rebuilt service was shut down once, consumers before dependencies. + assert order == ["outer", "service", "fake"] + assert (rebuilt_outer.destroyed, rebuilt_service.destroyed, fake.destroyed) == (1, 1, 1) + # 3. The originals are restored by identity and untouched. + assert container.resolve(Outer) is original_outer + assert container.resolve(Service) is original_service + assert container.resolve(Repo) is original_repo + assert (original_outer.destroyed, original_service.destroyed) == (0, 0) diff --git a/tests/test_token_store.py b/tests/test_token_store.py new file mode 100644 index 0000000..3e3dcd9 --- /dev/null +++ b/tests/test_token_store.py @@ -0,0 +1,266 @@ +"""Issue #68 storage, expiry, encryption compatibility, and secret safety.""" + +import asyncio +import builtins +import hashlib +import json +import os +import stat +from dataclasses import FrozenInstanceError +from pathlib import Path + +import pytest + +from nitrostack import ( + FileTokenStore, MemoryTokenStore, StoredToken, TokenStoreError, + calculate_expiration, create_default_token_store, get_default_store_path, + is_token_expired, token_response_to_stored, +) + +ACCESS = "ACCESS_SENTINEL_NOT_FOR_LOGS" +REFRESH = "REFRESH_SENTINEL_NOT_FOR_LOGS" +KEY = "ENCRYPTION_SENTINEL_NOT_FOR_LOGS" + + +def token(**overrides): + return StoredToken(**{"access_token": ACCESS, "token_type": "Bearer", "expires_at": 123, + "refresh_token": REFRESH, "scope": "read", "resource": "https://resource.example", + **overrides}) + + +@pytest.fixture(params=["memory", "file", "encrypted"]) +def store(request, tmp_path): + if request.param == "memory": + return MemoryTokenStore() + return FileTokenStore(tmp_path / "tokens.json", KEY if request.param == "encrypted" else None) + + +@pytest.mark.asyncio +async def test_roundtrip_expired_record_and_management(store): + original = token() + assert is_token_expired(original) + await store.save_token("issuer:client:alice:resource", original) + await store.save_token("bob", token(access_token="other")) + result = await store.get_token("issuer:client:alice:resource") + assert result == original + assert result.to_dict() == original.to_dict() + assert result.refresh_token == REFRESH + with pytest.raises(FrozenInstanceError): + result.access_token = "changed" + assert set(await store.list_keys()) == {"issuer:client:alice:resource", "bob"} + await store.delete_token("bob") + await store.delete_token("missing") + assert await store.get_token("bob") is None + await store.clear() + assert await store.list_keys() == [] + + +@pytest.mark.asyncio +async def test_store_and_record_representations_are_safe(store, caplog, capsys): + original = token() + await store.save_token("key", original) + caplog.set_level("DEBUG") + import logging + logging.getLogger(__name__).debug("store=%r token=%r", store, original) + output = repr(original) + str(original) + repr(store) + caplog.text + str(capsys.readouterr()) + assert all(secret not in output for secret in (ACCESS, REFRESH, KEY)) + + +@pytest.mark.asyncio +async def test_file_reopening_and_permissions(tmp_path, monkeypatch): + path = tmp_path / "private" / "tokens.json" + store = FileTokenStore(path) + replace = os.replace + modes = [] + + def observe(source, destination): + modes.append(stat.S_IMODE(Path(source).stat().st_mode)) + replace(source, destination) + + monkeypatch.setattr(os, "replace", observe) + await store.save_token("alice", token()) + assert await FileTokenStore(path).get_token("alice") == token() + assert list(path.parent.glob(".oauth-token-*")) == [] + if os.name == "posix": + assert modes == [0o600] + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + path.chmod(0o644) + await store.get_token("alice") + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure_point", ["replace", "fsync", "serialization"]) +async def test_atomic_failure_preserves_old_file(tmp_path, monkeypatch, failure_point): + path = tmp_path / "tokens.json" + store = FileTokenStore(path) + await store.save_token("alice", token()) + original = path.read_bytes() + + def fail(*args): + raise PermissionError(ACCESS + REFRESH) + + if failure_point == "serialization": + monkeypatch.setattr(store, "_encrypt", fail) + else: + monkeypatch.setattr(os, failure_point, fail) + with pytest.raises(TokenStoreError) as exc: + await store.save_token("bob", token(access_token="replacement")) + assert ACCESS not in str(exc.value) and REFRESH not in repr(exc.value) + assert path.read_bytes() == original + assert list(tmp_path.glob(".oauth-token-*")) == [] + assert await store.get_token("alice") == token() + + +@pytest.mark.asyncio +async def test_concurrent_instances_do_not_lose_keys(tmp_path): + stores = [FileTokenStore(tmp_path / "tokens.json") for _ in range(2)] + await asyncio.gather(*(stores[i % 2].save_token(str(i), token(access_token=str(i))) for i in range(30))) + assert set(await stores[0].list_keys()) == {str(i) for i in range(30)} + assert [(await stores[1].get_token(str(i))).access_token for i in range(30)] == [str(i) for i in range(30)] + + +@pytest.mark.asyncio +async def test_legacy_encryption_format_and_wrong_key(tmp_path): + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + + path = tmp_path / "tokens.json" + derived = hashlib.pbkdf2_hmac("sha256", KEY.encode(), b"nitrostack-token-store", 100000, 32) + iv = os.urandom(16) + encryptor = Cipher(algorithms.AES(derived), modes.GCM(iv)).encryptor() + ciphertext = encryptor.update(json.dumps({"alice": token().to_dict()}).encode()) + encryptor.finalize() + path.write_text(f"{iv.hex()}:{encryptor.tag.hex()}:{ciphertext.hex()}") + assert await FileTokenStore(path, KEY).get_token("alice") == token() + original = path.read_bytes() + with pytest.raises(TokenStoreError) as exc: + await FileTokenStore(path, "wrong").get_token("alice") + assert ACCESS not in str(exc.value) + assert path.read_bytes() == original + await FileTokenStore(path, KEY).save_token("bob", token()) + assert ACCESS not in path.read_text() and REFRESH not in path.read_text() + assert await FileTokenStore(path, KEY).get_token("bob") == token() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("content", ["broken", "[]", '{"alice":null}', '{"alice":{"access_token":"secret"}}']) +async def test_corruption_is_an_error_not_an_empty_store(tmp_path, content): + path = tmp_path / "tokens.json" + path.write_text(content) + with pytest.raises(TokenStoreError): + await FileTokenStore(path).get_token("alice") + assert path.read_text() == content + + +@pytest.mark.asyncio +async def test_missing_file_is_empty_and_symlink_is_refused(tmp_path, monkeypatch): + path = tmp_path / "tokens.json" + store = FileTokenStore(path) + assert await store.list_keys() == [] + assert not path.exists() + if os.name == "posix": + target = tmp_path / "target.json" + target.write_text("{}") + path.symlink_to(target) + else: + monkeypatch.setattr(Path, "is_symlink", lambda value: value == path) + with pytest.raises(TokenStoreError, match="symlink"): + await store.save_token("alice", token()) + + +@pytest.mark.asyncio +async def test_optional_encryption_import_is_lazy(tmp_path, monkeypatch): + original = builtins.__import__ + + def deny(name, *args, **kwargs): + if name.startswith("cryptography"): + raise ImportError(ACCESS) + return original(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", deny) + await FileTokenStore(tmp_path / "plain.json").save_token("a", token()) + with pytest.raises(TokenStoreError, match="token-encryption"): + await FileTokenStore(tmp_path / "encrypted.json", KEY).save_token("a", token()) + assert not (tmp_path / "encrypted.json").exists() + + +def test_expiry_units_boundaries_rotation_and_one_hour_fallback(monkeypatch): + monkeypatch.setattr("nitrostack.auth.token_store.time.time", lambda: 1000) + assert calculate_expiration(60) == 1060000 + assert not is_token_expired(token(expires_at=1030001)) + assert is_token_expired(token(expires_at=1030000)) + assert is_token_expired(token(expires_at=1000000), skew=0) + for response in [{"access_token": ACCESS}, {"access_token": ACCESS, "expires_in": None}]: + assert token_response_to_stored(response).expires_at == 4600000 + assert token_response_to_stored({"access_token": ACCESS, "expires_in": 0}).expires_at == 1000000 + refreshed = token_response_to_stored({"access_token": "new"}, previous=token()) + assert refreshed.refresh_token == REFRESH and refreshed.scope == "read" + assert refreshed.resource == token().resource + + +@pytest.mark.parametrize("duration", [-1, float("inf"), float("nan"), "60", None, True, 10 ** 400, 1e308], + ids=["negative", "infinite", "nan", "text", "none", "bool", "huge-int", "huge-float"]) +def test_invalid_durations_are_rejected(duration): + with pytest.raises(ValueError): + calculate_expiration(duration) + + +def test_default_store_helpers_are_explicit(tmp_path, monkeypatch): + monkeypatch.setattr(Path, "home", lambda: tmp_path) + assert Path(get_default_store_path()) == tmp_path / ".nitrostack" / "tokens.json" + assert isinstance(create_default_token_store(), FileTokenStore) + assert not (tmp_path / ".nitrostack").exists() + +@pytest.mark.parametrize("value,seconds", [("3600", 3600), ("0", 0), (" 1.5 ", 1.5), ("1e2", 100)]) +def test_provider_numeric_string_expiry(monkeypatch, value, seconds): + monkeypatch.setattr("nitrostack.auth.token_store.time.time", lambda: 1000) + assert token_response_to_stored({"access_token": ACCESS, "expires_in": value}).expires_at == int((1000 + seconds) * 1000) + + +@pytest.mark.parametrize("value", ["", " ", "no", "-1", "NaN", "Infinity", "1e999", "1e308", True]) +def test_provider_invalid_expiry_is_sanitized(value): + with pytest.raises(TokenStoreError, match="Invalid OAuth token response"): + token_response_to_stored({"access_token": ACCESS, "expires_in": value}) + + +@pytest.mark.asyncio +async def test_key_is_derived_once_per_instance(tmp_path, monkeypatch): + original = hashlib.pbkdf2_hmac + calls = [] + def derive(*args): + calls.append(1) + return original(*args) + monkeypatch.setattr(hashlib, "pbkdf2_hmac", derive) + path = tmp_path / "tokens" + store = FileTokenStore(path, KEY) + assert len(calls) == 1 and KEY not in vars(store).values() + await store.save_token("a", token()) + first = path.read_text().split(":")[0] + await store.get_token("a") + await store.save_token("b", token()) + assert path.read_text().split(":")[0] != first + assert len(calls) == 1 + assert await FileTokenStore(path, KEY).get_token("a") == token() + assert len(calls) == 2 + + +@pytest.mark.asyncio +async def test_fixed_lock_pool_same_path_and_collisions(tmp_path): + from nitrostack.auth.token_store import _path_locks + stores = [FileTokenStore(tmp_path / str(i)) for i in range(600)] + assert len(_path_locks) == 256 + assert len({id(store._lock) for store in stores}) <= 256 + same = FileTokenStore(tmp_path / "." / "0") + assert same._lock is stores[0]._lock + await asyncio.gather(*(FileTokenStore(tmp_path / "shared").save_token(str(i), token()) for i in range(30))) + assert len(await FileTokenStore(tmp_path / "shared").list_keys()) == 30 + by_lock = {} + for store in stores: + if id(store._lock) in by_lock: + other = by_lock[id(store._lock)] + await asyncio.gather(store.save_token("first", token()), other.save_token("second", token())) + assert await store.list_keys() == ["first"] + assert await other.list_keys() == ["second"] + break + by_lock[id(store._lock)] = store + else: + pytest.fail("Expected a collision in the fixed pool") diff --git a/tests/test_tool_context_input.py b/tests/test_tool_context_input.py new file mode 100644 index 0000000..6039785 --- /dev/null +++ b/tests/test_tool_context_input.py @@ -0,0 +1,124 @@ +"""ExecutionContext.input mirrors TS #373 (pre-pipe tool arguments).""" + +from __future__ import annotations + +import asyncio +import os +import sys +from typing import List + +from pydantic import BaseModel, Field + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from nitrostack import DIContainer, ExecutionContext +from nitrostack.core.pipeline import PipeMetadata, run_pipeline + +seen: dict = {} + + +class FlightInput(BaseModel): + from_: str = Field(alias="from") + to: str + + +class CityInput(BaseModel): + city: str + + +class RecordingGuard: + async def can_activate(self, context: ExecutionContext) -> bool: + seen["guard"] = dict(context.input or {}) + return True + + +class RecordingMiddleware: + async def use(self, context: ExecutionContext, next_fn): + seen["middleware"] = dict(context.input or {}) + return await next_fn() + + +class RecordingInterceptor: + async def intercept(self, context: ExecutionContext, next_fn): + seen["interceptor"] = dict(context.input or {}) + return await next_fn() + + +class UppercasePipe: + async def transform(self, value, metadata: PipeMetadata): + if isinstance(value, CityInput): + return CityInput(city=value.city.upper()) + return value + + +def _register(cls, instance) -> None: + DIContainer.get_instance().register_value(cls, instance) + + +def setup_function() -> None: + DIContainer.reset() + seen.clear() + + +def teardown_function() -> None: + DIContainer.reset() + + +def test_context_input_visible_through_pipeline(): + _register(RecordingGuard, RecordingGuard()) + _register(RecordingMiddleware, RecordingMiddleware()) + _register(RecordingInterceptor, RecordingInterceptor()) + + async def handler(_self, input: FlightInput, context: ExecutionContext): + seen["handler"] = dict(context.input or {}) + return {"ok": True} + + args_dict = {"from": "SFO", "to": "JFK"} + ctx = ExecutionContext(request_id="r1") + asyncio.run( + run_pipeline( + handler=handler, + handler_instance=object(), + args=(FlightInput.model_validate(args_dict), ctx), + kwargs={}, + context=ctx, + guards=[RecordingGuard], + middleware=[RecordingMiddleware], + interceptors=[RecordingInterceptor], + pipes=[], + filters=[], + param_type=FlightInput, + ) + ) + assert seen["guard"] == args_dict + assert seen["middleware"] == args_dict + assert seen["interceptor"] == args_dict + assert seen["handler"] == args_dict + + +def test_context_input_unchanged_when_pipes_transform_handler_input(): + _register(UppercasePipe, UppercasePipe()) + captured: List[dict] = [] + + async def handler(_self, input: CityInput, context: ExecutionContext): + captured.append({"handler": input.model_dump(), "context": dict(context.input or {})}) + return {} + + ctx = ExecutionContext(request_id="r2") + asyncio.run( + run_pipeline( + handler=handler, + handler_instance=object(), + args=(CityInput(city="paris"), ctx), + kwargs={}, + context=ctx, + guards=[], + middleware=[], + interceptors=[], + pipes=[UppercasePipe], + filters=[], + param_type=CityInput, + ) + ) + assert captured[0]["handler"] == {"city": "PARIS"} + assert captured[0]["context"] == {"city": "paris"} \ No newline at end of file diff --git a/tests/test_tool_output_schema.py b/tests/test_tool_output_schema.py new file mode 100644 index 0000000..b90540b --- /dev/null +++ b/tests/test_tool_output_schema.py @@ -0,0 +1,162 @@ +"""Issue #41: output schemas keep the null branch of Optional fields.""" + +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional + +import jsonschema +import pytest +from pydantic import BaseModel + +from nitrostack import DIContainer, NitroTestingModule, module, tool +from nitrostack.core.app import inspector_friendly_schema, tool_json_schema + +ROOT = Path(__file__).resolve().parents[1] +MODERN_META = { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": {"name": "schema-client", "version": "1"}, + "io.modelcontextprotocol/clientCapabilities": {}, +} + + +class Inner(BaseModel): + note: Optional[str] = None + + +class Out(BaseModel): + maybe: Optional[str] = None + n: Optional[int] = None + required_str: str = "x" + inner: Optional[Inner] = None + items: List[Optional[int]] = [] + + +class Empty(BaseModel): + pass + + +def _accepts_null(prop: Dict[str, Any]) -> bool: + for key in ("anyOf", "oneOf"): + if any(v.get("type") == "null" for v in prop.get(key, [])): + return True + types = prop.get("type") + return isinstance(types, list) and "null" in types + + +def test_output_schema_keeps_null_for_model(): + props = tool_json_schema(Out)["properties"] + assert _accepts_null(props["maybe"]) + assert _accepts_null(props["n"]) + assert _accepts_null(props["inner"]) + + +def test_output_schema_keeps_null_for_dict(): + props = tool_json_schema(Out.model_json_schema())["properties"] + assert _accepts_null(props["maybe"]) + assert _accepts_null(props["n"]) + + +def test_output_schema_keeps_null_in_nested_models_and_arrays(): + schema = tool_json_schema(Out) + assert _accepts_null(schema["$defs"]["Inner"]["properties"]["note"]) + assert _accepts_null(schema["properties"]["items"]["items"]) + + +def test_output_schema_does_not_loosen_required_fields(): + props = tool_json_schema(Out)["properties"] + assert not _accepts_null(props["required_str"]) + assert props["required_str"]["type"] == "string" + + +def test_output_schema_validates_null_payload(): + payload = {"maybe": None, "n": None, "required_str": "x", "inner": None, "items": [None, 1]} + jsonschema.validate(payload, tool_json_schema(Out)) + + +def test_input_schema_still_unwraps_optional_for_inspector(): + props = inspector_friendly_schema(Out.model_json_schema())["properties"] + assert not _accepts_null(props["maybe"]) + assert props["maybe"]["type"] == "string" + assert props["n"]["type"] == "integer" + + +class Tools: + @tool("profile", "Return empty optionals", Empty, output_schema=Out) + async def profile(self, input, context): + return Out() + + +@module(name="schema-app", providers=[Tools]) +class Root: + pass + + +@pytest.mark.asyncio +async def test_listed_schema_accepts_the_real_result_in_process(): + DIContainer.reset() + try: + harness = await NitroTestingModule.create(Root) + entry = next(iter(harness.app._tools.values())) + definition = harness.app._build_tool_definition(entry) + result = await harness.call_tool("profile", {"input": {}}) + assert result["maybe"] is None + jsonschema.validate(result, definition.output_schema) + finally: + DIContainer.reset() + + +class StdioServer: + """Runs the test server as a real subprocess and talks JSON-RPC over its stdio.""" + + def __init__(self): + self.process = subprocess.Popen( + [sys.executable, str(ROOT / "tests" / "output_schema_stdio_server.py")], + cwd=ROOT, env={**os.environ, "PYTHONPATH": str(ROOT)}, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding="utf-8", + ) + self.next_id = 1 + + def rpc(self, method, params): + self.process.stdin.write(json.dumps({ + "jsonrpc": "2.0", "id": self.next_id, "method": method, + "params": {**params, "_meta": MODERN_META}, + }) + "\n") + self.process.stdin.flush() + response = json.loads(self.process.stdout.readline()) + assert response["id"] == self.next_id + self.next_id += 1 + return response + + def close(self): + try: + self.process.stdin.close() + self.process.wait(timeout=10) + finally: + if self.process.poll() is None: + self.process.kill() + self.process.wait(timeout=5) + for stream in (self.process.stdout, self.process.stderr): + stream.close() + + +@pytest.mark.timeout(60) +def test_stdio_client_can_validate_null_results_against_the_advertised_schema(): + server = StdioServer() + try: + tools = server.rpc("tools/list", {})["result"]["tools"] + schema = next(t for t in tools if t["name"] == "profile")["outputSchema"] + assert _accepts_null(schema["properties"]["nickname"]) + assert _accepts_null(schema["properties"]["age"]) + + result = server.rpc("tools/call", {"name": "profile", "arguments": {}})["result"] + assert result.get("isError", False) is False + data = result["structuredContent"] + assert data["nickname"] is None and data["age"] is None + # This is what an MCP client does; it used to fail with "must be string". + jsonschema.validate(data, schema) + finally: + server.close() diff --git a/tests/test_tool_visibility.py b/tests/test_tool_visibility.py new file mode 100644 index 0000000..36b6955 --- /dev/null +++ b/tests/test_tool_visibility.py @@ -0,0 +1,378 @@ +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +from pydantic import BaseModel + +from nitrostack import ( + ExecutionContext, + ToolExamples, + ToolInvocation, + injectable, + module, + tool, +) +from nitrostack.core.app import McpApplication +from nitrostack.core.visibility import SessionVisibilityStore, VisibilityTransform +from nitrostack.runtime.request_ctx import RequestContext, request_ctx + + +class EmptyInput(BaseModel): + pass + + +class AdminInput(BaseModel): + secret_value: str + + +@injectable() +class VisibilityTools: + @tool("public_tool", "public", EmptyInput) + async def public(self, input: EmptyInput, context: ExecutionContext): + return "public" + + @tool("admin_tool", "admin", AdminInput, visibility="hidden", default_visible=False) + async def admin(self, input: AdminInput, context: ExecutionContext): + return input.secret_value + + @tool("unlock", "unlock", EmptyInput) + async def unlock(self, input: EmptyInput, context: ExecutionContext): + context.enable_tools(["admin_tool", "not_registered"]) + return "ok" + + @tool("lock", "lock", EmptyInput) + async def lock(self, input: EmptyInput, context: ExecutionContext): + context.disable_tools(["admin_tool"]) + return "ok" + + +@module(name="visibility", providers=[VisibilityTools]) +class VisibilityModule: + pass + + +def _app(): + app = McpApplication(VisibilityModule) + app.protocol_era = "legacy" + return app + + +def _request(session_id="session-a"): + return RequestContext(session=SimpleNamespace(id=session_id), request_id="1") + + +def test_session_store_lru_eviction(): + now = [0.0] + store = SessionVisibilityStore(ttl_seconds=10, max_entries=2, clock=lambda: now[0]) + store.update(("a", "u"), ["tool"], True) + store.update(("b", "u"), ["tool"], True) + assert store.is_visible(("a", "u"), "tool", False) + store.update(("c", "u"), ["tool"], True) + assert not store.is_visible(("b", "u"), "tool", False) + + +def test_session_store_ttl_expiry_uses_fake_clock(): + now = [0.0] + store = SessionVisibilityStore(ttl_seconds=10, max_entries=2, clock=lambda: now[0]) + store.update(("session", "subject"), ["tool"], True) + now[0] = 11 + assert not store.is_visible(("session", "subject"), "tool", False) + + +def test_session_key_requires_session_and_includes_verified_subject(): + assert VisibilityTransform.session_key(None, "user-a") is None + assert VisibilityTransform.session_key("client-session", "user-a") != ( + VisibilityTransform.session_key("client-session", "user-b") + ) + + +def test_tool_default_visible_preserves_existing_positional_arguments(): + examples = ToolExamples(input={"x": 1}, output={"y": 2}) + invocation = ToolInvocation(invoking="Working", invoked="Worked") + metadata = {"custom": "value"} + + @tool( + "positional_compat", + "compatibility", + EmptyInput, + "Compatibility", + None, + None, + "forbidden", + "hidden", + examples, + invocation, + metadata, + ) + async def positional_compat(self, input: EmptyInput, context: ExecutionContext): + return "ok" + + config = positional_compat._mcp_tool_config + assert config.examples is examples + assert config.invocation is invocation + assert config.metadata is metadata + assert config.visibility == "hidden" + assert config.default_visible is False + + +def test_tools_list_and_call_enforce_visibility_and_isolate_sessions(): + async def run(): + app = _app() + list_handler = app.mcp_server.request_handlers[ + __import__("mcp.types", fromlist=["ListToolsRequest"]).ListToolsRequest + ] + request = _request() + token = request_ctx.set(request) + try: + listed = await list_handler(SimpleNamespace(params=None)) + assert "admin_tool" not in [item.name for item in listed.root.tools] + denied = await app._call_tool("admin_tool", {}) + assert denied.is_error + + enabled = await app._call_tool("unlock", {}) + assert not enabled.is_error + listed = await list_handler(SimpleNamespace(params=None)) + assert "admin_tool" in [item.name for item in listed.root.tools] + + entry = app._tools["admin_tool"] + other_session = app._visibility_session_key(_request("session-b")) + assert not app.visibility_transform.is_visible(entry, other_session) + other_subject = ("session-a", "verified-user-b") + assert not app.visibility_transform.is_visible(entry, other_subject) + + disabled = await app._call_tool("lock", {}) + assert not disabled.is_error + listed = await list_handler(SimpleNamespace(params=None)) + assert "admin_tool" not in [item.name for item in listed.root.tools] + finally: + request_ctx.reset(token) + + asyncio.run(run()) + + +def test_sessionless_mutation_is_noop_but_static_default_applies(): + app = _app() + context = ExecutionContext(request_id="r") + app._configure_visibility_context(context, None) + context.enable_tools(["admin_tool"]) + assert not app.visibility_transform.is_visible(app._tools["admin_tool"], None) + assert app.visibility_transform.is_visible(app._tools["public_tool"], None) + + +def test_http_session_id_is_transport_owned_and_keyed_with_verified_subject(monkeypatch): + """Live HTTP requests use validated session ids and verified subjects for visibility.""" + from starlette.testclient import TestClient + + from nitrostack import DIContainer + from nitrostack.auth.jwt import JWTModule, JWTService + from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app + from nitrostack.transports.http import build_http_app + + async def build(): + @mcp_app(module=VisibilityModule, server=ServerConfig(name="visibility-http", protocol_era="legacy")) + class HttpVisibilityApp: + pass + + return await McpApplicationFactory.create(HttpVisibilityApp) + + monkeypatch.setenv("JWT_SECRET", "visibility-test-secret") + DIContainer.reset() + JWTModule.for_root(secret_env_var="JWT_SECRET") + app = asyncio.run(build()) + http_app = build_http_app( + app, protocol_era="legacy", wire_mode="sessionful", enable_cors=True + ) + token = DIContainer.get_instance().resolve(JWTService).create_token({"sub": "owner"}) + auth_headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + } + init_body = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "visibility-test", "version": "1"}, + }, + } + + def decode_response(response): + if response.headers.get("content-type", "").startswith("text/event-stream"): + for line in response.text.replace("\r\n", "\n").splitlines(): + if line.startswith("data:"): + return __import__("json").loads(line[len("data:"):].strip()) + raise AssertionError(f"No JSON-RPC response in {response.text!r}") + return response.json() + + with TestClient(http_app) as client: + session_a = client.post("/mcp", headers=auth_headers, json=init_body) + session_b = client.post("/mcp", headers=auth_headers, json=init_body) + assert session_a.status_code == session_b.status_code == 200 + id_a = session_a.headers["mcp-session-id"] + id_b = session_b.headers["mcp-session-id"] + assert id_a != id_b + + for session_id in (id_a, id_b): + client.post( + "/mcp", + headers={**auth_headers, "mcp-session-id": session_id}, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + ) + + def rpc(session_id, method, params, request_id=2, headers=auth_headers): + response = client.post( + "/mcp", + headers={**headers, "mcp-session-id": session_id}, + json={"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}, + ) + assert response.status_code == 200, response.text + return decode_response(response)["result"] + + def call(session_id, name, request_id=2, headers=auth_headers, arguments=None): + return rpc( + session_id, + "tools/call", + {"name": name, "arguments": arguments or {}}, + request_id, + headers, + ) + + denied_before_unlock = call(id_a, "admin_tool") + assert denied_before_unlock["isError"] is True + unlocked = call(id_a, "unlock", request_id=3) + assert unlocked["isError"] is False + + listed_a = rpc(id_a, "tools/list", {}, request_id=4) + listed_b = rpc(id_b, "tools/list", {}, request_id=5) + names_a = {entry["name"] for entry in listed_a["tools"]} + names_b = {entry["name"] for entry in listed_b["tools"]} + assert "admin_tool" in names_a + assert "admin_tool" not in names_b + + allowed_call = call( + id_a, "admin_tool", request_id=6, arguments={"secret_value": "private"} + ) + denied_other_session = call(id_b, "admin_tool", request_id=7) + assert allowed_call["isError"] is False + assert denied_other_session["isError"] is True + + # A different verified subject using the same validated session id gets + # an independent visibility key. + other_token = DIContainer.get_instance().resolve(JWTService).create_token({"sub": "intruder"}) + other_headers = {**auth_headers, "Authorization": f"Bearer {other_token}"} + listed_other_subject = rpc(id_a, "tools/list", {}, request_id=8, headers=other_headers) + assert "admin_tool" not in {entry["name"] for entry in listed_other_subject["tools"]} + + # A client-supplied random ID is rejected; it cannot select stored state. + arbitrary = client.post( + "/mcp", + headers={**auth_headers, "mcp-session-id": "client-chosen"}, + json={"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}, + ) + assert arbitrary.status_code == 404 + DIContainer.reset() + + +def test_search_tools_uses_current_request_visibility_for_names_and_schemas(monkeypatch): + from starlette.testclient import TestClient + + from nitrostack import DIContainer + from nitrostack.auth.jwt import JWTModule, JWTService + from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app + from nitrostack.transports.http import build_http_app + from nitrostack.transforms.search import RegexSearchTransform + + async def build(): + @mcp_app( + module=VisibilityModule, + server=ServerConfig(name="visibility-search-http", protocol_era="legacy"), + transforms=[RegexSearchTransform(always_visible=["unlock", "lock"])], + ) + class SearchVisibilityApp: + pass + + return await McpApplicationFactory.create(SearchVisibilityApp) + + monkeypatch.setenv("JWT_SECRET", "visibility-search-test-secret") + DIContainer.reset() + try: + JWTModule.for_root(secret_env_var="JWT_SECRET") + app = asyncio.run(build()) + http_app = build_http_app( + app, protocol_era="legacy", wire_mode="sessionful", enable_cors=True + ) + jwt = DIContainer.get_instance().resolve(JWTService) + headers = { + "Authorization": f"Bearer {jwt.create_token({'sub': 'search-owner'})}", + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + } + initialize = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "visibility-search-test", "version": "1"}, + }, + } + + def decode(response): + if response.headers.get("content-type", "").startswith("text/event-stream"): + import json + + data = next(line[5:].strip() for line in response.text.splitlines() if line.startswith("data:")) + return json.loads(data) + return response.json() + + with TestClient(http_app) as client: + initialized = [ + client.post("/mcp", headers=headers, json=initialize), + client.post("/mcp", headers=headers, json=initialize), + ] + assert all(response.status_code == 200 for response in initialized) + session_a, session_b = [response.headers["mcp-session-id"] for response in initialized] + + def call(session_id, name, request_id, arguments): + response = client.post( + "/mcp", + headers={**headers, "mcp-session-id": session_id}, + json={ + "jsonrpc": "2.0", + "id": request_id, + "method": "tools/call", + "params": {"name": name, "arguments": arguments}, + }, + ) + assert response.status_code == 200, response.text + return decode(response)["result"] + + enabled = call(session_a, "unlock", 2, {}) + assert enabled["isError"] is False + + visible = call( + session_a, + "search_tools", + 3, + {"query": "admin_tool", "detail": "full"}, + ) + hidden = call( + session_b, + "search_tools", + 4, + {"query": "admin_tool", "detail": "full"}, + ) + visible_results = visible["structuredContent"]["results"] + hidden_results = hidden["structuredContent"]["results"] + assert any(result["name"] == "admin_tool" for result in visible_results) + admin_result = next(result for result in visible_results if result["name"] == "admin_tool") + assert "secret_value" in str(admin_result) + assert all(result["name"] != "admin_tool" for result in hidden_results) + assert "secret_value" not in str(hidden_results) + finally: + DIContainer.reset() diff --git a/tests/test_tools_list_wire_cache.py b/tests/test_tools_list_wire_cache.py new file mode 100644 index 0000000..7495482 --- /dev/null +++ b/tests/test_tools_list_wire_cache.py @@ -0,0 +1,85 @@ +"""Regression tests for tools/list schema caching (issue #20fffe0 follow-ups).""" + +import json +import os +import pathlib +from unittest.mock import patch + +import pytest +from pydantic import BaseModel + +from nitrostack import DataSpilloverInterceptor, module, tool, use_interceptors +from nitrostack.core.app import McpApplication +from nitrostack.testing import NitroTestingModule +from tests._baseline_catalog import M +from tests.test_transformsapp import _list + +_BASELINE = pathlib.Path(__file__).parent / "fixtures" / "tools_list_baseline.json" + + +@pytest.mark.asyncio +async def test_tools_list_input_schema_isolated_between_calls(): + h = await NitroTestingModule.create(M) + try: + first = (await _list(h)).tools + first[0].input_schema["wire_cache_probe"] = True + second = (await _list(h)).tools + assert "wire_cache_probe" not in second[0].input_schema + finally: + await h.close() + + +@pytest.mark.asyncio +async def test_tools_list_order_matches_baseline(): + h = await NitroTestingModule.create(M) + try: + with patch.dict(os.environ, {"NITRO_MCP_PROTOCOL_VERSION": "modern"}): + response = await _list(h) + names = [listed.name for listed in response.tools] + expected = json.loads(_BASELINE.read_text(encoding="utf-8"))["modern"] + baseline_names = [item["name"] for item in json.loads(expected)["tools"]] + assert names == baseline_names + finally: + await h.close() + + +class _LateInput(BaseModel): + value: str = "x" + + +def test_spillover_schema_when_tool_registered_after_bootstrap(): + schema = { + "type": "object", + "properties": {"value": {"type": "string"}}, + "required": ["value"], + } + + class Existing: + @tool(name="existing", description="existing", input_schema=_LateInput) + async def existing(self, input, context): + return {"value": input.value} + + class Late: + @tool(name="late_spill", description="late", input_schema=_LateInput, output_schema=schema) + @use_interceptors(DataSpilloverInterceptor(threshold_bytes=1)) + async def late_spill(self, input, context): + return {"value": input.value} + + @module(name="late-spill-root", providers=[Existing]) + class Root: + pass + + app = McpApplication(Root) + late = Late() + tool_cfg = late.late_spill._mcp_tool_config + app._register_tool(late, late.late_spill, tool_cfg) + + entry = app._tools["late_spill"] + assert entry.has_spillover is None + definition = app._build_tool_definition(entry) + assert entry.has_spillover is True + assert definition.output_schema["anyOf"][1]["required"] == [ + "preview", + "resource_uri", + "original_size_bytes", + ] \ No newline at end of file diff --git a/tests/test_transforms_bm25.py b/tests/test_transforms_bm25.py new file mode 100644 index 0000000..3cb2d21 --- /dev/null +++ b/tests/test_transforms_bm25.py @@ -0,0 +1,209 @@ +import asyncio +import math + +import mcp.types as types +import pytest + +from nitrostack.transforms import TransformContext +from nitrostack.transforms.search import ( + Bm25Engine, Bm25SearchTransform, SearchToolsInput, tokenize, +) + + +def run(coro): + return asyncio.run(coro) + + +def make_tool(name, description="", props=None): + return types.Tool( + name=name, + description=description, + inputSchema={"type": "object", "properties": props or {}}, + ) + + +CATALOG = [ + make_tool("get_user", "Look up a user profile by id", {"user_id": {"type": "string"}}), + make_tool("get_order", "Fetch an order and its line items", {"order_id": {"type": "string"}}), + make_tool("send_email", "Send an email message to a recipient", {"to": {"type": "string"}}), + make_tool("search_genes", "Look up a gene by symbol and return annotations", {"symbol": {"type": "string"}}), + make_tool("get_rna_by_id", "Look up an RNA record by identifier", {"urs_id": {"type": "string"}}), + make_tool("list_invoices", "List invoices for a customer", {}), + make_tool("create_invoice", "Create an invoice for a customer order", {}), + make_tool("delete_user", "Delete a user account", {}), +] + + +class FakeRegistry: + def __init__(self, tools): + self.tools = tools + + def list_tools(self): + return list(self.tools) + + +def names(outcome): + return [tool.name for tool, _score in outcome.ranked] + + +# ---- tokenizer ------------------------------------------------------------- + +@pytest.mark.parametrize("text,expected", [ + ("getRnaById", ["get", "rna", "id"]), # "by" is a stop word + ("get_user_profile", ["get", "user", "profile"]), + ("HTTPServer", ["http", "server"]), + ("sha256Hash", ["sha256", "hash"]), # digits stay attached + ("find---genes!!", ["find", "genes"]), # repeated separators + ("Ünïcode Straße", ["ünïcode", "straße"]), + ("", []), + ("the of and", []), # stop words only +]) +def test_tokenizer(text, expected): + assert tokenize(text) == expected + + +def test_tokenizer_can_keep_stop_words(): + assert tokenize("the gene", drop_stop_words=False) == ["the", "gene"] + + +# ---- engine ---------------------------------------------------------------- + +def test_bm25_score_matches_hand_computation(): + engine = Bm25Engine(k1=1.5, b=0.75) + engine.build([("A", [(1.0, ["apple", "banana"])]), ("B", [(1.0, ["banana"])])]) + # N=2, n=1: idf = ln(1 + 1.5/1.5) = ln 2. avgdl = 1.5. A: tf=1, dl=2. + # denom = 1 + 1.5 * (0.25 + 0.75 * 2/1.5) = 2.875 ; num = 2.5 + expected = math.log(2) * 2.5 / 2.875 + result = engine.search(["apple"]) + assert [doc for doc, _ in result] == ["A"] + assert result[0][1] == pytest.approx(expected) + + +def test_idf_is_never_negative_for_common_terms(): + engine = Bm25Engine() + engine.build([(f"d{i}", [(1.0, ["common"])]) for i in range(5)]) + assert engine.idf("common") > 0 + + +def test_equal_scores_sort_by_id(): + engine = Bm25Engine() + engine.build([("b", [(1.0, ["x"])]), ("a", [(1.0, ["x"])])]) + assert [doc for doc, _ in engine.search(["x"])] == ["a", "b"] + + +def test_repeated_query_terms_count_once(): + engine = Bm25Engine() + engine.build([("a", [(1.0, ["x", "y"])])]) + assert engine.search(["x", "x", "x"]) == engine.search(["x"]) + + +@pytest.mark.parametrize("kwargs", [{"k1": -1}, {"b": 1.5}, {"b": -0.1}]) +def test_invalid_parameters_rejected(kwargs): + with pytest.raises(ValueError): + Bm25Engine(**kwargs) + + +# ---- ranking (golden) ------------------------------------------------------ +# These expectations are reasoned, not generated. Run once, and if one fails, +# check the reasoning before changing the expected value. + +def test_golden_single_match_queries(): + t = Bm25SearchTransform() + assert names(run(t.rank("email", CATALOG))) == ["send_email"] + assert names(run(t.rank("gene", CATALOG))) == ["search_genes"] # via description + assert names(run(t.rank("invoice", CATALOG))) == ["create_invoice"] + assert names(run(t.rank("invoices", CATALOG))) == ["list_invoices"] # no stemming + + +def test_golden_name_match_outranks_description_match(): + result = names(run(Bm25SearchTransform().rank("order", CATALOG))) + assert result[0] == "get_order" + assert "create_invoice" in result + + +def test_golden_user_query_returns_both_user_tools(): + result = names(run(Bm25SearchTransform().rank("user", CATALOG))) + assert set(result[:2]) == {"get_user", "delete_user"} + + +def test_ranking_is_deterministic_across_instances_and_catalog_order(): + first = names(run(Bm25SearchTransform().rank("look up", CATALOG))) + second = names(run(Bm25SearchTransform().rank("look up", list(reversed(CATALOG))))) + assert first == second + + +def test_no_match_returns_empty_list_not_error(): + outcome = run(Bm25SearchTransform().rank("zzzzzz", CATALOG)) + assert outcome.ranked == [] + + +def test_stop_word_only_query_explains_itself(): + outcome = run(Bm25SearchTransform().rank("of the", CATALOG)) + assert outcome.ranked == [] + assert "no searchable words" in outcome.note + + +# ---- index lifecycle ------------------------------------------------------- + +def test_index_is_not_rebuilt_on_every_search(): + t = Bm25SearchTransform() + assert t.build_count == 0 # lazy + for q in ("email", "gene", "order", "user"): + run(t.rank(q, CATALOG)) + assert t.build_count == 1 + + +def test_catalog_order_does_not_trigger_rebuild(): + t = Bm25SearchTransform() + run(t.rank("email", CATALOG)) + run(t.rank("email", list(reversed(CATALOG)))) + assert t.build_count == 1 + + +def test_adding_removing_or_editing_a_tool_rebuilds_once(): + t = Bm25SearchTransform() + run(t.rank("email", CATALOG)) + + added = CATALOG + [make_tool("send_sms", "Send a text message")] + assert "send_sms" in names(run(t.rank("sms", added))) + assert t.build_count == 2 + + run(t.rank("sms", added)) + assert t.build_count == 2 + + edited = [make_tool(x.name, "Totally new text") if x.name == "get_user" else x for x in added] + run(t.rank("totally", edited)) + assert t.build_count == 3 + + run(t.rank("email", [x for x in edited if x.name != "send_email"])) + assert t.build_count == 4 + + +# ---- through the search_tools handler -------------------------------------- + +async def _search(transform, **kw): + ctx = TransformContext() + + async def none(_name): + return None + + tool = await transform.resolve_tool(transform.search_tool_name, none, ctx) + return await tool.handler(SearchToolsInput(**kw), ctx) + + +def test_search_tools_handler_returns_ranked_results_and_clamps_limit(): + t = Bm25SearchTransform() + t.on_register(FakeRegistry(CATALOG)) + out = run(_search(t, query="email")) + assert [r["name"] for r in out["results"]] == ["send_email"] + big = run(_search(t, query="look", limit=500)) + assert len(big["results"]) <= 20 + assert "reduced" in big["note"] + + +def test_search_tools_handler_no_match_is_not_an_error(): + t = Bm25SearchTransform() + t.on_register(FakeRegistry(CATALOG)) + out = run(_search(t, query="zzzzzz")) + assert out["results"] == [] + assert "No tools matched" in out["note"] \ No newline at end of file diff --git a/tests/test_transforms_code_mode.py b/tests/test_transforms_code_mode.py new file mode 100644 index 0000000..6b18121 --- /dev/null +++ b/tests/test_transforms_code_mode.py @@ -0,0 +1,404 @@ +import asyncio +import os +import pytest +from pydantic import BaseModel + +import mcp.types as types +from nitrostack import ExecutionContext, injectable, module, tool, ToolAnnotations +from nitrostack.testing import NitroTestingModule +from nitrostack.transforms.code_mode import ( + CodeModeLimits, + CodeModeTransform, + WorkerPool, + format_legible_error, +) + +try: + import quickjs + HAS_QUICKJS = True +except ImportError: + HAS_QUICKJS = False + +requires_quickjs = pytest.mark.skipif( + not HAS_QUICKJS, + reason="The 'quickjs' package is required for Code Mode. Install it with: pip install 'nitrostack[code-mode]'", +) + + +def run(coro): + return asyncio.run(coro) + + +class CalcInput(BaseModel): + a: int + b: int + + +class WriteInput(BaseModel): + key: str + val: str + + +guard_call_count = 0 + + +class TrackingGuard: + async def can_activate(self, context): + global guard_call_count + guard_call_count += 1 + return True + + +@injectable() +class SampleController: + @tool( + name="add", + description="Add two numbers together", + input_schema=CalcInput, + annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False), + ) + async def add(self, input: CalcInput, context: ExecutionContext) -> int: + return input.a + input.b + + @tool( + name="multiply", + description="Multiply two numbers together", + input_schema=CalcInput, + annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False), + ) + async def multiply(self, input: CalcInput, context: ExecutionContext) -> int: + return input.a * input.b + + @tool( + name="destructive_wipe", + description="Destructive wipe operation", + input_schema=WriteInput, + annotations=ToolAnnotations(read_only_hint=False, destructive_hint=True), + ) + async def destructive_wipe(self, input: WriteInput, context: ExecutionContext) -> str: + return f"wiped {input.key}" + + +@module(name="sample", controllers=[SampleController]) +class SampleModule: + pass + + +@requires_quickjs +def test_cannot_reach_filesystem(): + """A script cannot reach the filesystem.""" + transform = CodeModeTransform() + res = run(transform.sandbox.run("typeof fs === 'undefined' ? 'isolated' : fs.readFileSync('/etc/passwd')", None, transform.limits)) + assert res.success is True + assert res.value == "isolated" + + res2 = run(transform.sandbox.run("fs.readFileSync('/etc/passwd')", None, transform.limits)) + assert res2.success is False + assert "ReferenceError" in res2.error + + +@requires_quickjs +def test_cannot_reach_network(): + """A script cannot reach network.""" + transform = CodeModeTransform() + res = run(transform.sandbox.run("typeof fetch === 'undefined' && typeof XMLHttpRequest === 'undefined' && typeof WebSocket === 'undefined'", None, transform.limits)) + assert res.success is True + assert res.value is True + + res2 = run(transform.sandbox.run("fetch('https://google.com')", None, transform.limits)) + assert res2.success is False + assert "ReferenceError" in res2.error + + +@requires_quickjs +def test_cannot_reach_environment_variables(): + """A script cannot reach environment variables.""" + transform = CodeModeTransform() + os.environ["SECRET_ENV_TOKEN"] = "supersecret123" + res = run(transform.sandbox.run("typeof process === 'undefined' ? 'no-process' : process.env.SECRET_ENV_TOKEN", None, transform.limits)) + assert res.success is True + assert res.value == "no-process" + + res2 = run(transform.sandbox.run("process.env", None, transform.limits)) + assert res2.success is False + assert "ReferenceError" in res2.error + + +@requires_quickjs +def test_cannot_reach_host_modules(): + """A script cannot reach host modules.""" + transform = CodeModeTransform() + res = run(transform.sandbox.run("typeof require === 'undefined' && typeof __import__ === 'undefined'", None, transform.limits)) + assert res.success is True + assert res.value is True + + res2 = run(transform.sandbox.run("require('os')", None, transform.limits)) + assert res2.success is False + assert "ReferenceError" in res2.error + + +@requires_quickjs +def test_infinite_loop_stops_within_timeout(): + """An infinite loop stops within the limits.""" + limits = CodeModeLimits(timeout_ms=200, memory_limit_mb=50, worker_pool_size=4) + pool = WorkerPool(limits) + try: + res = run(pool.run("while(true) {}", None, limits)) + assert res.success is False + assert res.error is not None + assert "TimeoutError" in res.error or "timed out" in res.error + finally: + run(pool.dispose()) + + +@requires_quickjs +def test_memory_bomb_stops_within_limits(): + """A memory bomb stops within memory limits.""" + limits = CodeModeLimits(timeout_ms=10000, memory_limit_mb=5, worker_pool_size=4) + pool = WorkerPool(limits) + try: + res = run(pool.run("let arr = []; while(true) { arr.push(new Array(50000).fill(1)); }", None, limits)) + assert res.success is False + assert res.error is not None + assert "MemoryLimitExceededError" in res.error or "out of memory" in res.error + finally: + run(pool.dispose()) + + +@requires_quickjs +def test_pool_keeps_serving_afterwards(): + """The pool keeps serving afterwards following timeout and memory bomb errors.""" + limits = CodeModeLimits(timeout_ms=5000, memory_limit_mb=5, worker_pool_size=4) + pool = WorkerPool(limits) + try: + timeout_limits = CodeModeLimits(timeout_ms=200, memory_limit_mb=5, worker_pool_size=4) + r1 = run(pool.run("while(true) {}", None, timeout_limits)) + assert r1.success is False + + r2 = run(pool.run("let arr = []; while(true) { arr.push(new Array(50000).fill(1)); }", None, limits)) + assert r2.success is False + + r3 = run(pool.run("const a = 10; const b = 20; a + b;", None, limits)) + assert r3.success is True + assert r3.value == 30 + + r4 = run(pool.run("return 40 + 2;", None, limits)) + assert r4.success is True + assert r4.value == 42 + finally: + run(pool.dispose()) + + +@requires_quickjs +def test_script_tool_calls_go_through_pipeline(): + """Script tool calls invoke real tools through the pipeline.""" + async def go(): + transform = CodeModeTransform() + h = await NitroTestingModule.create(SampleModule, transforms=[transform]) + + script = """ + const sum = tools.call('add', { a: 10, b: 5 }); + const product = call_tool('multiply', { a: sum, b: 2 }); + return { sum, product }; + """ + res = await h.call_tool("execute", {"code": script}) + return res + + result = run(go()) + assert isinstance(result, dict) + assert result["success"] is True + assert result["value"] == {"sum": 15, "product": 30} + assert result["toolCallCount"] == 2 + + +@requires_quickjs +def test_destructive_guard(): + """A tool is destructive unless readOnlyHint is true or destructiveHint is explicitly false. + Destructive tools are rejected unless allowDestructive is set. + """ + async def test_rejected(): + transform = CodeModeTransform(allow_destructive=False) + h = await NitroTestingModule.create(SampleModule, transforms=[transform]) + + script = "tools.call('destructive_wipe', { key: 'test', val: 'val' });" + return await h.call_tool("execute", {"code": script}) + + res = run(test_rejected()) + assert isinstance(res, dict) + assert res["success"] is False + assert "DestructiveToolError" in res["error"] + assert "destructive" in res["error"] + + async def test_allowed(): + transform = CodeModeTransform(allow_destructive=True) + h = await NitroTestingModule.create(SampleModule, transforms=[transform]) + + script = "tools.call('destructive_wipe', { key: 'test', val: 'val' });" + return await h.call_tool("execute", {"code": script}) + + res2 = run(test_allowed()) + assert isinstance(res2, dict) + assert res2["success"] is True + assert res2["value"] == "wiped test" + + +def test_import_nitrostack_works_without_extra(): + """import nitrostack works without extra installed.""" + import nitrostack + assert nitrostack.__name__ == "nitrostack" + + +@requires_quickjs +def test_synthetic_tools_catalog_and_discovery(): + """Search and get_schema synthetic tools work correctly.""" + async def go(): + transform = CodeModeTransform() + h = await NitroTestingModule.create(SampleModule, transforms=[transform]) + + srv = h.app.mcp_server + assert srv is not None + tools_list = (await srv.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list") + )).root.tools + + names = [t.name for t in tools_list] + assert set(names) == {"search", "get_schema", "execute"} + + search_res = await h.call_tool("search", {"query": "add"}) + assert search_res["matches"] == 1 + assert search_res["tools"][0]["name"] == "add" + + schema_res = await h.call_tool("get_schema", {"name": "add"}) + assert "add" in schema_res["schemas"] + assert "properties" in schema_res["schemas"]["add"]["inputSchema"] + + all_res = await h.call_tool("search", {"query": ""}) + assert all_res["total_tools"] == 3 + + run(go()) + + +@requires_quickjs +def test_configurable_synthetic_tool_names(): + """Synthetic tool names can be configured.""" + async def go(): + transform = CodeModeTransform( + search_tool_name="find_tools", + get_schema_tool_name="tool_schema", + execute_tool_name="run_code", + ) + h = await NitroTestingModule.create(SampleModule, transforms=[transform]) + srv = h.app.mcp_server + assert srv is not None + tools_list = (await srv.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list") + )).root.tools + names = [t.name for t in tools_list] + assert set(names) == {"find_tools", "tool_schema", "run_code"} + + run(go()) + + +@requires_quickjs +def test_max_tool_calls_limit(): + """Tool calls exceeding max_tool_calls limit are rejected.""" + async def go(): + transform = CodeModeTransform(max_tool_calls=2) + h = await NitroTestingModule.create(SampleModule, transforms=[transform]) + + script = """ + tools.call('add', { a: 1, b: 2 }); + tools.call('add', { a: 3, b: 4 }); + tools.call('add', { a: 5, b: 6 }); // 3rd call exceeds limit + """ + res = await h.call_tool("execute", {"code": script}) + return res + + res = run(go()) + assert isinstance(res, dict) + assert res["success"] is False + assert "Tool call limit exceeded" in res["error"] + + +def test_legible_error_scrubbing(): + """Errors returned to the model are readable and do not leak host paths or stack frames.""" + raw_error = f"Error in /home/aadarshm07/nitrostack/secret/path.py at line 42\n File \"/home/user/app.py\", line 10, in execute\nReferenceError: 'x' is not defined" + cleaned = format_legible_error(raw_error) + assert "/home/aadarshm07" not in cleaned + assert "File \"/home" not in cleaned + assert "ReferenceError: 'x' is not defined" in cleaned + + +@requires_quickjs +def test_console_logs_captured(): + """console.log, console.warn, console.error are captured into logs array.""" + async def go(): + transform = CodeModeTransform() + h = await NitroTestingModule.create(SampleModule, transforms=[transform]) + + script = """ + console.log("Starting calculation"); + console.warn("Watch out for precision"); + console.error("Test error message"); + return 100; + """ + res = await h.call_tool("execute", {"code": script}) + return res + + res = run(go()) + assert isinstance(res, dict) + assert res["success"] is True + assert res["value"] == 100 + logs = res["logs"] + assert any("[info] Starting calculation" in l for l in logs) + assert any("[warn] Watch out for precision" in l for l in logs) + assert any("[error] Test error message" in l for l in logs) + + +@requires_quickjs +def test_worker_slot_recovers_if_connection_none(): + """If a slot connection or process is killed/None, it recovers automatically.""" + limits = CodeModeLimits(worker_pool_size=1) + pool = WorkerPool(limits) + try: + slot = pool._all_slots[0] + slot.terminate() + assert slot.conn is None + + res = run(pool.run("return 123 * 2;", None, limits)) + assert res.success is True + assert res.value == 246 + finally: + run(pool.dispose()) + + +@requires_quickjs +def test_worker_pool_disposed_raises_runtime_error(): + """Running against a disposed pool raises RuntimeError, not AttributeError on NoneType.""" + limits = CodeModeLimits(worker_pool_size=1) + pool = WorkerPool(limits) + run(pool.dispose()) + + with pytest.raises(RuntimeError, match="disposed"): + run(pool.run("1 + 1", None, limits)) + + +@requires_quickjs +def test_timeout_applied_while_tool_call_in_progress(): + """Script timeout is enforced while a slow tool call is in progress.""" + async def slow_tool(name, args): + await asyncio.sleep(0.6) + return "done" + + limits = CodeModeLimits(timeout_ms=50, worker_pool_size=1) + pool = WorkerPool(limits) + try: + res = run(pool.run("tools.call('slow', {})", slow_tool, limits)) + assert res.success is False + assert res.error is not None + assert "TimeoutError" in res.error or "timed out" in res.error + # The script duration should be around 50ms, not 600ms+ + assert res.duration_ms < 250 + finally: + run(pool.dispose()) + diff --git a/tests/test_transforms_pipeline.py b/tests/test_transforms_pipeline.py new file mode 100644 index 0000000..dd37e31 --- /dev/null +++ b/tests/test_transforms_pipeline.py @@ -0,0 +1,104 @@ +import pytest + +from nitrostack.transforms import ( + CatalogTransform, McpTransformBase, TransformContext, TransformError, TransformPipeline, +) + + +class Tag(McpTransformBase): + def __init__(self, name, log): + self.name = name + self.log = log + + async def transform_tools(self, tools, ctx): + self.log.append(self.name) + return [t + f"+{self.name}" for t in tools] + + async def resolve_tool(self, name, next, ctx): + self.log.append(f"resolve:{self.name}") + found = await next(name) + return None if found is None else f"{found}|{self.name}" + + +@pytest.mark.asyncio +async def test_empty_pipeline_is_identity(): + p = TransformPipeline([]) + assert not p.enabled + tools = ["a", "b"] + assert await p.transform_tools(tools, TransformContext()) == ["a", "b"] + assert await p.resolve_tool("a", lambda n: n, TransformContext()) == "a" + + +@pytest.mark.asyncio +async def test_list_transforms_apply_in_declared_order(): + log = [] + p = TransformPipeline([Tag("one", log), Tag("two", log)]) + out = await p.transform_tools(["x"], TransformContext()) + assert out == ["x+one+two"] + assert log == ["one", "two"] + + +@pytest.mark.asyncio +async def test_resolve_chains_through_next_first_is_outermost(): + log = [] + p = TransformPipeline([Tag("one", log), Tag("two", log)]) + out = await p.resolve_tool("x", lambda n: n, TransformContext()) + assert out == "x|two|one" + assert log == ["resolve:one", "resolve:two"] + + +@pytest.mark.asyncio +async def test_resolve_unknown_tool_returns_none(): + p = TransformPipeline([Tag("one", [])]) + assert await p.resolve_tool("nope", lambda n: None, TransformContext()) is None + + +@pytest.mark.asyncio +async def test_raising_transform_becomes_transform_error(): + class Boom(McpTransformBase): + name = "boom" + + async def transform_tools(self, tools, ctx): + raise RuntimeError("bad") + + p = TransformPipeline([Boom()]) + with pytest.raises(TransformError) as e: + await p.transform_tools(["a"], TransformContext()) + assert e.value.transform_name == "boom" + # the pipeline is still usable afterwards + assert await TransformPipeline([]).transform_tools(["a"], TransformContext()) == ["a"] + + +@pytest.mark.asyncio +async def test_dispose_runs_all_in_reverse_even_if_one_fails(): + order = [] + + class D(McpTransformBase): + def __init__(self, name, fail=False): + self.name, self.fail = name, fail + + async def dispose(self): + order.append(self.name) + if self.fail: + raise RuntimeError("x") + + p = TransformPipeline([D("a"), D("b", fail=True), D("c")]) + await p.dispose() + assert order == ["c", "b", "a"] + + +def test_duplicate_names_rejected(): + with pytest.raises(ValueError): + TransformPipeline([Tag("same", []), Tag("same", [])]) + + +@pytest.mark.asyncio +async def test_catalog_transform_applies_and_supports_sync_apply(): + class Upper(CatalogTransform): + name = "upper" + + def apply_transform(self, tools, ctx): + return [t.upper() for t in tools] + + p = TransformPipeline([Upper()]) + assert await p.transform_tools(["a"], TransformContext()) == ["A"] \ No newline at end of file diff --git a/tests/test_transforms_reentrancy.py b/tests/test_transforms_reentrancy.py new file mode 100644 index 0000000..ee549c1 --- /dev/null +++ b/tests/test_transforms_reentrancy.py @@ -0,0 +1,50 @@ +import pytest + +from nitrostack.transforms import ( + CatalogTransform, TransformContext, TransformPipeline, bypassing, +) + + +class Hide(CatalogTransform): + name = "hide" + + def __init__(self): + self.applied = 0 + + def apply_transform(self, tools, ctx): + self.applied += 1 + return [t for t in tools if t != "secret"] + + +@pytest.mark.asyncio +async def test_transform_is_skipped_while_its_own_call_is_running(): + h = Hide() + p = TransformPipeline([h]) + ctx = TransformContext() + + assert await p.transform_tools(["a", "secret"], ctx) == ["a"] + assert h.applied == 1 + + with bypassing("hide"): + assert await p.transform_tools(["a", "secret"], ctx) == ["a", "secret"] + assert h.applied == 1 # not re-run + + assert await p.transform_tools(["a", "secret"], ctx) == ["a"] # bypass was released + assert h.applied == 2 + + +@pytest.mark.asyncio +async def test_call_tool_with_caller_bypasses_that_transform_only(): + seen = {} + + async def invoker(name, args, ctx): + from nitrostack.transforms import active_bypass + seen["bypass"] = set(active_bypass()) + return f"called {name}" + + ctx = TransformContext(_invoker=invoker) + assert await ctx.call_tool("real", {}, caller="hide") == "called real" + assert seen["bypass"] == {"hide"} + + await ctx.call_tool("real", {}) + assert seen["bypass"] == set() \ No newline at end of file diff --git a/tests/test_transforms_search.py b/tests/test_transforms_search.py new file mode 100644 index 0000000..24334b3 --- /dev/null +++ b/tests/test_transforms_search.py @@ -0,0 +1,227 @@ +import asyncio +import time + +import mcp.types as types +import pytest + +from nitrostack.transforms import TransformContext +from nitrostack.transforms.search import ( + CallToolInput, RegexSearchTransform, SearchToolsInput, is_browse_query, +) +from nitrostack.transforms.validation import ToolArgumentError + + +def run(coro): + return asyncio.run(coro) + + +def make_tool(name, description="", props=None, meta=None): + schema = {"type": "object", "properties": props or {}} + return types.Tool(name=name, description=description, inputSchema=schema, _meta=meta) + + +class FakeRegistry: + def __init__(self, tools): + self._tools = tools + + def list_tools(self): + return list(self._tools) + + +class FakeCtx(TransformContext): + def __init__(self): + super().__init__() + self.calls = [] + + async def call_tool(self, name, arguments=None, *, caller=None): + self.calls.append((name, arguments, caller)) + return {"ok": True} + + +def registered(transform, tools): + transform.on_register(FakeRegistry(tools)) + return transform + + +async def search(transform, **kw): + ctx = TransformContext() + tool = await transform.resolve_tool(transform.search_tool_name, _none, ctx) + return await tool.handler(SearchToolsInput(**kw), ctx) + + +async def _none(name): + return None + + +CATALOG = [ + make_tool("get_user", "Look up a user by id. Returns a profile.", {"user_id": {"type": "string", "description": "the id"}}), + make_tool("get_order", "Fetch an order.", {"order_id": {"type": "string"}}), + make_tool("send_email", "Send an email message.", {"to": {"type": "string"}}), +] + + +# ---- tools/list ------------------------------------------------------------- + +def test_list_shows_only_meta_tools_and_always_visible(): + t = RegexSearchTransform(always_visible=["send_email"]) + out = run(t.transform_tools(CATALOG, TransformContext())) + assert [x.name for x in out] == ["search_tools", "call_tool", "send_email"] + + +def test_meta_flag_keeps_tool_visible(): + flagged = make_tool("pinned", "x", meta={"alwaysVisible": True}) + t = RegexSearchTransform() + out = run(t.transform_tools([flagged, *CATALOG], TransformContext())) + assert "pinned" in [x.name for x in out] + + +def test_tool_names_are_configurable(): + t = RegexSearchTransform(search_tool_name="find", call_tool_name="run") + out = run(t.transform_tools(CATALOG, TransformContext())) + assert [x.name for x in out] == ["find", "run"] + + +def test_same_meta_names_rejected(): + with pytest.raises(ValueError): + RegexSearchTransform(search_tool_name="x", call_tool_name="x") + + +def test_search_tool_is_read_only(): + t = RegexSearchTransform() + out = run(t.transform_tools(CATALOG, TransformContext())) + assert out[0].annotations.read_only_hint is True + # and it serializes to the MCP wire name + assert out[0].model_dump(by_alias=True, exclude_none=True)["annotations"]["readOnlyHint"] is True + +# ---- browse ----------------------------------------------------------------- + +@pytest.mark.parametrize("q", ["", " ", "show tools", "list all tools", "what tools do you have"]) +def test_browse_queries(q): + assert is_browse_query(q) + + +@pytest.mark.parametrize("q", ["email", "get user", "(a+)+$", "^get_"]) +def test_task_queries_are_not_browse(q): + assert not is_browse_query(q) + + +def test_browse_returns_brief_index_of_whole_catalog(): + t = registered(RegexSearchTransform(), CATALOG) + out = run(search(t, query="show tools")) + assert out["mode"] == "browse" + assert [r["name"] for r in out["results"]] == ["get_order", "get_user", "send_email"] + assert set(out["results"][0]) == {"name", "summary"} + + +# ---- search ----------------------------------------------------------------- + +def test_literal_match_is_case_insensitive_and_ranks_name_first(): + t = registered(RegexSearchTransform(), CATALOG) + out = run(search(t, query="USER")) + assert [r["name"] for r in out["results"]] == ["get_user"] + + +def test_no_match_returns_empty_list_not_error(): + t = registered(RegexSearchTransform(), CATALOG) + out = run(search(t, query="zzzzz")) + assert out["results"] == [] + assert "No tools matched" in out["note"] + + +def test_limit_above_20_is_clamped(): + many = [make_tool(f"t{i:02d}", f"item {i}") for i in range(25)] + t = registered(RegexSearchTransform(), many) + out = run(search(t, query="item", limit=500)) + assert len(out["results"]) == 20 + assert "reduced" in out["note"] + + +def test_limit_is_respected_below_cap(): + many = [make_tool(f"t{i:02d}", f"item {i}") for i in range(25)] + t = registered(RegexSearchTransform(), many) + assert len(run(search(t, query="item", limit=3))["results"]) == 3 + + +def test_equal_scores_sort_by_name(): + tools = [make_tool("b_tool", "widget"), make_tool("a_tool", "widget")] + t = registered(RegexSearchTransform(), tools) + out = run(search(t, query="widget")) + assert [r["name"] for r in out["results"]] == ["a_tool", "b_tool"] + + +def test_detail_levels(): + t = registered(RegexSearchTransform(), CATALOG) + brief = run(search(t, query="user", detail="brief"))["results"] + detailed = run(search(t, query="user", detail="detailed"))["results"] + full = run(search(t, query="user", detail="full"))["results"] + + assert [r["name"] for r in detailed] == ["get_user"] + assert set(brief[0]) == {"name", "summary"} + assert detailed[0]["parameters"][0]["name"] == "user_id" + assert detailed[0]["parameters"][0]["required"] is False + assert "inputSchema" in full[0] + + +# ---- regex ------------------------------------------------------------------ + +def test_literal_by_default_treats_dot_literally(): + t = registered(RegexSearchTransform(), [make_tool("getXuser", "x")]) + assert run(search(t, query="get.user"))["results"] == [] + + +def test_regex_enabled_matches_pattern(): + t = registered(RegexSearchTransform(allow_regex=True), CATALOG) + out = run(search(t, query="^get_")) + assert [r["name"] for r in out["results"]] == ["get_order", "get_user"] + + +def test_invalid_regex_falls_back_to_literal(): + t = registered(RegexSearchTransform(allow_regex=True), CATALOG) + out = run(search(t, query="([")) + assert out["results"] == [] + assert "literal" in out["note"] + + +def test_catastrophic_pattern_returns_within_timeout_using_literal(): + nasty = make_tool("victim", "a" * 40 + "!") + t = registered(RegexSearchTransform(allow_regex=True, regex_timeout=1.0), [nasty, *CATALOG]) + start = time.monotonic() + out = run(search(t, query="(a+)+$")) + assert time.monotonic() - start < 8 + assert "timed out" in out["note"] + assert out["results"] == [] # literal "(a+)+$" matches nothing + + +def test_long_pattern_is_not_run_as_regex(): + t = registered(RegexSearchTransform(allow_regex=True, max_pattern_length=10), CATALOG) + out = run(search(t, query="x" * 50)) + assert "longer than" in out["note"] + + +# ---- call_tool -------------------------------------------------------------- + +def test_call_tool_dispatches_through_context_skipping_this_transform(): + t = registered(RegexSearchTransform(), CATALOG) + ctx = FakeCtx() + tool = run(t.resolve_tool("call_tool", _none, ctx)) + run(tool.handler(CallToolInput(name="get_user", arguments={"user_id": "1"}), ctx)) + assert ctx.calls == [("get_user", {"user_id": "1"}, "regex_search")] + + +@pytest.mark.parametrize("target", ["search_tools", "call_tool"]) +def test_call_tool_rejects_meta_tools(target): + t = registered(RegexSearchTransform(), CATALOG) + ctx = FakeCtx() + tool = run(t.resolve_tool("call_tool", _none, ctx)) + with pytest.raises(ToolArgumentError): + run(tool.handler(CallToolInput(name=target), ctx)) + assert ctx.calls == [] + + +def test_unknown_names_fall_through_to_next_resolver(): + t = RegexSearchTransform() + + async def nxt(name): + return f"real:{name}" + + assert run(t.resolve_tool("get_user", nxt, TransformContext())) == "real:get_user" \ No newline at end of file diff --git a/tests/test_transforms_search_app.py b/tests/test_transforms_search_app.py new file mode 100644 index 0000000..34d33d0 --- /dev/null +++ b/tests/test_transforms_search_app.py @@ -0,0 +1,73 @@ +import asyncio + +import mcp.types as types +from pydantic import BaseModel + +from nitrostack import ExecutionContext, injectable, module, tool +from nitrostack.testing import NitroTestingModule +from nitrostack.transforms.search import RegexSearchTransform +from nitrostack import use_guards + +class In(BaseModel): + q: str = "" + + +@injectable() +class C: + @tool(name="alpha", description="first tool about apples", input_schema=In) + async def alpha(self, input: In, context: ExecutionContext) -> str: + return "alpha-result" + + @tool(name="beta", description="second tool about bananas", input_schema=In) + async def beta(self, input: In, context: ExecutionContext) -> str: + return "beta-result" + + +@module(name="m", controllers=[C]) +class M: + pass + + +def run(coro): + return asyncio.run(coro) + + +async def _list(h): + srv = h.app.mcp_server + return (await srv.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list"))).root + + +def test_tools_list_returns_only_meta_tools(): + async def go(): + h = await NitroTestingModule.create(M, transforms=[RegexSearchTransform()]) + return [t.name for t in (await _list(h)).tools] + + assert run(go()) == ["search_tools", "call_tool"] + + +def test_search_then_call_runs_the_real_tool(): + async def go(): + h = await NitroTestingModule.create(M, transforms=[RegexSearchTransform()]) + found = await h.call_tool("search_tools", {"input": {"query": "bananas"}}) + called = await h.call_tool("call_tool", {"input": {"name": "beta", "arguments": {"q": "x"}}}) + return found, called + + found, called = run(go()) + assert "beta" in str(found) + assert "beta-result" in str(called) + + + +def test_call_tool_cannot_call_itself(): + async def go(): + h = await NitroTestingModule.create( + M, transforms=[RegexSearchTransform()] + ) + return await h.call_tool( + "call_tool", + {"input": {"name": "call_tool"}}, + ) + + result = run(go()) + assert "cannot be called" in str(result) diff --git a/tests/test_transformsapp.py b/tests/test_transformsapp.py new file mode 100644 index 0000000..779cd7b --- /dev/null +++ b/tests/test_transformsapp.py @@ -0,0 +1,127 @@ + +import json +import pathlib + +import mcp.types as types +import pytest + +from nitrostack.testing import NitroTestingModule +from nitrostack.transforms import CatalogTransform, McpTransformBase +from tests._baseline_catalog import ERAS, In, M + + +BASELINE = ( + pathlib.Path(__file__).parent + / "fixtures" + / "tools_list_baseline.json" +) + + +async def _list(h): + srv = h.app.mcp_server + response = ( + await srv.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list") + ) + ).root + return response + + +@pytest.mark.asyncio +@pytest.mark.parametrize("era", ERAS) +async def test_no_transforms_output_is_byte_identical_to_baseline( + era, monkeypatch +): + monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", era) + + h = await NitroTestingModule.create(M) + response = await _list(h) + + expected = json.loads( + BASELINE.read_text(encoding="utf-8") + )[era] + + actual = response.model_dump_json( + by_alias=True, + exclude_none=True, + ) + + assert actual == expected + + +class DropBeta(CatalogTransform): + name = "drop_beta" + + def apply_transform(self, tools, ctx): + return [tool for tool in tools if tool.name != "beta"] + + +class Suffix(CatalogTransform): + name = "suffix" + + def apply_transform(self, tools, ctx): + return [ + tool.model_copy( + update={ + "description": (tool.description or "") + "!" + } + ) + for tool in tools + ] + + +@pytest.mark.asyncio +async def test_two_transforms_compose_in_declared_order_for_list(): + h = await NitroTestingModule.create( + M, + transforms=[DropBeta(), Suffix()], + ) + + response = await _list(h) + + assert [tool.name for tool in response.tools] == ["alpha"] + assert response.tools[0].description == "first!" + + +class Boom(McpTransformBase): + name = "boom" + + async def transform_tools(self, tools, ctx): + raise RuntimeError("bad transform") + + +@pytest.mark.asyncio +async def test_failing_transform_returns_error_and_server_keeps_serving(): + h = await NitroTestingModule.create( + M, + transforms=[Boom()], + ) + + with pytest.raises(Exception): + await _list(h) + + # A transform failure must not stop the server from handling tool calls. + result = await h.call_tool("alpha", {"input": {"q": "x"}}) + assert result is not None + + +@pytest.mark.asyncio +async def test_dispose_runs_on_shutdown(): + disposed = [] + + class D(McpTransformBase): + name = "d" + + async def dispose(self): + disposed.append(True) + + h = await NitroTestingModule.create( + M, + transforms=[D()], + ) + + # Exercise disposal directly because this harness may not expose + # a public application-shutdown method. + await h.app._transforms.dispose() + + assert disposed == [True] diff --git a/tests/test_transports.py b/tests/test_transports.py index 57a19bb..e976123 100644 --- a/tests/test_transports.py +++ b/tests/test_transports.py @@ -89,7 +89,7 @@ def _free_port() -> int: async def _build_app() -> McpApplication: - @mcp_app(module=TransportsTestModule, server=ServerConfig(name="transports-test-server")) + @mcp_app(module=TransportsTestModule, server=ServerConfig(name="transports-test-server", protocol_era="legacy")) class _TestApp: pass @@ -165,7 +165,9 @@ def test_http_health_and_cors(): preflight = client.options( "/mcp", - headers={"Origin": "http://example.com", "Access-Control-Request-Method": "POST"}, + headers={"Origin": "http://example.com", "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": + "Mcp-Session-Id, Mcp-Name, Mcp-Method, MCP-Protocol-Version"}, ) assert preflight.status_code == 200 assert preflight.headers.get("access-control-allow-origin") == "*" diff --git a/tests/test_validate_vendored.py b/tests/test_validate_vendored.py new file mode 100644 index 0000000..8b6b298 --- /dev/null +++ b/tests/test_validate_vendored.py @@ -0,0 +1,32 @@ +"""Validate must not treat vendored SDK copies as project code.""" + +from pathlib import Path + +from nitrostack.cli.validators import validate_project + + +def test_validate_skips_the_vendored_sdk(tmp_path: Path): + """`init` vendors the SDK; its testing helpers apply @mcp_app inside functions.""" + (tmp_path / "pyproject.toml").write_text( + "[project]\n" + 'name = "vendored"\n' + 'version = "0.1.0"\n' + "dependencies = [\n" + ' "nitrostack",\n' + "]\n", + encoding="utf-8", + ) + sdk = tmp_path / "vendor" / "nitrostack" / "nitrostack" / "testing" + sdk.mkdir(parents=True) + (sdk / "__init__.py").write_text( + "from nitrostack import mcp_app, ServerConfig\n\n" + "def create(module):\n" + " @mcp_app(module=module, server=ServerConfig(name='test'))\n" + " class TestApp:\n" + " pass\n" + " return TestApp\n", + encoding="utf-8", + ) + + issues = validate_project(str(tmp_path)) + assert not [issue for issue in issues if "vendor" in issue.path], [i.format() for i in issues] \ No newline at end of file diff --git a/tests/test_validate_widgets.py b/tests/test_validate_widgets.py new file mode 100644 index 0000000..2a0a251 --- /dev/null +++ b/tests/test_validate_widgets.py @@ -0,0 +1,408 @@ +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from nitrostack.cli.validators import _collect_widget_routes, validate_project, validate_widgets + +TOOL = ( + "from nitrostack import tool, widget\n\n" + "@tool(name='show')\n" + "@widget('card')\n" + "async def show(self, input, context):\n" + " return {}\n" +) + + +def _project(tmp_path: Path, source: str = TOOL) -> Path: + (tmp_path / "tools.py").write_text(source, encoding="utf-8") + return tmp_path + + +def _write_html(root: Path, route: str, html: str) -> None: + out = root / "widgets" / "out" + out.mkdir(parents=True, exist_ok=True) + (out / f"{route}.html").write_text(html, encoding="utf-8") + + +def test_missing_widget_html_is_a_warning(tmp_path: Path): + issues = validate_widgets(str(_project(tmp_path))) + assert len(issues) == 1 + assert issues[0].severity == "warning" + assert "file is missing" in issues[0].message + assert "card.html" in issues[0].message + assert "ui://widget/card.html" in issues[0].message + assert issues[0].path == "tools.py" + + +def test_empty_widget_html_is_a_warning(tmp_path: Path): + _write_html(_project(tmp_path), "card", " \n") + issues = validate_widgets(str(tmp_path)) + assert len(issues) == 1 + assert issues[0].severity == "warning" + assert "file is empty" in issues[0].message + + +def test_valid_widget_html_passes(tmp_path: Path): + _write_html(_project(tmp_path), "card", "") + assert validate_widgets(str(tmp_path)) == [] + + +def test_widget_options_route_is_collected(tmp_path: Path): + src = "from nitrostack import WidgetOptions, widget\n\n@widget(WidgetOptions(route='chart'))\ndef f(): ...\n" + issues = validate_widgets(str(_project(tmp_path, src))) + assert len(issues) == 1 + assert "'chart'" in issues[0].message + + +def test_invalid_route_is_reported_not_resolved(tmp_path: Path): + issues = validate_widgets(str(_project(tmp_path, "@widget('../evil')\ndef f(): ...\n"))) + assert len(issues) == 1 + assert "not a single alphanumeric path segment" in issues[0].message + + +def test_duplicate_routes_are_reported_once(tmp_path: Path): + (tmp_path / "a.py").write_text(TOOL, encoding="utf-8") + (tmp_path / "b.py").write_text(TOOL, encoding="utf-8") + assert len(validate_widgets(str(tmp_path))) == 1 + + +def test_vendored_sdk_is_ignored(tmp_path: Path): + vendored = tmp_path / "vendor" / "nitrostack" + vendored.mkdir(parents=True) + (vendored / "x.py").write_text(TOOL, encoding="utf-8") + assert validate_widgets(str(tmp_path)) == [] + + +def test_project_without_widgets_has_no_widget_issues(tmp_path: Path): + (tmp_path / "plain.py").write_text("x = 1\n", encoding="utf-8") + assert validate_widgets(str(tmp_path)) == [] + + +def test_validate_project_reports_widget_warnings_only(tmp_path: Path, monkeypatch): + monkeypatch.setattr(sys, "path", list(sys.path)) + _project(tmp_path) + issues = [i for i in validate_project(str(tmp_path)) if "widget route" in i.message] + assert len(issues) == 1 + assert issues[0].severity == "warning" + +HELPER = ( + "from nitrostack import WidgetOptions, widget\n\n" + "def pizzaz_widget(route: str) -> WidgetOptions:\n" + " return WidgetOptions(route=route, prefers_border=True)\n\n" + "class helpers:\n" + " @staticmethod\n" + " def make(route):\n" + " return WidgetOptions(route=route)\n\n" + "class T:\n" + " @widget(pizzaz_widget('pizza-map'))\n" + " def a(self): ...\n\n" + " @widget(helpers.make(\"pizza-list\"))\n" + " def b(self): ...\n\n" + " @widget(pizzaz_widget(route='pizza-shop', extra=1))\n" + " def c(self): ...\n" +) + + +def test_helper_wrapped_routes_are_collected(tmp_path: Path): + issues = validate_widgets(str(_project(tmp_path, HELPER))) + assert sorted(i.message.split("'")[1] for i in issues) == ["pizza-list", "pizza-map", "pizza-shop"] + assert all("file is missing" in i.message for i in issues) + + +def test_helper_wrapped_route_with_html_passes(tmp_path: Path): + _project(tmp_path, HELPER) + for route in ("pizza-map", "pizza-list", "pizza-shop"): + _write_html(tmp_path, route, "") + assert validate_widgets(str(tmp_path)) == [] + + +def test_route_is_read_from_the_argument_that_feeds_it(tmp_path: Path): + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def helper(flag, route): return WidgetOptions(route=route)\n" + "@widget(helper(True, 'second'))\ndef a(): ...\n" + "@widget(helper('first', 'third'))\ndef b(): ...\n" + "@widget(helper(flag=False, route='by-keyword'))\ndef c(): ...\n" + ) + assert sorted(_routes(tmp_path, {"tools.py": src})) == ["by-keyword", "second", "third"] + + +def test_unrelated_helper_call_is_not_taken_as_a_route(tmp_path: Path): + # Not defined in the project and never builds a WidgetOptions: no false warning. + src = "@widget(something('x'))\ndef f(): ...\n" + assert validate_widgets(str(_project(tmp_path, src))) == [] + src = "def something(name): return {'n': name}\n@widget(something('x'))\ndef f(): ...\n" + assert validate_widgets(str(_project(tmp_path, src))) == [] + + +def test_helper_defined_in_another_file_is_found(tmp_path: Path): + (tmp_path / "helpers.py").write_text( + "from nitrostack import WidgetOptions\ndef panel(route): return WidgetOptions(route=route)\n", + encoding="utf-8", + ) + src = "from helpers import panel\n@widget(panel('chart'))\ndef f(): ...\n" + issues = validate_widgets(str(_project(tmp_path, src))) + assert len(issues) == 1 and "'chart'" in issues[0].message + + +def test_widget_options_positional_route_is_collected(tmp_path: Path): + src = "from nitrostack import WidgetOptions, widget\n@widget(WidgetOptions('chart'))\ndef f(): ...\n" + issues = validate_widgets(str(_project(tmp_path, src))) + assert len(issues) == 1 and "'chart'" in issues[0].message + + +def test_invalid_helper_route_is_reported(tmp_path: Path): + src = "def helper(r): return WidgetOptions(route=r)\n@widget(helper('../evil'))\ndef f(): ...\n" + issues = validate_widgets(str(_project(tmp_path, src))) + assert len(issues) == 1 + assert "not a single alphanumeric path segment" in issues[0].message + + +TEMPLATES = Path(__file__).resolve().parents[1] / "nitrostack" / "templates" + + +@pytest.mark.parametrize("template, expected", [ + ("pizzaz", {"pizza-map", "pizza-list", "pizza-shop"}), + ("starter", {"calculator-result"}), + ("flight-booking", { + "flight-search-results", "flight-details", "airport-search", + "order-summary", "seat-selection", "order-cancellation", + }), +]) +def test_shipped_templates_report_every_widget_route(template, expected): + routes = {route for route, _ in _collect_widget_routes(str(TEMPLATES / template))} + assert routes == expected + + +def test_pizzaz_template_warns_when_a_widget_html_is_removed(tmp_path: Path): + project = tmp_path / "pizzaz" + shutil.copytree(TEMPLATES / "pizzaz", project) + assert validate_widgets(str(project)) == [] + (project / "widgets" / "out" / "pizza-list.html").unlink() + issues = validate_widgets(str(project)) + assert len(issues) == 1 + assert "'pizza-list'" in issues[0].message and "file is missing" in issues[0].message + + +def test_cli_validate_checks_pizzaz_helper_wrapped_widgets(tmp_path: Path): + project = tmp_path / "pizzaz" + shutil.copytree(TEMPLATES / "pizzaz", project) + + def validate(): + return subprocess.run( + [sys.executable, "-m", "nitrostack.cli.main", "validate"], + cwd=project, env={**os.environ, "PYTHONPATH": str(TEMPLATES.parents[1])}, + capture_output=True, text=True, encoding="utf-8", timeout=60, + ) + + clean = validate() + assert clean.returncode == 0, clean.stdout + clean.stderr + assert "widget route" not in clean.stdout + + (project / "widgets" / "out" / "pizza-list.html").unlink() + broken = validate().stdout + assert "widget route 'pizza-list'" in broken and "file is missing" in broken + assert "pizza-map" not in broken and "pizza-shop" not in broken + + +def _routes(tmp_path: Path, files: dict) -> list: + for name, text in files.items(): + target = tmp_path / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + return [route for route, _ in _collect_widget_routes(str(tmp_path))] + + +FACTORY = "from nitrostack import WidgetOptions\ndef panel(route): return WidgetOptions(route=route)\n" + + +def test_argument_that_does_not_feed_route_is_not_a_route(tmp_path: Path): + # panel("dashboard") builds the "card" widget; dashboard.html is never used. + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def panel(name, description=None):\n" + " return WidgetOptions(route='card', description=description)\n" + "@widget(panel('dashboard'))\ndef f(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["card"] + assert validate_widgets(str(tmp_path))[0].message.startswith("widget route 'card'") + assert len(validate_widgets(str(tmp_path))) == 1 + + +def test_reassigned_or_forwarded_to_something_else_is_not_a_factory(tmp_path: Path): + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def fixed(route):\n route = 'always-this'\n return WidgetOptions(route=route)\n" + "def other(route): return WidgetOptions(route='card', description=route)\n" + "@widget(fixed('x'))\ndef a(): ...\n@widget(other('y'))\ndef b(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["card"] + + +def test_same_helper_name_in_another_module_is_not_a_factory(tmp_path: Path): + files = { + "factory.py": FACTORY, + "unrelated.py": ( + "from nitrostack import widget\n" + "def panel(name): return {'name': name}\n" + "@widget(panel('not-a-route'))\ndef f(): ...\n" + ), + "undefined.py": "from nitrostack import widget\n@widget(panel('also-not'))\ndef g(): ...\n", + "other_lib.py": ( + "from some_library import panel\nfrom nitrostack import widget\n" + "@widget(panel('third-party'))\ndef h(): ...\n" + ), + } + assert _routes(tmp_path, files) == [] + + +def test_factory_is_resolved_through_the_calling_modules_imports(tmp_path: Path): + files = { + "factory.py": FACTORY, + "plain.py": "from factory import panel\nfrom nitrostack import widget\n@widget(panel('plain'))\ndef a(): ...\n", + "aliased.py": "from factory import panel as build\nfrom nitrostack import widget\n@widget(build('aliased'))\ndef b(): ...\n", + "module.py": "import factory as fx\nfrom nitrostack import widget\n@widget(fx.panel('via-module'))\ndef c(): ...\n", + "pkg/__init__.py": "", + "pkg/helpers.py": FACTORY, + "pkg/tools.py": "from .helpers import panel\nfrom nitrostack import widget\n@widget(panel('relative'))\ndef d(): ...\n", + "pkg/sub.py": "from pkg import helpers\nfrom nitrostack import widget\n@widget(helpers.panel('pkg-module'))\ndef e(): ...\n", + } + assert sorted(_routes(tmp_path, files)) == ["aliased", "pkg-module", "plain", "relative", "via-module"] + + +def test_a_local_definition_wins_over_an_import_of_the_same_name(tmp_path: Path): + files = { + "factory.py": FACTORY, + "tools.py": ( + "from factory import panel\nfrom nitrostack import widget\n" + "def panel(name): return {'name': name}\n" + "@widget(panel('shadowed'))\ndef f(): ...\n" + ), + } + assert _routes(tmp_path, files) == [] + + +def test_a_factory_that_forwards_to_another_factory_is_found(tmp_path: Path): + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def base(route): return WidgetOptions(route=route)\n" + "def wrapped(r): return base(r)\n" + "@widget(wrapped('deep'))\ndef f(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["deep"] + + +def test_unimported_widget_options_alias_and_attribute_forms(tmp_path: Path): + src = ( + "import nitrostack\nfrom nitrostack import WidgetOptions as WO, widget\n" + "@widget(WO(route='aliased-options'))\ndef a(): ...\n" + "@nitrostack.widget(nitrostack.WidgetOptions('attribute-form'))\ndef b(): ...\n" + ) + assert sorted(_routes(tmp_path, {"tools.py": src})) == ["aliased-options", "attribute-form"] + + +def test_a_file_that_does_not_parse_still_yields_its_literal_routes(tmp_path: Path): + src = "@widget('legacy')\ndef f(:\n pass\nWidgetOptions(route='legacy-options')\n" + assert sorted(_routes(tmp_path, {"broken.py": src})) == ["legacy", "legacy-options"] + + +def test_widget_options_reexported_by_a_project_package_is_followed(tmp_path: Path): + files = { + "shared/__init__.py": "from nitrostack import WidgetOptions, widget\n", + "tools.py": ( + "from shared import WidgetOptions, widget\n" + "@widget(WidgetOptions(route='missing-card'))\ndef a(): ...\n" + ), + } + assert sorted(_routes(tmp_path, files)) == ["missing-card"] + + +def test_reexport_through_an_alias_and_two_hops_is_followed(tmp_path: Path): + files = { + "core/options.py": "from nitrostack import WidgetOptions as Options, widget as ui\n", + "core/__init__.py": "from .options import Options, ui\n", + "shared.py": "from core import Options as Opts, ui as sdk_widget\n", + "tools.py": ( + "from shared import Opts, sdk_widget\n" + "@sdk_widget('direct')\ndef a(): ...\n" + "@sdk_widget(Opts(route='via-options'))\ndef b(): ...\n" + ), + } + assert sorted(_routes(tmp_path, files)) == ["direct", "via-options"] + + +def test_reexported_factory_is_still_a_factory(tmp_path: Path): + files = { + "shared/__init__.py": "from .helpers import panel\n", + "shared/helpers.py": FACTORY, + "tools.py": "from nitrostack import widget\nfrom shared import panel\n@widget(panel('reexported'))\ndef a(): ...\n", + } + assert _routes(tmp_path, files) == ["reexported"] + + +def test_import_cycle_between_reexporting_modules_terminates(tmp_path: Path): + files = { + "a.py": "from b import thing\n", + "b.py": "from a import thing\n", + "tools.py": "from a import thing\n@thing('x')\ndef f(): ...\n", + } + assert _routes(tmp_path, files) == [] + + +def test_a_name_reexported_from_a_non_sdk_module_is_not_the_sdk(tmp_path: Path): + files = { + "shared/__init__.py": "from .own import WidgetOptions\n", + "shared/own.py": "class WidgetOptions:\n def __init__(self, route): ...\n", + "tools.py": "from shared import WidgetOptions\nWidgetOptions(route='not-a-widget')\n", + } + assert _routes(tmp_path, files) == [] + + +def test_missing_html_check_runs_for_a_reexported_widget_options(tmp_path: Path): + (tmp_path / "shared").mkdir() + (tmp_path / "shared" / "__init__.py").write_text("from nitrostack import WidgetOptions, widget\n") + (tmp_path / "tools.py").write_text( + "from shared import WidgetOptions, widget\n" + "@widget(WidgetOptions(route='missing-card'))\ndef a(): ...\n" + ) + issues = validate_widgets(str(tmp_path)) + assert [i.severity for i in issues] == ["warning"] + assert "missing-card.html" in issues[0].message + + +@pytest.mark.parametrize( + "decorator, imports", + [ + ("@pytest.mark.widget('smoke')", "import pytest\n"), + ("@marks.widget('smoke')", "from tests import marks\n"), + ("@widget('smoke')", "from other_lib import widget\n"), + ("@widget('smoke')", "def widget(name):\n return lambda f: f\n"), + ("@app.widget('smoke')", "from fastapi import FastAPI\napp = FastAPI()\n"), + ], +) +def test_widget_decorators_that_are_not_the_sdks_are_ignored(tmp_path: Path, decorator, imports): + src = f"{imports}\n{decorator}\ndef test_it(): ...\n" + assert _routes(tmp_path, {"test_tools.py": src}) == [] + assert validate_widgets(str(tmp_path)) == [] + + +def test_pytest_widget_marker_does_not_hide_the_real_widget(tmp_path: Path): + src = ( + "import pytest\nfrom nitrostack import widget\n" + "@pytest.mark.widget('smoke')\ndef test_it(): ...\n" + "@widget('card')\ndef real(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["card"] + + +def test_qualified_sdk_decorators_are_still_collected(tmp_path: Path): + src = ( + "import nitrostack\nimport nitrostack.decorators as deco\n" + "@nitrostack.widget('top')\ndef a(): ...\n" + "@deco.widget('submodule')\ndef b(): ...\n" + ) + assert sorted(_routes(tmp_path, {"tools.py": src})) == ["submodule", "top"] diff --git a/tests/test_vendor.py b/tests/test_vendor.py index f53be41..9449ca9 100644 --- a/tests/test_vendor.py +++ b/tests/test_vendor.py @@ -6,11 +6,14 @@ import pytest from nitrostack.cli.vendor import ( + apply_runtime_nitrostack_pins, copy_running_nitrostack, ensure_vendored_nitrostack, pin_project_to_vendor, running_nitrostack_root, + runtime_nitrostack_requirement, ) +import nitrostack def test_running_nitrostack_root_is_the_sdk_checkout(): @@ -34,11 +37,12 @@ def test_ensure_vendored_pins_pyproject_and_requirements(tmp_path: Path): (tmp_path / "requirements.txt").write_text("nitrostack>=0.3.2\n", encoding="utf-8") dest = ensure_vendored_nitrostack(str(tmp_path), quiet=True) assert dest and os.path.isdir(dest) + expected = runtime_nitrostack_requirement() pyproject = (tmp_path / "pyproject.toml").read_text(encoding="utf-8") - assert 'dependencies = ["nitrostack"]' in pyproject + assert f'dependencies = ["{expected}"]' in pyproject assert "file:./vendor" not in pyproject assert 'nitrostack = { path = "vendor/nitrostack" }' in pyproject - assert (tmp_path / "requirements.txt").read_text(encoding="utf-8").strip() == "nitrostack" + assert (tmp_path / "requirements.txt").read_text(encoding="utf-8").strip() == expected pin_project_to_vendor(tmp_path) again = (tmp_path / "pyproject.toml").read_text(encoding="utf-8") assert again.count('nitrostack = { path = "vendor/nitrostack" }') == 1 @@ -53,11 +57,12 @@ def test_pin_strips_file_url_that_breaks_cloud_uv_wheels(tmp_path: Path): (tmp_path / "requirements.txt").write_text("nitrostack @ file:./vendor/nitrostack\n", encoding="utf-8") (tmp_path / "vendor" / "nitrostack").mkdir(parents=True) pin_project_to_vendor(tmp_path) + expected = runtime_nitrostack_requirement() text = (tmp_path / "pyproject.toml").read_text(encoding="utf-8") - assert 'dependencies = ["nitrostack"]' in text + assert f'dependencies = ["{expected}"]' in text assert "file:./vendor" not in text assert 'nitrostack = { path = "vendor/nitrostack" }' in text - assert (tmp_path / "requirements.txt").read_text(encoding="utf-8").strip() == "nitrostack" + assert (tmp_path / "requirements.txt").read_text(encoding="utf-8").strip() == expected def test_minimal_pyproject_uses_distribution_version(tmp_path: Path, monkeypatch): @@ -69,6 +74,7 @@ def test_minimal_pyproject_uses_distribution_version(tmp_path: Path, monkeypatch text = (dest / "pyproject.toml").read_text(encoding="utf-8") assert 'version = "9.9.9"' in text assert "0.3.2" not in text + assert "posthog" not in text def test_distribution_version_has_no_hardcoded_fallback(monkeypatch): @@ -85,6 +91,25 @@ def _missing(_name: str) -> str: _distribution_version() +def test_requirements_from_project_pins_nitrostack_minimum(tmp_path: Path) -> None: + from nitrostack.cli._pack_metadata import requirements_from_project + + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "demo"\nversion = "0.1.0"\n' + 'dependencies = ["uvicorn[standard]>=0.20", "nitrostack>=0.3.0"]\n', + encoding="utf-8", + ) + deps = requirements_from_project(str(tmp_path)) + assert "uvicorn[standard]>=0.20" in deps + assert runtime_nitrostack_requirement() in deps + + +def test_apply_runtime_nitrostack_pins_replaces_plain_name(): + spec = runtime_nitrostack_requirement() + deps = apply_runtime_nitrostack_pins(["mcp>=2", "nitrostack", "nitrostack==0.4.2"]) + assert deps == ["mcp>=2", spec, spec] + + def test_ensure_vendored_skips_the_sdk_checkout(): root = running_nitrostack_root() assert ensure_vendored_nitrostack(str(root), quiet=True) is None diff --git a/tests/test_widget_registry.py b/tests/test_widget_registry.py new file mode 100644 index 0000000..ae3d010 --- /dev/null +++ b/tests/test_widget_registry.py @@ -0,0 +1,315 @@ +"""Widget manifests from real registrations, templates and MCP transports.""" + +import asyncio +from concurrent.futures import ThreadPoolExecutor +import json +import os +from pathlib import Path +import subprocess +import sys + +import mcp.types as types +from pydantic import BaseModel +import pytest +from starlette.testclient import TestClient + +from nitrostack import ( + DIContainer, ExecutionContext, ToolExamples, WidgetCsp, WidgetExample, + WidgetManifest, WidgetMetadata, WidgetOptions, WidgetRegistry, + get_widget_registry, module, resource, tool, widget, +) +from nitrostack.core.app import McpApplication, ServerConfig, mcp_app +from nitrostack.core.errors import ResourceNotFoundError +from nitrostack.widgets.mcp_meta import resource_read_contents_meta + +ROOT = Path(__file__).resolve().parents[1] +PROBE = ROOT / "tests" / "support" / "widget_registry_probe.py" +URI = "widget://examples" +META = { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": {"name": "registry-test", "version": "1"}, + "io.modelcontextprotocol/clientCapabilities": {}, +} + + +class Empty(BaseModel): + pass + + +@pytest.fixture(autouse=True) +def clean_state(monkeypatch): + DIContainer.reset() + for name in ("NITRO_MCP_PROTOCOL_VERSION", "MCP_STATELESS"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("NITROSTACK_APP_MODE", "universal") + yield + DIContainer.reset() + + +def make_app(specs=(), *, era="auto", collision=False): + methods = {} + for name, spec, example in specs: + async def handler(self, input: Empty, context: ExecutionContext): + raise AssertionError("Registry construction must not execute tools") + methods[name] = tool(name, f"Description of {name}", Empty, examples=example)( + widget(spec)(handler) + ) + if collision: + @resource(URI, "Custom", "Custom resource") + async def custom(self, context: ExecutionContext): + return "custom" + methods["custom"] = custom + provider = type("RegistryTools", (), methods) + + @module(name="registry-tests", providers=[provider]) + class AppModule: + pass + + @mcp_app(module=AppModule, server=ServerConfig(name="registry-test", protocol_era=era)) + class App: + pass + + return McpApplication(App) + + +def test_public_exports_and_empty_app(): + import nitrostack.widgets as widgets + for symbol in (WidgetExample, WidgetManifest, WidgetMetadata, WidgetRegistry): + assert getattr(widgets, symbol.__name__) is symbol + app = make_app() + assert get_widget_registry(app) is app.widget_registry + assert widgets.get_widget_registry(app) is app.widget_registry + assert app.widget_registry.get_manifest().to_dict() == { + "widgets": [], "count": 0, "loaded": True, + } + assert URI not in app._resources + with pytest.raises(ResourceNotFoundError): + asyncio.run(app._read_resource(URI)) + + +@pytest.mark.parametrize("spec", [ + "example", "/widget/example.html", WidgetOptions(route="example", html="

test

"), + {"route": "example", "html": "

test

"}, +]) +def test_decorator_forms_and_resource_consistency(spec): + app = make_app([("example_tool", spec, None)]) + entry = app.widget_registry.get_all_widgets()[0] + assert entry.route == "example" + assert entry.uri == "ui://widget/example.html" + assert entry.mime_type == "text/html;profile=mcp-app" + assert entry.examples == [] + assert entry.tool_names == ["example_tool"] + component = app._tools["example_tool"].component + contents = asyncio.run(app._read_resource(entry.uri))[0] + assert contents.content == component.get_bundle() + assert contents.mime_type == entry.mime_type + assert contents.meta == resource_read_contents_meta(component) + + +@pytest.mark.parametrize("mode,mime", [ + ("openai", "text/html"), ("mcp-app", "text/html;profile=mcp-app"), + ("universal", "text/html;profile=mcp-app"), +]) +def test_helper_metadata_and_app_modes(monkeypatch, mode, mime): + monkeypatch.setenv("NITROSTACK_APP_MODE", mode) + + def options(): + return WidgetOptions( + route="helper", html="

not in manifest

", prefers_border=True, + domain="https://widgets.example.com", can_invoke_tools=True, + csp=WidgetCsp(connect_domains=["https://api.example.com"]), + ) + + app = make_app([("helper_tool", options(), None)]) + entry = app.widget_registry.get_all_widgets()[0] + assert entry.mime_type == mime + assert entry.metadata == resource_read_contents_meta(app._tools["helper_tool"].component) + assert bool(entry.metadata.get("ui")) == (mode != "openai") + assert ("openai/widgetCSP" in entry.metadata) == (mode != "mcp-app") + assert "not in manifest" not in json.dumps(app.widget_registry.get_manifest().to_dict()) + + +def test_duplicates_order_examples_and_copy_isolation(): + original = ToolExamples(input={"nested": [False, None, 0]}, output=[], description="A") + app = make_app([ + ("z_tool", WidgetOptions(route="shared", description="Z", prefers_border=False), ToolExamples({}, False)), + ("a_tool", WidgetOptions(route="shared", description="A", prefers_border=True), original), + ("b_tool", "another", None), + ]) + registry = app.widget_registry + expected = registry.get_manifest().to_dict() + assert [w["route"] for w in expected["widgets"]] == ["another", "shared"] + shared = registry.get_widget("ui://widget/shared.html") + assert shared.name == "a_tool" and shared.description == "A" + assert shared.tool_names == ["a_tool", "z_tool"] + assert shared.metadata["ui"]["prefersBorder"] is True + assert [e.tool_name for e in shared.examples] == ["a_tool", "z_tool"] + assert shared.examples[0].input == {"nested": [False, None, 0]} + assert shared.examples[0].output == [] + assert shared.examples[1].output is False + # Neither source declarations nor nested values returned through any API + # may modify the stored snapshot. + original.input["nested"].append("changed") + shared.examples[0].input.clear() + shared.tool_names.clear() + registry.get_all_widgets()[1].metadata.clear() + registry.get_manifest().widgets.clear() + expected["widgets"][0]["metadata"]["changed"] = True + assert "changed" not in json.dumps(registry.get_manifest().to_dict()) + assert registry.get_widget("missing") is None + + +def test_applications_do_not_share_state(): + first = make_app([("one", "one", None)]) + second = make_app([("two", "two", None)]) + assert [w.route for w in first.widget_registry.get_all_widgets()] == ["one"] + assert [w.route for w in second.widget_registry.get_all_widgets()] == ["two"] + + +def test_manifest_order_does_not_depend_on_registration_order(): + specs = [ + ("z_tool", WidgetOptions(route="shared", description="Z"), ToolExamples(0, None)), + ("a_tool", WidgetOptions(route="shared", description="A"), ToolExamples(False, {})), + ("other", "another", None), + ] + first = make_app(specs).widget_registry.get_manifest().to_dict() + second = make_app(list(reversed(specs))).widget_registry.get_manifest().to_dict() + assert first == second + + +def test_manifest_does_not_include_environment_credentials(monkeypatch): + monkeypatch.setenv("MAPBOX_TOKEN", "widget-registry-secret-sentinel") + app = make_app([("one", WidgetOptions(route="one", html="

html-sentinel

"), None)]) + serialized = json.dumps(app.widget_registry.get_manifest().to_dict()) + assert "widget-registry-secret-sentinel" not in serialized + assert "html-sentinel" not in serialized + + +def test_reserved_uri_collision_only_when_widgets_exist(): + with pytest.raises(ValueError, match="reserved for the widget manifest"): + make_app([("one", "one", None)], collision=True) + app = make_app(collision=True) + assert asyncio.run(app._read_resource(URI))[0].content == "custom" + + +def test_additional_server_has_manifest_handlers(): + app = make_app([("one", "one", None)]) + server = app.create_configured_mcp_server() + listed = asyncio.run(server.request_handlers[types.ListResourcesRequest]( + types.ListResourcesRequest(method="resources/list") + )).root + assert URI in {str(entry.uri) for entry in listed.resources} + read = asyncio.run(server.request_handlers[types.ReadResourceRequest]( + types.ReadResourceRequest(method="resources/read", params=types.ReadResourceRequestParams(uri=URI)) + )).root + assert json.loads(read.contents[0].text) == app.widget_registry.get_manifest().to_dict() + + +@pytest.mark.parametrize("era", ["legacy", "modern"]) +@pytest.mark.parametrize("has_widgets", [False, True]) +def test_http_manifest(era, has_widgets): + app = make_app([("one", "one", None)] if has_widgets else [], era=era) + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} + with TestClient(app.get_combined_app(json_response=True)) as client: + def rpc(method, params, request_id): + request_headers = {**headers, "Mcp-Method": method} + if "uri" in params: + request_headers["Mcp-Name"] = params["uri"] + response = client.post("/mcp", headers=request_headers, json={ + "jsonrpc": "2.0", "id": request_id, "method": method, "params": params, + }) + assert response.status_code == 200, response.text + return response.json() + + if era == "legacy": + init = client.post("/mcp", headers=headers, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}, + }, + }) + assert init.status_code == 200, init.text + headers["mcp-session-id"] = init.headers["mcp-session-id"] + response = client.post("/mcp", headers=headers, json={ + "jsonrpc": "2.0", "method": "notifications/initialized", + }) + assert response.status_code == 202 + meta = {} + else: + headers["MCP-Protocol-Version"] = "2026-07-28" + meta = {"_meta": META} + listed = rpc("resources/list", meta, 2)["result"]["resources"] + assert (URI in {entry["uri"] for entry in listed}) is has_widgets + result = rpc("resources/read", {"uri": URI, **meta}, 3) + if has_widgets: + contents = result["result"]["contents"][0] + assert contents["mimeType"] == "application/json" + assert json.loads(contents["text"]) == app.widget_registry.get_manifest().to_dict() + else: + assert "error" in result + + +@pytest.mark.parametrize("template,routes", [ + ("starter", ["calculator-result"]), + ("pizzaz", ["pizza-list", "pizza-map", "pizza-shop"]), + ("flight-booking", ["airport-search", "flight-details", "flight-search-results", + "order-cancellation", "order-summary", "seat-selection"]), +]) +def test_real_template_bootstrap(template, routes): + env = {**os.environ, "PYTHONPATH": str(ROOT), "NITROSTACK_APP_MODE": "universal"} + result = subprocess.run( + [sys.executable, str(PROBE), template], cwd=ROOT, env=env, + capture_output=True, text=True, timeout=25, + ) + assert result.returncode == 0, result.stderr + manifest = json.loads(result.stdout) + assert [w["route"] for w in manifest["widgets"]] == routes + assert manifest["count"] == len(routes) and manifest["loaded"] is True + for entry in manifest["widgets"]: + assert entry["uri"] == f"ui://widget/{entry['route']}.html" + assert entry["mime_type"] == "text/html;profile=mcp-app" + if template == "flight-booking": + summary = next(w for w in manifest["widgets"] if w["route"] == "order-summary") + assert len(summary["tool_names"]) == 2 + if template == "pizzaz": + for entry in manifest["widgets"]: + assert entry["metadata"]["ui"]["prefersBorder"] is True + assert "https://api.mapbox.com" in entry["metadata"]["ui"]["csp"]["connectDomains"] + assert entry["examples"] + + +def test_real_stdio_manifest_has_only_protocol_output(): + env = {**os.environ, "PYTHONPATH": str(ROOT), "NITRO_MCP_PROTOCOL_VERSION": "auto"} + process = subprocess.Popen( + [sys.executable, str(PROBE), "stdio"], cwd=ROOT, env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding="utf-8", + ) + with ThreadPoolExecutor(max_workers=1) as reader: + try: + def rpc(method, params, request_id): + process.stdin.write(json.dumps({ + "jsonrpc": "2.0", "id": request_id, "method": method, + "params": {**params, "_meta": META}, + }) + "\n") + process.stdin.flush() + line = reader.submit(process.stdout.readline).result(timeout=10) + payload = json.loads(line) + assert payload["id"] == request_id + return payload["result"] + + listed = rpc("resources/list", {}, 1) + assert URI in {entry["uri"] for entry in listed["resources"]} + contents = rpc("resources/read", {"uri": URI}, 2)["contents"][0] + assert contents["mimeType"] == "application/json" + manifest = json.loads(contents["text"]) + assert manifest["count"] == 1 + assert manifest["widgets"][0]["route"] == "stdio-example" + process.stdin.close() + process.wait(timeout=10) + assert process.returncode == 0, process.stderr.read() + assert process.stdout.read() == "" + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) diff --git a/tests/test_widgets.py b/tests/test_widgets.py index 2625533..efad2b9 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -130,13 +130,13 @@ class WidgetTestModule: return WidgetTestModule, html_path if with_html_file else None -async def _harness(module_cls, *, chdir_to_fixtures: bool = False): +async def _harness(module_cls, *, chdir_to_fixtures: bool = False, protocol_era: str = "auto"): if chdir_to_fixtures: os.chdir(FIXTURES.parent.parent.parent) # tests/fixtures @mcp_app(module=module_cls, server=ServerConfig(name="widget-test")) class _App: pass - return await NitroTestingModule.create(module_cls) + return await NitroTestingModule.create(module_cls, protocol_era=protocol_era) # --------------------------------------------------------------------------- @@ -151,7 +151,7 @@ def test_widget_mime_type_by_mode(): with app_mode("universal"): assert get_widget_mime_type() == RESOURCE_MIME_TYPE_MCP_APP with app_mode(None): - assert get_widget_mime_type() == RESOURCE_MIME_TYPE_MCP_APP + assert get_widget_mime_type() == RESOURCE_MIME_TYPE_OPENAI assert OPENAI_SKYBRIDGE_MIME_TYPE == "text/html+skybridge" assert get_widget_mime_type() != OPENAI_SKYBRIDGE_MIME_TYPE @@ -481,7 +481,7 @@ async def run(): prev = os.getcwd() try: os.chdir(FIXTURES.parent.parent) - harness = await _harness(mod) + harness = await _harness(mod, protocol_era="legacy") finally: os.chdir(prev) diff --git a/uv.lock b/uv.lock index b4eb511..a0154ab 100644 --- a/uv.lock +++ b/uv.lock @@ -1,10 +1,10 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", - "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", + "python_full_version == '3.11.*' or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", "python_full_version < '3.11'", ] @@ -40,6 +40,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] +[[package]] +name = "backoff" +version = "2.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/47/d7/5bbeb12c44d7c4f2fb5b56abce497eb5ed9f34d85701de869acedd602619/backoff-2.2.1.tar.gz", hash = "sha256:03f829f5bb1923180821643f8753b0502c3b682293992485b0eef2807afa5cba", size = 17001, upload-time = "2022-10-05T19:19:32.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" }, +] + +[[package]] +name = "backports-asyncio-runner" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8e/ff/70dca7d7cb1cbc0edb2c6cc0c38b65cba36cccc491eca64cabd5fe7f8670/backports_asyncio_runner-1.2.0.tar.gz", hash = "sha256:a5aa7b2b7d8f8bfcaa2b57313f70792df84e32a2a746f585213373f900b42162", size = 69893, upload-time = "2025-07-02T02:27:15.685Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/59/76ab57e3fe74484f48a53f8e337171b4a2349e506eabe136d7e01d059086/backports_asyncio_runner-1.2.0-py3-none-any.whl", hash = "sha256:0da0a936a8aeb554eccb426dc55af3ba63bcdc69fa1a600b5bb305413a4477b5", size = 12313, upload-time = "2025-07-02T02:27:14.263Z" }, +] + [[package]] name = "cachetools" version = "7.1.8" @@ -51,11 +69,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.7.22" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -168,6 +186,169 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, ] +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/77/46e87bcfc45d25ab4db7cfc9bb544bfa3ffd302289ed31ae93f5433eb899/charset_normalizer-3.5.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3", size = 373348, upload-time = "2026-09-30T04:34:42.843Z" }, + { url = "https://files.pythonhosted.org/packages/52/fc/e518013affcc43c9f919c3ba41bffe9b4ee4aceb0a6462a6243efcca5f2d/charset_normalizer-3.5.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e", size = 260860, upload-time = "2026-09-30T04:34:44.817Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ad/2a895c945ee61988dfd9ccee64f0b78dc09f29c9b34d1dd545246d78e0ad/charset_normalizer-3.5.2-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5", size = 246491, upload-time = "2026-09-30T04:34:46.227Z" }, + { url = "https://files.pythonhosted.org/packages/c9/05/5d958bc8ea503e26be25ada5430fd409cfb45dc22ff33f9f96e649613c99/charset_normalizer-3.5.2-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa", size = 290875, upload-time = "2026-09-30T04:34:47.691Z" }, + { url = "https://files.pythonhosted.org/packages/55/e2/06bad57dfdb49cad92c0ba85b6b4fa5827a67df37897287cfef0553843c2/charset_normalizer-3.5.2-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320", size = 286987, upload-time = "2026-09-30T04:34:49.356Z" }, + { url = "https://files.pythonhosted.org/packages/c4/9f/9f52d2886d52645987d603425482c63c5045a3005db1354a7097e5ed1ae9/charset_normalizer-3.5.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249", size = 271105, upload-time = "2026-09-30T04:34:50.957Z" }, + { url = "https://files.pythonhosted.org/packages/4a/41/e05e19578b7b87e7db2c3ecb884bd09d065274ab41e1f535542e8bae9b06/charset_normalizer-3.5.2-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e", size = 269833, upload-time = "2026-09-30T04:34:52.623Z" }, + { url = "https://files.pythonhosted.org/packages/c2/cd/fc7152414561ff78f9c61a4a627025f65fd244abaefc99ac4e75c6169b33/charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9", size = 263048, upload-time = "2026-09-30T04:34:54.013Z" }, + { url = "https://files.pythonhosted.org/packages/71/71/fb379e399b1013962716a059d551e03bd80b3e02f05d81246886af6c0958/charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5", size = 249237, upload-time = "2026-09-30T04:34:55.373Z" }, + { url = "https://files.pythonhosted.org/packages/33/4f/aeadccd6d20882909eb2597ec40eccc05d505e2262f14dc76d7620700657/charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c", size = 290756, upload-time = "2026-09-30T04:34:56.867Z" }, + { url = "https://files.pythonhosted.org/packages/b9/7b/e8a92613236b257d3b75d532496eb21f68ad8231d7d56df94497e460112e/charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c", size = 269026, upload-time = "2026-09-30T04:34:58.278Z" }, + { url = "https://files.pythonhosted.org/packages/ff/ac/21d5c6b972285c5f095ff78afdc99f3539e3985dfcf7ff1cfbe9e772f529/charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be", size = 287601, upload-time = "2026-09-30T04:34:59.703Z" }, + { url = "https://files.pythonhosted.org/packages/59/72/263491ec1494a194b16fcbff88a0220f2af633738c79e92b4d7189226322/charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45", size = 272660, upload-time = "2026-09-30T04:35:01.26Z" }, + { url = "https://files.pythonhosted.org/packages/38/7a/81f1186c57e406233969ae96b5fd0c907254ab8b6e47da8ae24cd20fb9d7/charset_normalizer-3.5.2-cp310-cp310-win32.whl", hash = "sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4", size = 187301, upload-time = "2026-09-30T04:35:02.659Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ab/fb8b5178fdf7bf68efa61cbe892286bc9f73846f26147d4725fb89388475/charset_normalizer-3.5.2-cp310-cp310-win_amd64.whl", hash = "sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275", size = 215446, upload-time = "2026-09-30T04:35:04.011Z" }, + { url = "https://files.pythonhosted.org/packages/36/40/e270b74e0d3f583d78d902960845a149e80eb7c737ee5613ccc6efc7264b/charset_normalizer-3.5.2-cp310-cp310-win_arm64.whl", hash = "sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c", size = 203389, upload-time = "2026-09-30T04:35:05.577Z" }, + { url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" }, + { url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" }, + { url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" }, + { url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" }, + { url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" }, + { url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" }, + { url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" }, + { url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" }, + { url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" }, + { url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" }, + { url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" }, + { url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" }, + { url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" }, + { url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c8/693809898870237d82785a03f3b2b58fe4c9f14669f84a7d4e623c92a59e/charset_normalizer-3.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491", size = 367780, upload-time = "2026-09-30T04:35:30.888Z" }, + { url = "https://files.pythonhosted.org/packages/c9/87/2fea8c13dc24b3ca9c6f803a5b2dfdeae73eb4f9e12c7885ed908ff0433c/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c", size = 246730, upload-time = "2026-09-30T04:35:32.286Z" }, + { url = "https://files.pythonhosted.org/packages/a8/9e/09efac30b937722f46d3110ba30b875b24b2e3a266ed746cc4e376a94d80/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0", size = 237707, upload-time = "2026-09-30T04:35:33.709Z" }, + { url = "https://files.pythonhosted.org/packages/9e/18/70d76670b13686237863a379928d60bd10e021f17d243ab3d7014c4a5f4e/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51", size = 273050, upload-time = "2026-09-30T04:35:35.138Z" }, + { url = "https://files.pythonhosted.org/packages/54/e2/77a8b09d5adc013ed07b95b01b8b8fa5441c4e810e83ee7e4aae2fa4d91a/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5", size = 270345, upload-time = "2026-09-30T04:35:36.502Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c5/38806a25ab5e65fc178f39affeda20858efafede2fce1ffc2556cfc9fe73/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649", size = 257601, upload-time = "2026-09-30T04:35:37.919Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8d/213565184708fdb263ae55e2c04ee1ff748129dd65d48ed0e3502da9c85a/charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e", size = 252222, upload-time = "2026-09-30T04:35:39.544Z" }, + { url = "https://files.pythonhosted.org/packages/7e/24/76d2cefc25472531e4c5c7dfff68865eb1c39b78482f0fdc15b46f047830/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346", size = 248482, upload-time = "2026-09-30T04:35:41.088Z" }, + { url = "https://files.pythonhosted.org/packages/7d/dc/65a801b66ab4c197e22c433ab25e7ac24324ac6f45a2269aca42cce309bf/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1", size = 241206, upload-time = "2026-09-30T04:35:42.59Z" }, + { url = "https://files.pythonhosted.org/packages/a7/95/ca9b5eabde673002c6f1e7ada1b223916fe18f6d661da7aabd4d643718f1/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875", size = 273190, upload-time = "2026-09-30T04:35:44.347Z" }, + { url = "https://files.pythonhosted.org/packages/2d/8b/803b4d2a3f6e1740f63f1e87b04d14b42f3d4fdfe6ed7d4db2d34102b14f/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1", size = 253527, upload-time = "2026-09-30T04:35:45.915Z" }, + { url = "https://files.pythonhosted.org/packages/a9/55/93c0e5dbd085ae0471346026abbe7e0db9ea2d6fea74e51f0b5a46f233a7/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413", size = 271285, upload-time = "2026-09-30T04:35:47.49Z" }, + { url = "https://files.pythonhosted.org/packages/95/69/0dbd0e0b9b16cfa816cdfcb3e2e3854a1f680dc07fb1245ea125e7448060/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869", size = 260010, upload-time = "2026-09-30T04:35:48.996Z" }, + { url = "https://files.pythonhosted.org/packages/58/9d/e7b88e7b1bf403590c3b573277b5e1e488c68c7a6fbacca310a2c324e90c/charset_normalizer-3.5.2-cp312-cp312-win32.whl", hash = "sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e", size = 184125, upload-time = "2026-09-30T04:35:50.777Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e6/e6e083884cbcfd49c64865af05027fe7011be7b2d9179524f099a1b611f3/charset_normalizer-3.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc", size = 207486, upload-time = "2026-09-30T04:35:52.194Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e3/017aea0911ada7405a825c7d937eb3a13009664e2f5b38e8c4bbf2abf894/charset_normalizer-3.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3", size = 196734, upload-time = "2026-09-30T04:35:53.636Z" }, + { url = "https://files.pythonhosted.org/packages/c5/34/68292d68512768591aaff07c59bb53ee31341c87759433a859c4641a50c2/charset_normalizer-3.5.2-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5", size = 225946, upload-time = "2026-09-30T04:35:55.313Z" }, + { url = "https://files.pythonhosted.org/packages/e3/80/bee0b01b90ccd5322ae1d0abb33fab1bd95b7c2eadaf02aeccf22e04ee83/charset_normalizer-3.5.2-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e", size = 238619, upload-time = "2026-09-30T04:35:56.863Z" }, + { url = "https://files.pythonhosted.org/packages/78/6e/60ce52a85a7fd631ae8482ae6d74521014ca2f255892679484dc04d7ef56/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a", size = 206701, upload-time = "2026-09-30T04:35:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/36/8c/71aafad23f971afc84c2b295bc0c560739ce1dac558aad9fec22e39f3639/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d", size = 210506, upload-time = "2026-09-30T04:36:00.147Z" }, + { url = "https://files.pythonhosted.org/packages/91/da/3c5a7798c046df7d2d68ad653cf5b6c5a8bfee225055a843c6f2f42aac1a/charset_normalizer-3.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055", size = 366626, upload-time = "2026-09-30T04:36:01.77Z" }, + { url = "https://files.pythonhosted.org/packages/e1/16/710ac3de2ee354e2bd1a9c94efe45a2d27b5c6ad39b2d6a905be2c094b6c/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858", size = 244624, upload-time = "2026-09-30T04:36:03.389Z" }, + { url = "https://files.pythonhosted.org/packages/d6/39/45c7439f5b63d24f7d5b2a1d760f34af7628782d7144b4cc8ded45c2d4bc/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234", size = 235731, upload-time = "2026-09-30T04:36:04.987Z" }, + { url = "https://files.pythonhosted.org/packages/4d/34/38f3154785ce92e9f56eb226f4d35bdfae6b008480dd055f58837a89c810/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21", size = 270352, upload-time = "2026-09-30T04:36:06.412Z" }, + { url = "https://files.pythonhosted.org/packages/04/f3/859f74e7babc977705026b30593b3be04049632a522fb7000f83c033d747/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718", size = 267393, upload-time = "2026-09-30T04:36:07.865Z" }, + { url = "https://files.pythonhosted.org/packages/4b/85/41d27f234b82e47c167a5f6c0f62501dc0c640585ff4aba79e08a390336a/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4", size = 254660, upload-time = "2026-09-30T04:36:09.248Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/5d1a997587febe5b26d8daffe363b5c1a091cece19828eec6502fd09c5ef/charset_normalizer-3.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3", size = 249996, upload-time = "2026-09-30T04:36:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/b3/1f/d1e78246f7ed60c8c8d606b4ac27f66ce49cc3e95f24893ccbeba9f77302/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c", size = 247028, upload-time = "2026-09-30T04:36:12.294Z" }, + { url = "https://files.pythonhosted.org/packages/8e/37/eba316edd4f0c4d3a5d945924c4eeeae59abac4056aa815d8a4268f863a2/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429", size = 240562, upload-time = "2026-09-30T04:36:13.887Z" }, + { url = "https://files.pythonhosted.org/packages/c8/8e/aaa037d40ca9ef045977f1a661048b1aa33f223adfce3452fe9be9f79d14/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f", size = 271699, upload-time = "2026-09-30T04:36:15.41Z" }, + { url = "https://files.pythonhosted.org/packages/26/19/1c1c9f75974adf523b87f34b8a2adc5a435cd65916812bcbd0dfa45f9a29/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a", size = 252030, upload-time = "2026-09-30T04:36:16.839Z" }, + { url = "https://files.pythonhosted.org/packages/bc/90/0660ef18e18df0a4d2a1a0edff7dfbba42d4e50ef2425557a5bb7051f77b/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00", size = 268565, upload-time = "2026-09-30T04:36:18.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/ba/57adc269824e8658f1a0f97a9e514c247445a9632b3419b97e0ba37f16dc/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d", size = 257627, upload-time = "2026-09-30T04:36:19.938Z" }, + { url = "https://files.pythonhosted.org/packages/9a/85/33abd4315c052d3d4f54c92b1ee49bfbc0dc7115a981e462a793b6d2ab87/charset_normalizer-3.5.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3", size = 143407, upload-time = "2026-09-30T04:36:21.376Z" }, + { url = "https://files.pythonhosted.org/packages/4f/de/6435e18d1aaa5d910b896d551411c96af1f42a0c56c29afc2016c61ccc2e/charset_normalizer-3.5.2-cp313-cp313-win32.whl", hash = "sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd", size = 183207, upload-time = "2026-09-30T04:36:22.776Z" }, + { url = "https://files.pythonhosted.org/packages/9c/76/b8ec57f4e9ee3253541abf95e4a462c0175fe8032dcd070f1f2421240942/charset_normalizer-3.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639", size = 206489, upload-time = "2026-09-30T04:36:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/3e/60/c647c6ae47480221e875ea5d743ff94946f7416e3c69415ab772928e8d32/charset_normalizer-3.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3", size = 195501, upload-time = "2026-09-30T04:36:25.846Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/7aa91362a2f77ac8e9e28a9b902a74f7d0e11a851ef0d27a74308da8cd90/charset_normalizer-3.5.2-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187", size = 226010, upload-time = "2026-09-30T04:36:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/a8/cf/ac8878d0322cf88a1aad4c7b147db32ca0bd806eb0060957b2e31486dbe6/charset_normalizer-3.5.2-cp314-cp314-android_24_x86_64.whl", hash = "sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad", size = 239266, upload-time = "2026-09-30T04:36:29.434Z" }, + { url = "https://files.pythonhosted.org/packages/c9/6d/9a08d7e0b29b7208e2c6c01dc56c8e0520e7c7beadbbfb024b58fd69c8a5/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf", size = 206783, upload-time = "2026-09-30T04:36:30.872Z" }, + { url = "https://files.pythonhosted.org/packages/82/44/b0aa350280e6ff5a5492d17cf10460dd39d5ee848f872f7ba2df10607f60/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995", size = 210449, upload-time = "2026-09-30T04:36:32.625Z" }, + { url = "https://files.pythonhosted.org/packages/7c/8a/40db9aa9f5907bb0e6f8b6d64064bf8852fb33d4b813ff9414911df7647c/charset_normalizer-3.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424", size = 367815, upload-time = "2026-09-30T04:36:34.197Z" }, + { url = "https://files.pythonhosted.org/packages/7f/72/9c5e7707b57c8ddfa9ddf7b0b1d009d7fbab9e9e887d5b721060f37e307d/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13", size = 247095, upload-time = "2026-09-30T04:36:35.803Z" }, + { url = "https://files.pythonhosted.org/packages/83/09/71e453691e927de4ddf792770cfaab3f49d494e222f66ea5e404bbd5e39c/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d", size = 233942, upload-time = "2026-09-30T04:36:37.407Z" }, + { url = "https://files.pythonhosted.org/packages/9f/86/85c84e4da8b27dd409577d9437926ff581c5f9d3c66038dc68c1a526de51/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4", size = 273762, upload-time = "2026-09-30T04:36:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/92/08/564955a4b5f2ccb410ab480bbe8c6a18063ff27f2d35458731c4a5335df9/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438", size = 269514, upload-time = "2026-09-30T04:36:40.469Z" }, + { url = "https://files.pythonhosted.org/packages/18/24/bad3ac4271589df29cf5ce2f5ae490518a5739358052bd0d61209e6fea54/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a", size = 255056, upload-time = "2026-09-30T04:36:42.02Z" }, + { url = "https://files.pythonhosted.org/packages/d6/3e/350d89ad49916b86554d6f5f2d03ec1152148f87e5ff735106c6a03b1a36/charset_normalizer-3.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56", size = 251311, upload-time = "2026-09-30T04:36:43.577Z" }, + { url = "https://files.pythonhosted.org/packages/56/5b/4970a2d154df502e133402906dd04e3ae7cada7b3011283c88d0479a2585/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd", size = 250190, upload-time = "2026-09-30T04:36:45.185Z" }, + { url = "https://files.pythonhosted.org/packages/88/8c/f1a91bddc8fb47c2889e29ea7ea49a194eb0d9868675d786806519c00d76/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204", size = 237098, upload-time = "2026-09-30T04:36:46.689Z" }, + { url = "https://files.pythonhosted.org/packages/24/0e/bb5dace3cc7e79068425386a6589c19b5a2ab5fefc2a46abea6919683332/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7", size = 274228, upload-time = "2026-09-30T04:36:48.31Z" }, + { url = "https://files.pythonhosted.org/packages/9d/79/b849ad523017ea9f5a45581bbebed91439e0cf42fd2860a6f64e358eb5a6/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd", size = 252401, upload-time = "2026-09-30T04:36:50.091Z" }, + { url = "https://files.pythonhosted.org/packages/89/8c/75469d690cf47200bce8f6cad7655724fc23148e147abfc5ce78b5f65863/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc", size = 271846, upload-time = "2026-09-30T04:36:51.719Z" }, + { url = "https://files.pythonhosted.org/packages/26/cd/6d52d3c7437cdcf2e310ce9f28f282e733d4ef60ed19105d1819c356255f/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874", size = 258151, upload-time = "2026-09-30T04:36:53.234Z" }, + { url = "https://files.pythonhosted.org/packages/f7/4c/070b38bdb5f49a70199fce923ec0726a49536a63ab262abbfcaaf351110b/charset_normalizer-3.5.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655", size = 143570, upload-time = "2026-09-30T04:36:54.816Z" }, + { url = "https://files.pythonhosted.org/packages/81/84/9ebfc8ed6c8c4fcd8e726ff6bf220cc8deb3966e31dce9be8dd8aa017e64/charset_normalizer-3.5.2-cp314-cp314-win32.whl", hash = "sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0", size = 186412, upload-time = "2026-09-30T04:36:56.643Z" }, + { url = "https://files.pythonhosted.org/packages/d1/78/5ed86f743d4bc350db307e7636419a0a5ee1d91806d30c7f667bd5c80dae/charset_normalizer-3.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c", size = 210965, upload-time = "2026-09-30T04:36:58.205Z" }, + { url = "https://files.pythonhosted.org/packages/53/94/a3a7698e9b1a395e1eb99ccd9a324be9347973bff4e72db2a06496d7cd27/charset_normalizer-3.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253", size = 200406, upload-time = "2026-09-30T04:36:59.764Z" }, + { url = "https://files.pythonhosted.org/packages/c1/48/c5dd00d5ef7791f02666de250a5bb6071e29b7e133cf4b835800b6d3bc27/charset_normalizer-3.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709", size = 396871, upload-time = "2026-09-30T04:37:01.543Z" }, + { url = "https://files.pythonhosted.org/packages/12/c8/8379554b42e8368161d898476686947a0fdbd3e8865170d7909dcabfdee8/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084", size = 249711, upload-time = "2026-09-30T04:37:03.111Z" }, + { url = "https://files.pythonhosted.org/packages/4a/eb/2ddb1035d17320caa9f41682935123a9a250277b261c3efc86b2d2a21343/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb", size = 231146, upload-time = "2026-09-30T04:37:04.721Z" }, + { url = "https://files.pythonhosted.org/packages/4a/24/2ecb4bde104322cd7859d6594fcfa74649f8d90b3221c9feecbef149875b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f", size = 271552, upload-time = "2026-09-30T04:37:06.295Z" }, + { url = "https://files.pythonhosted.org/packages/3f/98/9d5f6ebc3aee9fef5d30b4aff11fb2ab7a1222b4064f8ef2c7c87cde217a/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09", size = 269810, upload-time = "2026-09-30T04:37:07.905Z" }, + { url = "https://files.pythonhosted.org/packages/09/e1/a3b06a10461b1b7628853c934c644e03bc28e42767116afb52f19a56519b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80", size = 259845, upload-time = "2026-09-30T04:37:09.554Z" }, + { url = "https://files.pythonhosted.org/packages/fd/d3/6f561f74a296cf27d61775a1dc665ad13f3bff6a798810ca05907f37a7c4/charset_normalizer-3.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c", size = 252825, upload-time = "2026-09-30T04:37:11.274Z" }, + { url = "https://files.pythonhosted.org/packages/26/9f/69e13ca3b18f43e0eafcd34c04a45b732ae22a43b54a5fc9e119103356eb/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f", size = 252659, upload-time = "2026-09-30T04:37:12.941Z" }, + { url = "https://files.pythonhosted.org/packages/73/a9/ace29806a0dae18939919c76ba526472d83214afa101105fabff2cf30625/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03", size = 238819, upload-time = "2026-09-30T04:37:14.659Z" }, + { url = "https://files.pythonhosted.org/packages/f8/c1/6116d52a2e3311ec80f21f5fb5e17b27405f10b9608af8f6e69516841a1b/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604", size = 272973, upload-time = "2026-09-30T04:37:16.346Z" }, + { url = "https://files.pythonhosted.org/packages/19/aa/9955c7e93bba10a9c7e8f7a5031b7ced66f3a1883a55c00712b8d5850ff3/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8", size = 253692, upload-time = "2026-09-30T04:37:18.212Z" }, + { url = "https://files.pythonhosted.org/packages/bb/33/2a6ae7fdc1b10cb581cef91addd8cdfc5f40d50abb5702309369d5834579/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93", size = 268757, upload-time = "2026-09-30T04:37:19.877Z" }, + { url = "https://files.pythonhosted.org/packages/a2/22/80992720a0282cd39bba1db35868e6b9c22f41281160143a836544bc1d8a/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915", size = 262220, upload-time = "2026-09-30T04:37:21.583Z" }, + { url = "https://files.pythonhosted.org/packages/92/9f/181fd07e1bffea1d95cd80c84ac537354f50699c22cfc4d3c02b6fc16208/charset_normalizer-3.5.2-cp314-cp314t-win32.whl", hash = "sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5", size = 197797, upload-time = "2026-09-30T04:37:23.235Z" }, + { url = "https://files.pythonhosted.org/packages/49/1c/25d8415ec1c4f2f41f1680435e4c87cfb378ff2f677d950946f2a45d0632/charset_normalizer-3.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc", size = 222765, upload-time = "2026-09-30T04:37:24.891Z" }, + { url = "https://files.pythonhosted.org/packages/3e/b4/46b48f013dadfc0d0d33b375438e31bdf5a989dc68389c6bf627054d4df9/charset_normalizer-3.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105", size = 210985, upload-time = "2026-09-30T04:37:26.634Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e9/34e597dee616d0b8ee4b34d29399e85c2204ade174157a48505d42baa4ff/charset_normalizer-3.5.2-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26", size = 367676, upload-time = "2026-09-30T04:37:28.329Z" }, + { url = "https://files.pythonhosted.org/packages/60/9f/a5d1c91c0263745e2cd344c5a4415d787c575501ab1d449f1148ac6b495d/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364", size = 248414, upload-time = "2026-09-30T04:37:30.167Z" }, + { url = "https://files.pythonhosted.org/packages/26/79/e697f77464748a3ee3cf490c83d592459400d4898380d66c38366b03080c/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253", size = 244775, upload-time = "2026-09-30T04:37:31.964Z" }, + { url = "https://files.pythonhosted.org/packages/ca/87/3d42a42e18ea066e2513936fd678a00696e77878b5ae04528976abdbcb83/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0", size = 273877, upload-time = "2026-09-30T04:37:33.661Z" }, + { url = "https://files.pythonhosted.org/packages/c3/76/8a28136f3938ba9836f84280ce0c4d61ed1cf15a036b2034900c62634162/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc", size = 269455, upload-time = "2026-09-30T04:37:35.573Z" }, + { url = "https://files.pythonhosted.org/packages/a0/a1/4fbf5d0f0f1b2a080474c1cf9a2f12c4c6531bb0e8ba591055e846d2b4e9/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229", size = 257336, upload-time = "2026-09-30T04:37:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/ba/a2/8b50aa320adb880ad579518e6f718f24944804b42a88b83d267d5d444125/charset_normalizer-3.5.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5", size = 257584, upload-time = "2026-09-30T04:37:39.522Z" }, + { url = "https://files.pythonhosted.org/packages/a5/57/50e3fed84e175f40349bd0da7a4fce94c87f0378f52d74f511d89e0bdc20/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98", size = 251854, upload-time = "2026-09-30T04:37:41.23Z" }, + { url = "https://files.pythonhosted.org/packages/d6/54/f7fbb3493c9f49091213b9c2d6dd65800696f1ce1a3f196a4205f50417b1/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3", size = 248767, upload-time = "2026-09-30T04:37:42.883Z" }, + { url = "https://files.pythonhosted.org/packages/d9/37/b3a6385acc5a1e45b39ae9c90bfb9cf838a09b9dd37ef2740ab4c6b4a2eb/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2", size = 274479, upload-time = "2026-09-30T04:37:44.658Z" }, + { url = "https://files.pythonhosted.org/packages/89/44/809913e2cfd279e635a9294fdbbfb1b1dc62a8189d473d561f649fce98d8/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf", size = 258310, upload-time = "2026-09-30T04:37:46.529Z" }, + { url = "https://files.pythonhosted.org/packages/af/a2/f28400ab13359d91bd39179df8e149376b9bf36588e739a3a4f9de2b84b2/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95", size = 271100, upload-time = "2026-09-30T04:37:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/e9/89/9bab37955edf0adb3b66f8a3a6617d9f2f487e0d56f295a6a286cb640aa6/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d", size = 259936, upload-time = "2026-09-30T04:37:50.023Z" }, + { url = "https://files.pythonhosted.org/packages/23/b5/4459e08d45a679f903d50fea08bc52cfa728cca4d7bd02c757b5e5abda2e/charset_normalizer-3.5.2-cp315-cp315-win32.whl", hash = "sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847", size = 186301, upload-time = "2026-09-30T04:37:51.722Z" }, + { url = "https://files.pythonhosted.org/packages/98/e8/55d5fd3935b4bce6da4fe0df61898e8c82653e317e677bd58aceb9c60f13/charset_normalizer-3.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8", size = 210858, upload-time = "2026-09-30T04:37:53.427Z" }, + { url = "https://files.pythonhosted.org/packages/a9/5b/974423c2fd8e524c7a7f64318c1e02240ef954912fa2b4d70344107b9c68/charset_normalizer-3.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a", size = 200309, upload-time = "2026-09-30T04:37:55.015Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f9/00ee0195db1013d8f7c416fd770fbeb560bb46eb2e36b054d05cb56f6cfa/charset_normalizer-3.5.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1", size = 395343, upload-time = "2026-09-30T04:37:56.743Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/c00b50e94c964cf934c7899cd47c97952fc11dad71cc5884b3c61795b09b/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b", size = 250114, upload-time = "2026-09-30T04:37:58.607Z" }, + { url = "https://files.pythonhosted.org/packages/50/27/d102dc880bbcffd0479ab64dfc1fb96777a854355a55e2bda72a71efadcb/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f", size = 239997, upload-time = "2026-09-30T04:38:00.511Z" }, + { url = "https://files.pythonhosted.org/packages/a5/4a/bf7ef45794dd293fab5f98a9309817977fbb845b9998f171b8cc5d8437a3/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3", size = 272313, upload-time = "2026-09-30T04:38:02.509Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ee/008a2837737991474c5754bb3191010007663860979701990982a502cbaf/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e", size = 269986, upload-time = "2026-09-30T04:38:04.435Z" }, + { url = "https://files.pythonhosted.org/packages/93/ad/bd74a283940dc910c5b14f8e4f80a248082bc9c0fcbe1f54530cb6d9cc5e/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9", size = 260202, upload-time = "2026-09-30T04:38:06.549Z" }, + { url = "https://files.pythonhosted.org/packages/8a/7b/ed341c66f69f688723501fac752be3d63c7159ca0d0d4174fc611e5710bb/charset_normalizer-3.5.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a", size = 259083, upload-time = "2026-09-30T04:38:08.311Z" }, + { url = "https://files.pythonhosted.org/packages/cc/9d/e41588b777965e5031a43128a1e96173ebb35ac75fc53ec3b517e7c21cd4/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115", size = 253081, upload-time = "2026-09-30T04:38:10.402Z" }, + { url = "https://files.pythonhosted.org/packages/81/35/b761eb6d8c1eb218b9b42b9b4d5ac902afdc399fb6dac6f9a9aac7bda589/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c", size = 248712, upload-time = "2026-09-30T04:38:12.317Z" }, + { url = "https://files.pythonhosted.org/packages/4d/2c/147169a041b747759f37405c0a97157e8e92de967968373101ff14915cba/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d", size = 274176, upload-time = "2026-09-30T04:38:14.138Z" }, + { url = "https://files.pythonhosted.org/packages/f0/2d/0ff8db0d373ba8538db686db11cd7e8912031490b9e4f383b41912e8d594/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d", size = 259413, upload-time = "2026-09-30T04:38:15.841Z" }, + { url = "https://files.pythonhosted.org/packages/8a/8e/b4a085fb47c9d3a7e43576a4784fdd8fe23f907514a972de8086edaf7a48/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4", size = 269434, upload-time = "2026-09-30T04:38:17.626Z" }, + { url = "https://files.pythonhosted.org/packages/83/1c/d8d8d7322a7c3eecdf3237a4a419cf41d2eaad8e006ce7dfdd9d4c8fa2eb/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b", size = 262716, upload-time = "2026-09-30T04:38:19.214Z" }, + { url = "https://files.pythonhosted.org/packages/a0/16/0e4c6ba9b44e97a2da150e52d331e8f9c968b21b358fbffa6c856cebcd89/charset_normalizer-3.5.2-cp315-cp315t-win32.whl", hash = "sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800", size = 197159, upload-time = "2026-09-30T04:38:21.037Z" }, + { url = "https://files.pythonhosted.org/packages/be/33/e90bc2b1374f7f36ef106f56620de5a783907e19ca857efe2277e31cac3e/charset_normalizer-3.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21", size = 221322, upload-time = "2026-09-30T04:38:22.886Z" }, + { url = "https://files.pythonhosted.org/packages/66/89/dfa6dcb08c200b7830ab56439e8c1890f2971d51aafbb3937894a2e7fcfc/charset_normalizer-3.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58", size = 209192, upload-time = "2026-09-30T04:38:24.648Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + [[package]] name = "click" version = "8.5.0" @@ -385,12 +566,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/02/08/9c41fb51ab5b43eb21674aff13df270e8ba6c4b29c8624e328dc7a9482af/distlib-0.4.3-py2.py3-none-any.whl", hash = "sha256:4b0ce306c966eb73bc3a7b6abad017c556dadd92c44701562cd528ac7fde4d5b", size = 470628, upload-time = "2026-06-12T08:04:50.506Z" }, ] +[[package]] +name = "distro" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722, upload-time = "2023-12-24T09:54:32.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, +] + [[package]] name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -433,8 +623,8 @@ name = "httpcore2" version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, - { name = "truststore", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, + { name = "h11" }, + { name = "truststore" }, ] sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" } wheels = [ @@ -568,12 +758,14 @@ wheels = [ [[package]] name = "nitrostack" -version = "0.4.2" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "anyio" }, + { name = "certifi" }, { name = "mcp" }, { name = "packaging" }, + { name = "posthog" }, { name = "pydantic" }, { name = "starlette" }, { name = "tomli", marker = "python_full_version < '3.11'" }, @@ -582,29 +774,49 @@ dependencies = [ ] [package.optional-dependencies] +code-mode = [ + { name = "quickjs" }, +] dev = [ + { name = "cryptography" }, { name = "httpx" }, { name = "pytest" }, + { name = "pytest-asyncio" }, { name = "pytest-cov" }, + { name = "pytest-timeout" }, + { name = "quickjs" }, + { name = "setuptools" }, { name = "tox" }, ] +token-encryption = [ + { name = "cryptography" }, +] [package.metadata] requires-dist = [ { name = "anyio", specifier = ">=4.0.0" }, + { name = "certifi", specifier = ">=2026.10.19" }, + { name = "cryptography", marker = "extra == 'dev'", specifier = ">=41" }, + { name = "cryptography", marker = "extra == 'token-encryption'", specifier = ">=41" }, { name = "httpx", marker = "extra == 'dev'", specifier = ">=0.27.0" }, { name = "mcp", specifier = ">=2,<3" }, { name = "packaging", specifier = ">=23.0.0" }, + { name = "posthog", specifier = ">=3,<5" }, { name = "pydantic", specifier = ">=2.0.0" }, - { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.4.0" }, + { name = "pytest", marker = "extra == 'dev'", specifier = ">=8" }, + { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.23" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.1.0" }, + { name = "pytest-timeout", marker = "extra == 'dev'", specifier = ">=2.3.0" }, + { name = "quickjs", marker = "extra == 'code-mode'", specifier = ">=1.19.4" }, + { name = "quickjs", marker = "extra == 'dev'", specifier = ">=1.19.4" }, + { name = "setuptools", marker = "extra == 'dev'", specifier = ">=70.1" }, { name = "starlette", specifier = ">=0.30.0" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.0" }, { name = "tox", marker = "extra == 'dev'", specifier = ">=4.0.0" }, { name = "uvicorn", specifier = ">=0.20.0" }, { name = "watchfiles", specifier = ">=0.18.0" }, ] -provides-extras = ["dev"] +provides-extras = ["token-encryption", "code-mode", "dev"] [[package]] name = "opentelemetry-api" @@ -645,6 +857,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] +[[package]] +name = "posthog" +version = "4.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "backoff" }, + { name = "distro" }, + { name = "python-dateutil", version = "3.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "python-dateutil", version = "4.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "requests" }, + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d1/3d/7fed38dfcc178c198b2c903dfda7011f35eea52455fd5333216d32db3be0/posthog-4.10.0.tar.gz", hash = "sha256:513bfbb21344013294abc046b1142173189c5422a3906cf2280d1389b0c2e28b", size = 85178, upload-time = "2025-06-13T19:36:26.24Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/85/c7/d8820c1040118919d0776d8c66ca091b503a574234571a69ff151e7c4072/posthog-4.10.0-py3-none-any.whl", hash = "sha256:b693d3d8209d000d8c5f4d6ea19096bfdfb83047fa8a14c937ae50a3394809a1", size = 102475, upload-time = "2025-06-13T19:36:24.839Z" }, +] + [[package]] name = "pycparser" version = "3.0" @@ -842,6 +1071,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] +[[package]] +name = "pytest-asyncio" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "backports-asyncio-runner", marker = "python_full_version < '3.11'" }, + { name = "pytest" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, +] + [[package]] name = "pytest-cov" version = "7.1.0" @@ -856,6 +1099,51 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, ] +[[package]] +name = "pytest-timeout" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/82/4c9ecabab13363e72d880f2fb504c5f750433b2b6f16e99f4ec21ada284c/pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a", size = 17973, upload-time = "2025-05-05T19:44:34.99Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/b6/3127540ecdf1464a00e5a01ee60a1b09175f6913f0644ac748494d9c4b21/pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2", size = 14382, upload-time = "2025-05-05T19:44:33.502Z" }, +] + +[[package]] +name = "python-dateutil" +version = "3.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "six" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0e/df/f15f80383f152452d8985b36d95cb8751f901a3e0ff4cd27f7e118f168e2/python_dateutil-3.0.0.tar.gz", hash = "sha256:7ebcb3c29a92f3ceafe79a7a48a5c45677e9e004bbeec5742ac0bbb00560b7a2", size = 271066, upload-time = "2026-10-21T23:41:45.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/17/cebee01d1c0c1441174cf0456ddc91b280d79acb65340c05e41d77866ee8/python_dateutil-3.0.0-py2.py3-none-any.whl", hash = "sha256:3c79630202e4152c6add678446984236efe4f57e84d8e892aab0637bab82e9fd", size = 94659, upload-time = "2026-10-21T23:41:43.431Z" }, +] + +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", + "python_full_version == '3.11.*' or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", +] +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + [[package]] name = "python-discovery" version = "1.6.0" @@ -902,6 +1190,26 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" }, ] +[[package]] +name = "quickjs" +version = "1.19.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f1/a7/8fac2e213db8108d8108e9f1ee8d6c2abfcbe943238b0960585c26666862/quickjs-1.19.4.tar.gz", hash = "sha256:1205953abc24ff757f4a795304d5d61e4bf1e555c9ef6ec96a132d4b95535484", size = 456179, upload-time = "2023-11-19T10:06:39.445Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/1c/152eba405e315348f9028cd5be1c7206730a76474d1cdd911b5ad9c89d06/quickjs-1.19.4-cp310-cp310-macosx_11_0_x86_64.whl", hash = "sha256:19520c326e840ef4aa72298e49f60c8feffeaf33ac62fac74ed9130ed46e7cb6", size = 532527, upload-time = "2023-11-19T10:06:03.963Z" }, + { url = "https://files.pythonhosted.org/packages/6b/a5/2ea2a6fb7c5df83e4e6e02d713f31ed470d4c5c9ba45a0340fd04d217b67/quickjs-1.19.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:be7424b9af7853aaff930e3af2d1f2ebd83241cd2764abcea66247476a6d56d5", size = 2177974, upload-time = "2023-11-19T10:06:05.965Z" }, + { url = "https://files.pythonhosted.org/packages/21/6a/a04a823c60bdc6b5f4cd38c3579cbfb73df5f6aeaab7ec781f69d35fc25f/quickjs-1.19.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d579851d2a34be57b8adcc48e2b30d3f2e8b87a30898c90ebad440cefbda6f1", size = 2172385, upload-time = "2023-11-19T10:06:07.774Z" }, + { url = "https://files.pythonhosted.org/packages/76/0c/92377aba51d068fd0a739905f642e38bd41b05c768ad200fbde65160414e/quickjs-1.19.4-cp310-cp310-win_amd64.whl", hash = "sha256:4bf4a6596dbc49dfc79ab15ca38bf2c300fbde7e45f5f63ba836d841e79df3e9", size = 382324, upload-time = "2023-11-19T10:06:09.767Z" }, + { url = "https://files.pythonhosted.org/packages/65/f4/9edeafd79dd295d2f46c66b52c6b158263f5183e88ca6a29dd6a023c2184/quickjs-1.19.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2272597b5fbe468a11803a700b1fc345df65d1bdba27dcde929c7d905e67e1e8", size = 1004505, upload-time = "2023-11-19T10:06:11.175Z" }, + { url = "https://files.pythonhosted.org/packages/73/19/1cc58e237d935fd3b640f9d8ab4f21a43fcc5bf210ad3ca7c486aa9ca937/quickjs-1.19.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:845d0635f86b6168d819ef13d820dec07453e07b1ac735e0738d889c66762788", size = 2179366, upload-time = "2023-11-19T10:06:12.885Z" }, + { url = "https://files.pythonhosted.org/packages/bf/18/ef9346c67c26c8941523f2b840018319f0d5028dc34e267f5ea5279126f9/quickjs-1.19.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:93c32e0f55c9871beff92a020b852e9addc59480b596955a9d1d40f5cbde8c5a", size = 2173800, upload-time = "2023-11-19T10:06:14.411Z" }, + { url = "https://files.pythonhosted.org/packages/f3/2b/d365ae4066cd7d9b84c006080c73a66c49e2d54ec093c5813e1ba592e010/quickjs-1.19.4-cp311-cp311-win_amd64.whl", hash = "sha256:d730ccbf65040a246105cceaafff7da9c67fe7c4a0832489c0982c153161b83c", size = 382407, upload-time = "2023-11-19T10:06:15.816Z" }, + { url = "https://files.pythonhosted.org/packages/95/4f/df90bde103703cd052fd76ad7bddfcb9a4f908ab6c940ad05fdb3997e173/quickjs-1.19.4-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:1bc38a840144a54e90668fb1f99441148429ab1d1b1355ecafbbe656eaeff788", size = 1004472, upload-time = "2023-11-19T10:06:17.453Z" }, + { url = "https://files.pythonhosted.org/packages/26/59/1689a6f59f26d8f68c082dc6dfbbb38d9b7eaa3e243a775f8be2c876b561/quickjs-1.19.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:45d0e68570425d8322c48fb8989865df9b8c3e3ad3a01726151e0451d3c637eb", size = 2179639, upload-time = "2023-11-19T10:06:21.064Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cd/8fd683236b976487bbd4c99e24334b25fc0542367164f2348bca08572490/quickjs-1.19.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ac4b6d40b90553e9b135b35b3eaca264d10cdf92bfafce36ed9fb9acfdc5b420", size = 2173664, upload-time = "2023-11-19T10:06:22.931Z" }, + { url = "https://files.pythonhosted.org/packages/be/10/58064fe6beeb72c122f2ecb4729cf437055d89891d29cc2cd20ed88c1d66/quickjs-1.19.4-cp312-cp312-win_amd64.whl", hash = "sha256:3ebe018eaef1957a21264b98877c6217d7bfc4e28cbc5d87e75f879e1f45fc85", size = 382359, upload-time = "2023-11-19T10:06:25.343Z" }, +] + [[package]] name = "referencing" version = "0.37.0" @@ -917,6 +1225,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, ] +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + [[package]] name = "rpds-py" version = "0.30.0" @@ -1049,7 +1372,7 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", - "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", + "python_full_version == '3.11.*' or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } wheels = [ @@ -1170,6 +1493,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/85/48f0abdcef5cce4e034c7a5b0ceeceba0b01bf0d942824f4bb720afe2dec/rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:8e65860d238379ed982fd9ba690579b5e95af2f4840f99c772816dbe573cb826", size = 586486, upload-time = "2026-06-30T07:17:51.141Z" }, ] +[[package]] +name = "setuptools" +version = "84.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "sse-starlette" version = "3.4.11" @@ -1312,6 +1653,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, ] +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + [[package]] name = "uvicorn" version = "0.52.4"