diff --git a/.file_length_baseline.json b/.file_length_baseline.json index 813dcd1..09d5ef1 100644 --- a/.file_length_baseline.json +++ b/.file_length_baseline.json @@ -1,8 +1,6 @@ { "examples/flight_booking_server.py": 582, "nitrostack/auth/oauth.py": 516, - "nitrostack/cli/main.py": 2019, - "nitrostack/cli/pack.py": 507, "nitrostack/core/app.py": 2273, "nitrostack/transports/http.py": 797, "nitrostack/widgets/route_templates.py": 870, diff --git a/.github/workflows/bump-version.yml b/.github/workflows/bump-version.yml new file mode 100644 index 0000000..3f7ff55 --- /dev/null +++ b/.github/workflows/bump-version.yml @@ -0,0 +1,85 @@ +name: Bump version + +# After a non-release PR merges to main, open (or refresh) a release PR that +# bumps pyproject.toml + uv.lock ahead of PyPI. Merging that PR runs publish.yml. +on: + pull_request: + types: [closed] + branches: [main] + workflow_dispatch: + inputs: + bump: + description: Semver component to increment + type: choice + options: [patch, minor, major] + default: patch + +concurrency: + group: bump-version + cancel-in-progress: true + +jobs: + bump: + if: > + github.event_name == 'workflow_dispatch' || + (github.event.pull_request.merged == true && + !contains(github.event.pull_request.labels.*.name, 'release')) + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: ${{ github.event_name == 'workflow_dispatch' && 'main' || github.event.pull_request.merge_commit_sha }} + token: ${{ secrets.GITHUB_TOKEN }} + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Plan and write bump + id: bump + run: | + set -euo pipefail + KIND="${{ github.event_name == 'workflow_dispatch' && inputs.bump || 'patch' }}" + VERSION=$(python scripts/bump_version.py --bump "$KIND" --write | tail -n 1) + if [ -z "$VERSION" ]; then + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "skip=false" >> "$GITHUB_OUTPUT" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Open or update release PR + if: steps.bump.outputs.skip != 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ steps.bump.outputs.version }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + BRANCH="release/${VERSION}" + git checkout -B "$BRANCH" + git add pyproject.toml uv.lock + git diff --staged --quiet && { echo "No version files changed"; exit 1; } + git commit -m "chore(release): ${VERSION}" + git push --force-with-lease origin "HEAD:refs/heads/${BRANCH}" + gh label create release --description "Version bump / PyPI release" --color 0E8A16 --force || true + EXISTING=$(gh pr list --base main --head "$BRANCH" --json number --jq '.[0].number // empty') + if [ -n "$EXISTING" ]; then + echo "Updated PR #${EXISTING}" + exit 0 + fi + gh pr create --base main --head "$BRANCH" --title "chore(release): ${VERSION}" --label release --body "$(cat <> "$GITHUB_OUTPUT" + echo "publish=true" >> "$GITHUB_OUTPUT" + else + echo "publish=false" >> "$GITHUB_OUTPUT" + echo "pyproject version is already on PyPI; skipping upload" + fi + + publish: + needs: check + if: needs.check.outputs.publish == 'true' + runs-on: ubuntu-latest + environment: + name: pypi + url: https://pypi.org/project/nitrostack/ + permissions: + id-token: write + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: python -m pip install -U build && python -m build + - uses: pypa/gh-action-pypi-publish@release/v1 + - name: Tag release + env: + VERSION: ${{ needs.check.outputs.version }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + TAG="v${VERSION}" + if git rev-parse "$TAG" >/dev/null 2>&1; then + echo "Tag $TAG already exists" + exit 0 + fi + git tag -a "$TAG" -m "nitrostack ${VERSION}" + git push origin "$TAG" diff --git a/README.md b/README.md index 7031f56..17471dc 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # NitroStack Python SDK +NitroStack - Build, test, and deploy MCP servers in one place | Product Hunt + 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. --- @@ -128,15 +130,16 @@ Attach generated pipeline classes with `@use_guards`, `@use_pipes`, `@use_interc ```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`. The real `.env` file and other secrets are never packed. Temporary build directories are deleted afterwards. +`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 # latest nitrostack on PyPI (writes nitrostack>=latest) -nitrostack-py upgrade --version 0.3.2 # pin exactly this version (writes nitrostack==0.3.2) +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 @@ -155,7 +158,7 @@ nitrostack = { path = "/path/to/nitrostack-python-sdk", editable = true } then `uv lock` / `uv sync`. Without `uv`, install falls back to `.venv` + `pip`. -`upgrade` updates the `nitrostack` dependency spec in `pyproject.toml` in place (and `requirements.txt` when it already pins nitrostack). `--version X` writes `nitrostack==X`. Without `--version`, the latest PyPI release is written as `nitrostack>=latest`. A target older than the currently declared 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. +`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. --- @@ -247,7 +250,29 @@ if __name__ == "__main__": ### 2. Configure Environment Variables -The SDK reads standard settings from the environment or `.env` files: +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 | |---|---| @@ -324,6 +349,214 @@ OAuthModule.for_root(**setup_oauth_auth()) # reads RESOURCE_URI, AUTH_SERVER `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). + +### Tools + +```python +from pydantic import BaseModel, Field +from nitrostack import tool, initial_tool, ToolAnnotations, ToolExamples, ExecutionContext + +class LookupInput(BaseModel): + city: str = Field(description="City name") + +class Weather(BaseModel): + city: str + temp: float + units: str + +class NoInput(BaseModel): + pass + +class WeatherController: + @tool( + name="get_weather", + title="Get Weather", + description="Current weather for a city", + input_schema=LookupInput, + output_schema=Weather, # optional; adds structuredContent + annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True), + examples=ToolExamples(input={"city": "Paris"}, output={"city": "Paris", "temp": 21, "units": "metric"}), + ) + async def get_weather(self, input: LookupInput, context: ExecutionContext) -> dict: + return {"city": input.city, "temp": 21, "units": "metric"} + + @tool(name="whats_new", description="Shown when a client connects", input_schema=NoInput) + @initial_tool # clients that support it call this on connect + async def whats_new(self, input: NoInput, context: ExecutionContext) -> str: + return "Try get_weather." +``` + +A tool with no arguments still needs an input model; use an empty `BaseModel` subclass like `NoInput` (not `BaseModel` itself). `visibility="hidden"` keeps a tool callable but out of `tools/list`. Raise an exception to return an MCP error to the client. + +### Resources and prompts + +```python +from typing import List +from nitrostack import resource, prompt, PromptArgument, PromptMessage, ExecutionContext + +class WeatherController: + @resource(uri="weather://units", name="Units", description="Units in use", mime_type="text/plain") + async def units(self, context: ExecutionContext) -> str: + return "metric" + + @prompt( + name="forecast_brief", + description="Write a short forecast", + arguments=[PromptArgument(name="city", description="City", required=True)], + ) + async def forecast_brief(self, args: dict, context: ExecutionContext) -> List[PromptMessage]: + return [PromptMessage(role="user", content=f"Write a short forecast for {args['city']}.")] +``` + +### Guards, interceptors, pipes, middleware and filters + +Each is a small class with one async method; attach it with a decorator below `@tool`. Generate stubs with `nitrostack-py generate guard|pipe|interceptor|filter `. + +| Stage | Method | Attach with | Runs | +|---|---|---|---| +| Guard | `can_activate(context) -> bool` | `@use_guards(...)` | first; `False` rejects the call ("Access denied by guard") | +| Pipe | `transform(value, metadata)` | `@use_pipes(...)` | on the tool input, after guards | +| Middleware | `use(context, next_fn)` | `@use_middleware(...)` | around interceptors and the tool | +| Interceptor | `intercept(context, next_fn)` | `@use_interceptors(...)` | around the tool; can change its result | +| Exception filter | `catch(error, context)` | `@use_filters(...)` | on errors; its return value becomes the result | + +```python +from nitrostack import tool, use_guards, use_interceptors, use_filters, ExecutionContext + +class OfficeHoursGuard: + async def can_activate(self, context: ExecutionContext) -> bool: + return context.metadata.get("office_open", True) + +class TimingInterceptor: + async def intercept(self, context: ExecutionContext, next_fn): + result = await next_fn() + context.logger.info(f"{context.tool_name} finished") + return result + +class FriendlyErrors: + async def catch(self, error: Exception, context: ExecutionContext): + return {"error": str(error)} + +class WeatherController: + @tool(name="get_forecast", description="Forecast for a city", input_schema=LookupInput) + @use_guards(OfficeHoursGuard) + @use_interceptors(TimingInterceptor) + @use_filters(FriendlyErrors) + async def get_forecast(self, input: LookupInput, context: ExecutionContext) -> dict: + return {"city": input.city, "forecast": "sunny"} +``` + +### Authentication + +Register an auth module in the root module, then guard tools. Guards fill `context.auth` (`subject`, `scopes`, `client_id`, `claims`, ...). + +| Module | Guard | Configured by | +|---|---|---| +| `ApiKeyModule.for_root(keys_env_prefix="API_KEY", hashed=False)` | `ApiKeyGuard` | `x-api-key` header checked against `API_KEY`, `API_KEY_1`, `API_KEY_2`, ... (SHA-256 hashes when `hashed=True`) | +| `JWTModule.for_root(secret_env_var="JWT_SECRET", audience=..., issuer=...)` | `JwtGuard` | `Authorization: Bearer ` | +| `OAuthModule.for_root(resource_uri=..., authorization_servers=[...], scopes_supported=[...], token_introspection_endpoint=... or jwks_uri=...)` | `OAuthGuard` | OAuth 2.1 access tokens, audience-bound; `OAUTH_REQUIRED=true` to require one | + +```python +from nitrostack import ( + ApiKeyGuard, ApiKeyModule, ExecutionContext, OAuthGuard, module, require_scopes, tool, use_guards, +) + +class AccountController: + @tool(name="get_balance", description="Account balance", input_schema=NoInput) + @use_guards(ApiKeyGuard) + async def get_balance(self, input: NoInput, context: ExecutionContext) -> dict: + return {"balance": 42} + + @tool(name="close_account", description="Close the account", input_schema=NoInput) + @use_guards(OAuthGuard) + @require_scopes("admin") # needs context.auth with every listed scope + async def close_account(self, input: NoInput, context: ExecutionContext) -> dict: + return {"closed": True} + +@module(name="app", imports=[ApiKeyModule.for_root()], controllers=[AccountController]) +class AppModule: + pass +``` + +Register `ApiKeyModule` when you use `ApiKeyGuard`: without it, the guard falls back to the `API_KEY` variable, and with neither set it lets every call through. + +`has_scope`, `has_any_scope` and `has_all_scopes` check `context.auth` inside a tool. For OAuth, start from the `python-oauth` template and its `OAUTH_SETUP.md`; PKCE (`generate_pkce_params`, `verify_pkce`), client ID metadata documents (`resolve_cimd`) and `generate_www_authenticate_header` are exported for custom flows. + +### Caching and rate limits + +```python +from nitrostack import cache, injectable, rate_limit, tool + +@injectable() +class WeatherService: + @cache(ttl=60) # seconds; keyed on the arguments + async def lookup(self, city: str) -> dict: + return {"city": city, "temp": 21} + +class WeatherController: + @tool(name="ping", description="Ping", input_schema=NoInput) + @rate_limit(max=10, window=60) # 10 calls per 60 s, across all callers + async def ping(self, input: NoInput, context: ExecutionContext) -> str: + return "pong" +``` + +Put `@cache` on a service method with plain, hashable arguments (strings, numbers, tuples). It can't key on a tool's Pydantic input object. + +### Long-running tasks + +Set `task_support="optional"` (or `"required"`) and the client can run the tool as an MCP task: it polls `tasks/get`, can cancel it, and gets live `notifications/progress` when it sends a `progressToken`. `context.task` is `None` when the tool is called normally. + +```python +import asyncio +from pydantic import BaseModel +from nitrostack import tool, ExecutionContext + +class ReportInput(BaseModel): + steps: int = 5 + +class ReportController: + @tool(name="build_report", description="Build a report", input_schema=ReportInput, task_support="optional") + async def build_report(self, input: ReportInput, context: ExecutionContext) -> dict: + for step in range(1, input.steps + 1): + if context.task: + context.task.update_progress(f"Step {step}/{input.steps}") + context.task.throw_if_cancelled() + await asyncio.sleep(1) + return {"steps": input.steps} +``` + +### Events and health checks + +```python +from typing import List +from nitrostack import EventEmitter, health_check, injectable, on_event + +@injectable() +class OrderService: + async def place(self, order_id: str) -> None: + await EventEmitter.get_instance().emit("order.placed", {"id": order_id}) + +@injectable() +class AuditLog: + def __init__(self): + self.entries: List[str] = [] + + @on_event("order.placed") + def record(self, payload: dict) -> None: + self.entries.append(payload["id"]) + + @health_check("audit") + def healthy(self) -> bool: + return True +``` + +Listeners and health checks are found on any provider or controller in a module. When any health check exists, the server exposes the `health://status` resource (`{"audit": "healthy"}`). Keep health checks synchronous. + +--- + ## Transport Options NitroStack apps can run over three transports, selected via `MCP_TRANSPORT_TYPE` (or `ServerConfig(transport_type=...)`): @@ -432,7 +665,7 @@ Place HTML at `widgets/out/{route}.html` (e.g. `widgets/out/card.html`). The SDK `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 | |------|----------------|---------------| @@ -450,6 +683,8 @@ from nitrostack import WidgetOptions, WidgetCsp, widget prefers_border=True, csp=WidgetCsp(connect_domains=["https://api.example.com"]), )) +async def show_chart(self, input, context): + ... ``` `nitrostack-py init` copies `widgets/out/{route}.html` for every `@widget`. Widget HTML diff --git a/nitrostack/__init__.py b/nitrostack/__init__.py index 8ca72b1..f6f10e0 100644 --- a/nitrostack/__init__.py +++ b/nitrostack/__init__.py @@ -1,5 +1,26 @@ # NitroStack Python SDK Public API Exports +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 @@ -21,347 +42,211 @@ except (ImportError, KeyError, OSError, ValueError, TypeError): __version__ = "unknown" -from nitrostack.widgets.registry import ( - WidgetExample, - WidgetManifest, - WidgetMetadata, - WidgetRegistry, - get_widget_registry, -) -from nitrostack.core.interceptors import ( - DataSpilloverInterceptor, - FileSpilloverStore, - MemorySpilloverStore, - PayloadTooLargeError, - SpilloverEntry, - SpilloverStore, - generate_preview, -) +__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 -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.log_emitter import LogRecord, LogEmitter, LogEmitterHandler, log_emitter -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, - RateLimitExceededError, - 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, - TransformTelemetry, - ServerHealthPayload, -) -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.client import ( - AuthorizationFlow, - ClientRegistration, - OAuth2Client, - OAuth2ClientConfig, - OAuthClientError, - get_well_known_metadata_uris, - parse_www_authenticate_header, -) -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, -) -from nitrostack.auth.scopes import ( - has_all_scopes, - has_any_scope, - has_scope, - require_scopes, -) -from nitrostack.auth.config import ( - ConfigModule, - ConfigService, -) -from nitrostack.auth.secret import ( - SecretValue, - is_secret_value, - unwrap_secret, -) -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, -) -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 +def __dir__() -> list[str]: + return sorted({*globals().keys(), *__all__, *_subpackage_names()}) -__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", -] +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/config.py b/nitrostack/auth/config.py index a521972..a124578 100644 --- a/nitrostack/auth/config.py +++ b/nitrostack/auth/config.py @@ -22,7 +22,10 @@ def __init__( # Merge system environment variables first self._config.update(os.environ) - # Parse .env manually (no stdout prints allowed) + # Parse .env manually (no stdout prints allowed). The process + # environment wins, as with python-dotenv and Node's dotenv: a host + # that starts the server with PORT=3001 must not be overridden by the + # PORT=3000 that `nitrostack init` writes into .env. if not ignore_env_file and os.path.exists(env_file_path): try: with open(env_file_path, "r", encoding="utf-8") as f: @@ -34,6 +37,8 @@ def __init__( k, v = line.split("=", 1) k = k.strip() v = v.strip().strip("'\"") # Remove wrapping quotes + if k in os.environ: + continue self._config[k] = v os.environ[k] = v except Exception as e: diff --git a/nitrostack/cli/_pack_files.py b/nitrostack/cli/_pack_files.py index 4ccc99f..f0de42d 100644 --- a/nitrostack/cli/_pack_files.py +++ b/nitrostack/cli/_pack_files.py @@ -72,10 +72,17 @@ def _matches_gitignore(rel_posix: str, patterns: Sequence[Tuple[str, bool]]) -> return ignored -def _should_exclude(rel_posix: str, name: str, is_dir: bool, gitignore: Sequence[Tuple[str, bool]]) -> bool: +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): + if _is_secret_env(name) and not include_env: return True if name in _EXCLUDE_DIR_NAMES and is_dir: return True @@ -90,7 +97,7 @@ def _should_exclude(rel_posix: str, name: str, is_dir: bool, gitignore: Sequence return False -def collect_pack_files(root: str) -> List[str]: +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] = [] @@ -103,14 +110,14 @@ def collect_pack_files(root: str) -> List[str]: 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): + 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): + if _should_exclude(child_rel, filename, False, gitignore, include_env=include_env): continue included.append(child_rel) @@ -143,14 +150,14 @@ def _copy_selected(src_root: str, dest_root: str, files: Sequence[str]) -> None: shutil.copy2(src, dest) -def _collect_staging_bytes(src_root: str) -> dict: +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): + if _is_secret_env(filename) and not include_env: continue full = os.path.join(dirpath, filename) rel = os.path.relpath(full, src_root).replace("\\", "/") diff --git a/nitrostack/cli/_pack_metadata.py b/nitrostack/cli/_pack_metadata.py index 868a68c..bd59859 100644 --- a/nitrostack/cli/_pack_metadata.py +++ b/nitrostack/cli/_pack_metadata.py @@ -96,8 +96,12 @@ def requirements_from_project(root: str) -> List[str]: 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 + 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: diff --git a/nitrostack/cli/_pack_wheel.py b/nitrostack/cli/_pack_wheel.py index 0eb14da..929f30d 100644 --- a/nitrostack/cli/_pack_wheel.py +++ b/nitrostack/cli/_pack_wheel.py @@ -69,6 +69,8 @@ def _write_purelib_wheel( 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) @@ -78,7 +80,7 @@ def _write_purelib_wheel( wheel_path = os.path.join(wheel_dir, wheel_filename) dist_info = f"{dist_name}-{version}.dist-info" - contents = _collect_staging_bytes(src_root) + contents = _collect_staging_bytes(src_root, include_env=include_env) metadata_lines = [ "Metadata-Version: 2.1", f"Name: {display_name}", diff --git a/nitrostack/cli/_parser.py b/nitrostack/cli/_parser.py index 324e1a4..4be23e9 100644 --- a/nitrostack/cli/_parser.py +++ b/nitrostack/cli/_parser.py @@ -89,13 +89,18 @@ def build_parser(*, _add_port_flags, OFFICIAL_TEMPLATES): # pack command pack_parser = subparsers.add_parser( "pack", - help="Build a deployable wheel of the current project (never includes .env/secrets)", + 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( diff --git a/nitrostack/cli/_project_init.py b/nitrostack/cli/_project_init.py index 6faecdb..163ecd8 100644 --- a/nitrostack/cli/_project_init.py +++ b/nitrostack/cli/_project_init.py @@ -133,7 +133,7 @@ def init_project( 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") + 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) @@ -224,7 +224,10 @@ def init_project( 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( + " 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)") diff --git a/nitrostack/cli/_servers.py b/nitrostack/cli/_servers.py index 02d748f..8bc0930 100644 --- a/nitrostack/cli/_servers.py +++ b/nitrostack/cli/_servers.py @@ -1,10 +1,110 @@ """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" @@ -34,34 +134,37 @@ def run_dev(port=None, widget=None, *, _popen_npm, _resolve_runtime_ports): def start_process(): nonlocal process - if process: - try: - process.terminate() - process.wait(timeout=2) - except Exception: - try: - process.kill() - except Exception: - pass + _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) - process = subprocess.Popen([sys.executable, target], env=env) + # 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 - if process: - try: - process.terminate() - except Exception: - pass + _stop_child(process) + process = None if widgets_process: try: widgets_process.terminate() + widgets_process.wait(timeout=5) except Exception: - pass + try: + widgets_process.kill() + except Exception: + pass try: start_process() @@ -70,17 +173,18 @@ def cleanup(): 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)): + 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) - try: - mtimes[path] = os.path.getmtime(path) - except Exception: - pass + 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 @@ -91,18 +195,13 @@ def get_mtimes(): 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 + 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() - - time.sleep(0.5) if process and process.poll() is not None: print("Server process exited. Waiting for file changes to restart...") @@ -133,6 +232,7 @@ def get_mtimes(): 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): @@ -181,4 +281,4 @@ def run_start(port=None, widget=None, *, _popen_npm, _resolve_runtime_ports): try: widgets_process.terminate() except Exception: - pass + pass \ No newline at end of file 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/main.py b/nitrostack/cli/main.py index 1d2d62f..187b6a8 100644 --- a/nitrostack/cli/main.py +++ b/nitrostack/cli/main.py @@ -200,7 +200,6 @@ def run_login(user_id: str, email: str, org_id: str | None = None): organization_id=(org_id or "").strip() or None, ) - def run_dev(port=None, widget=None): return _servers.run_dev( port, @@ -265,87 +264,73 @@ def register_cursor_server(name: str, file_path: str = "main.py", *, global_conf ) -def main(): - if hasattr(sys.stdout, "reconfigure"): +def dispatch_command(args, gen_parser) -> None: + def _run_command(fn, *fn_args, **fn_kwargs): 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 + return fn(*fn_args, **fn_kwargs) + except Exception as exc: + print(f"Error: {exc}") + sys.exit(1) + + if args.command == "init": + init_project( + args.name, + args.template, + skip_install=args.skip_install, + port=args.port, + widget=args.widget, + force=args.force, + ) + elif args.command == "dev": + run_dev(port=args.port, widget=args.widget) + elif args.command == "start": + 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() + sys.exit(1) + if args.generator == "tool": + generate_tool(args.name) + elif args.generator == "module": + generate_module(args.name) + else: + generate_component(args.generator, args.name) + elif args.command == "pack": + _run_command(pack_project, dry_run=args.dry_run, include_env=args.include_env) + elif args.command == "upgrade": + _run_command( + upgrade_project, + version=args.target_version, + dry_run=args.dry_run, + allow_downgrade=args.allow_downgrade, + ) + elif args.command == "install": + _run_command(install_dependencies, production=args.production) + elif args.command == "validate": + issues = _run_command(validate_project) + 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) - 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) - - try: - maybe_print_first_run_notice() - track_command_invoked(args.command) - - def _run_command(fn, *fn_args, **fn_kwargs): - try: - return fn(*fn_args, **fn_kwargs) - except Exception as exc: - print(f"Error: {exc}") - sys.exit(1) - - if args.command == "init": - init_project( - args.name, - args.template, - skip_install=args.skip_install, - port=args.port, - widget=args.widget, - force=args.force, - ) - elif args.command == "dev": - run_dev(port=args.port, widget=args.widget) - elif args.command == "start": - 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() - sys.exit(1) - if args.generator == "tool": - generate_tool(args.name) - elif args.generator == "module": - generate_module(args.name) - else: - generate_component(args.generator, args.name) - elif args.command == "pack": - _run_command(pack_project, dry_run=args.dry_run) - elif args.command == "upgrade": - _run_command( - upgrade_project, - version=args.target_version, - dry_run=args.dry_run, - allow_downgrade=args.allow_downgrade, - ) - elif args.command == "install": - _run_command(install_dependencies, production=args.production) - elif args.command == "validate": - issues = _run_command(validate_project) - 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) - finally: - shutdown_telemetry() +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 dc933a1..717da4f 100644 --- a/nitrostack/cli/pack.py +++ b/nitrostack/cli/pack.py @@ -1,8 +1,9 @@ """Project packing for `nitrostack-py pack`. Builds a deployable wheel of the current project using the setuptools backend -already declared in NitroStack's packaging config. Secrets (``.env``) are never -included. Temporary build artifacts are cleaned up after packing. +already declared in NitroStack's packaging config. Secrets (``.env``) are excluded +by default; pass ``include_env`` to pack them. Temporary build artifacts are +cleaned up after packing. """ from __future__ import annotations @@ -46,6 +47,17 @@ ) +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}") + + def _build_wheel_with_setuptools(src_root: str, wheel_dir: str) -> Optional[str]: """Resolve the backend callback here so existing facade patches still apply.""" return _pack_wheel._build_wheel_with_setuptools( @@ -59,11 +71,16 @@ def _build_wheel( name: str, version: str, deps: Sequence[str], + *, + include_env: bool = False, ) -> str: + def _write_purelib_with_env(sr, wd, n, v, d): + return _write_purelib_wheel(sr, wd, n, v, d, include_env=include_env) + return _pack_wheel._build_wheel( src_root, wheel_dir, name, version, deps, build_with_setuptools=_build_wheel_with_setuptools, - write_purelib=_write_purelib_wheel, + write_purelib=_write_purelib_with_env, ) @@ -71,6 +88,7 @@ def pack_project( root: Optional[str] = None, *, dry_run: bool = False, + include_env: bool = False, output_dir: Optional[str] = None, ) -> dict: """Pack the project at ``root``. @@ -80,12 +98,15 @@ def pack_project( root = os.path.abspath(root or os.getcwd()) from nitrostack.cli.vendor import ensure_vendored_nitrostack ensure_vendored_nitrostack(root) - files = collect_pack_files(root) + files = collect_pack_files(root, include_env=include_env) name, version = _project_name_and_version(root) dist_name = _pep503_wheel_name(_normalize_dist_name(name)) planned_wheel = f"{dist_name}-{version}-py3-none-any.whl" dest_dir = os.path.abspath(output_dir or os.path.join(root, "dist")) + if include_env: + _warn_including_env_files(_secret_env_paths_in_pack(files)) + print("Files that would be packed:" if dry_run else "Packing files:") for rel in files: print(f" {rel}") @@ -105,12 +126,17 @@ def pack_project( write_requirements_txt(staging, deps) _ensure_pyproject(staging, name, version, deps) - wheel_path = _build_wheel(staging, wheel_tmp, 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): @@ -128,4 +154,4 @@ def pack_project( raise finally: _rmtree(staging) - _rmtree(wheel_tmp) + _rmtree(wheel_tmp) \ No newline at end of file diff --git a/nitrostack/cli/upgrade.py b/nitrostack/cli/upgrade.py index 4b6bf3d..121e0a6 100644 --- a/nitrostack/cli/upgrade.py +++ b/nitrostack/cli/upgrade.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json import os import re @@ -19,13 +20,20 @@ write_text_atomic, ) from nitrostack.cli.skills import upgrade_agent_skills +from nitrostack.cli.vendor import ( + VENDOR_REL, + _distribution_version, + replace_vendored_nitrostack, + vendored_version, +) PYPI_JSON = "https://pypi.org/pypi/nitrostack/json" PYPI_VERSION_JSON = "https://pypi.org/pypi/nitrostack/{version}/json" -# Name must not be a prefix of nitrostack-studio / nitrostack_extras / nitrostack.contrib. +# Name must not be a prefix of nitrostack-studio / nitrostack_extras / nitrostack.contrib, +# nor the tail of a path such as ./vendor/nitrostack. _DEP_RE = re.compile( - r'(["\']?)(nitrostack)(?![\w.-])((?:\s*(?:===|==|!=|~=|>=|<=|>|<)\s*[^"\'\s,#]+)?)(\1)', + r'(?=|<=|>|<)\s*[^"\'\s,#]+)?)(\1)', re.IGNORECASE, ) @@ -75,6 +83,46 @@ def verify_nitrostack_version(version: str, timeout: float = 15.0) -> None: raise UpgradeError(f"Could not reach PyPI to verify nitrostack=={version}: {exc}") from exc +def fetch_nitrostack_wheel(version: str, timeout: float = 60.0) -> bytes: + """Download the nitrostack wheel for ``version`` from PyPI and check its sha256.""" + req = urllib.request.Request( + PYPI_VERSION_JSON.format(version=version), + headers={"Accept": "application/json", "User-Agent": "nitrostack-py"}, + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + payload = json.loads(resp.read().decode("utf-8")) + wheels = [ + f for f in payload.get("urls") or [] + if f.get("packagetype") == "bdist_wheel" + and str(f.get("filename", "")).endswith("-none-any.whl") + ] + if not wheels: + raise UpgradeError(f"PyPI has no wheel for nitrostack=={version}.") + wheel = wheels[0] + expected = (wheel.get("digests") or {}).get("sha256") + if not expected: + raise UpgradeError( + f"PyPI lists no sha256 for {wheel.get('filename')}; not installing it." + ) + download = urllib.request.Request(wheel["url"], headers={"User-Agent": "nitrostack-py"}) + with urllib.request.urlopen(download, timeout=timeout) as resp: + data = resp.read() + except urllib.error.HTTPError as exc: + if exc.code == 404: + raise UpgradeError(f"nitrostack=={version} was not found on PyPI.") from exc + raise UpgradeError(f"Downloading nitrostack=={version} failed: {exc}") from exc + except urllib.error.URLError as exc: + raise UpgradeError( + f"Could not reach PyPI to download nitrostack=={version}: {exc}" + ) from exc + except json.JSONDecodeError as exc: + raise UpgradeError(f"PyPI returned invalid JSON: {exc}") from exc + if hashlib.sha256(data).hexdigest() != expected: + raise UpgradeError(f"{wheel.get('filename')} failed its sha256 check; not installing it.") + 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()]) @@ -85,6 +133,23 @@ def _is_source_reference(text: str, match: re.Match) -> bool: ) +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.""" + return find_toml_array_inner(text, "dependencies") or (0, 0) + + +def _find_pyproject_spec(text: str) -> Optional[str]: + start, end = _pyproject_dependencies(text) + return find_current_spec(text[start:end]) + + +def _replace_pyproject_spec(text: str, spec: str) -> Tuple[str, int]: + start, end = _pyproject_dependencies(text) + inner, count = replace_nitrostack_spec(text[start:end], spec) + return text[:start] + inner + text[end:], count + + def find_current_spec(text: str) -> Optional[str]: for match in _DEP_RE.finditer(text): # A [tool.uv.sources] key is not a dependency requirement. @@ -161,6 +226,68 @@ def _commit_file_changes(changes: list) -> list: raise +def _upgrade_vendored( + root: str, + current: str, + *, + version: Optional[str], + dry_run: bool, + verify: bool, + allow_downgrade: bool, +) -> dict: + """Replace `vendor/nitrostack` with the target release. + + `init` vendors the SDK and points uv at it with `[tool.uv.sources]`, so the + project runs that copy whatever version spec it declares. The dependency + stays the plain name `nitrostack` (see `vendor.py`). + """ + target = version or fetch_latest_nitrostack_version() + if version and verify: + verify_nitrostack_version(target) + try: + target_ver = Version(target) + except InvalidVersion as exc: + raise UpgradeError(f"Invalid target version '{target}': {exc}") from exc + try: + current_ver: Optional[Version] = Version(current) + except InvalidVersion: + current_ver = None + if not allow_downgrade and current_ver is not None and target_ver < current_ver: + raise UpgradeError( + f"Target {target} is older than the vendored nitrostack {current}. " + "Re-run with --allow-downgrade if you intend to downgrade." + ) + + vendor_dir = VENDOR_REL.replace(os.sep, "/") + change = {"file": vendor_dir, "from": current, "to": target} + up_to_date = current_ver == target_ver + print("NITROSTACK — Upgrade" + (" (dry run)" if dry_run else "")) + print(f"Target version: {target}") + print(f" {vendor_dir}: {current} → {target}" + (" (already installed)" if up_to_date else "")) + + written: list = [] + if dry_run: + print("\nDry run — no files modified.") + elif not up_to_date: + # The running CLI is the target release: copy it rather than download it. + wheel = None if _distribution_version() == target else fetch_nitrostack_wheel(target) + replace_vendored_nitrostack(root, wheel) + written = [vendor_dir] + print(f"Updated {vendor_dir}") + print(f"\nUpgrade complete. The project now runs nitrostack {target}.") + print("Run `nitrostack-py install` to install it.") + + skills = upgrade_agent_skills(root, dry_run=dry_run) + return { + "version": target, + "spec": "nitrostack", + "changes": [] if up_to_date else [change], + "dry_run": dry_run, + "written": written, + "skills": skills, + } + + def upgrade_project( root: Optional[str] = None, *, @@ -169,7 +296,12 @@ def upgrade_project( verify: bool = True, allow_downgrade: bool = False, ) -> dict: - """Update the nitrostack dependency spec in pyproject.toml (and requirements.txt if present).""" + """Move the project to another nitrostack release. + + Vendored projects (`vendor/nitrostack`, as `init` creates) get the vendored copy + replaced. Others get the dependency spec in pyproject.toml (and requirements.txt + if present) rewritten. + """ root = os.path.abspath(root or os.getcwd()) pyproject = os.path.join(root, "pyproject.toml") requirements = os.path.join(root, "requirements.txt") @@ -180,6 +312,17 @@ def upgrade_project( "Run this command from a NitroStack project, or create pyproject.toml first." ) + vendored = vendored_version(root) + if vendored is not None: + return _upgrade_vendored( + root, + vendored, + version=version, + dry_run=dry_run, + verify=verify, + allow_downgrade=allow_downgrade, + ) + target = version or fetch_latest_nitrostack_version() if version and verify: verify_nitrostack_version(target) @@ -191,7 +334,7 @@ def upgrade_project( current_specs = [] if original_pyproject is not None: - current_specs.append(find_current_spec(original_pyproject)) + current_specs.append(_find_pyproject_spec(original_pyproject)) if original_reqs is not None: current_specs.append(find_current_spec(original_reqs)) @@ -210,8 +353,8 @@ def upgrade_project( ) if original_pyproject is not None: - current = find_current_spec(original_pyproject) - updated, n = replace_nitrostack_spec(original_pyproject, new_spec) + current = _find_pyproject_spec(original_pyproject) + updated, n = _replace_pyproject_spec(original_pyproject, new_spec) if n == 0: updated = _add_to_pyproject_dependencies(original_pyproject, new_spec) current = current or "(missing)" diff --git a/nitrostack/cli/validators.py b/nitrostack/cli/validators.py index 2154299..7c41867 100644 --- a/nitrostack/cli/validators.py +++ b/nitrostack/cli/validators.py @@ -22,6 +22,7 @@ read_text, split_requirement, ) +from nitrostack.cli.vendor import VENDOR_REL @dataclass @@ -40,7 +41,9 @@ def format(self) -> str: def _iter_python_files(root: str) -> Iterable[str]: - vendored_sdk = os.path.join(os.path.abspath(root), "vendor", "nitrostack") + # The vendored SDK is not project code; its testing helpers apply @mcp_app + # inside functions, which reads as an app with no decorated class. + vendored_sdk = os.path.join(os.path.abspath(root), VENDOR_REL) for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [ d for d in dirnames diff --git a/nitrostack/cli/vendor.py b/nitrostack/cli/vendor.py index af35dd7..21dfbbc 100644 --- a/nitrostack/cli/vendor.py +++ b/nitrostack/cli/vendor.py @@ -8,16 +8,27 @@ """ from __future__ import annotations +import email.parser +import io +import json import os import re import shutil +import tempfile +import zipfile from pathlib import Path -from typing import Optional +from typing import List, Optional -from nitrostack.cli._shared import 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" @@ -87,8 +98,25 @@ def _distribution_version() -> str: ) -def _write_minimal_pyproject(dest: Path) -> None: - version = _distribution_version() +_DEFAULT_DEPENDENCIES = ( + "mcp>=2,<3", + "pydantic>=2.0.0", + "starlette>=0.30.0", + "uvicorn>=0.20.0", + "watchfiles>=0.18.0", + "anyio>=4.0.0", + "packaging>=23.0.0", + "tomli>=2.0.0; python_version < '3.11'", +) + + +def _write_minimal_pyproject( + dest: Path, + version: Optional[str] = None, + dependencies: Optional[List[str]] = None, +) -> None: + version = version or _distribution_version() + deps = "".join(f" {json.dumps(dep)},\n" for dep in (dependencies or _DEFAULT_DEPENDENCIES)) dest.mkdir(parents=True, exist_ok=True) (dest / "pyproject.toml").write_text( "[build-system]\n" @@ -100,17 +128,10 @@ def _write_minimal_pyproject(dest: Path) -> None: 'description = "NitroStack Python SDK (vendored)"\n' 'requires-python = ">=3.10"\n' "dependencies = [\n" - ' "mcp>=2,<3",\n' - ' "pydantic>=2.0.0",\n' - ' "starlette>=0.30.0",\n' - ' "uvicorn>=0.20.0",\n' - ' "watchfiles>=0.18.0",\n' - ' "anyio>=4.0.0",\n' - ' "packaging>=23.0.0",\n' - ' "tomli>=2.0.0; python_version < \'3.11\'",\n' + 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" @@ -142,6 +163,10 @@ def copy_running_nitrostack(dest: Path) -> None: else: _write_minimal_pyproject(dest) + _check_vendored_tree(dest) + + +def _check_vendored_tree(dest: Path) -> None: assets = dest / "nitrostack" / "transports" / "assets" / "landing.html" if not assets.is_file(): raise RuntimeError( @@ -150,9 +175,97 @@ def copy_running_nitrostack(dest: Path) -> None: ) +def extract_nitrostack_wheel(wheel: bytes, dest: Path) -> str: + """Unpack a nitrostack wheel into ``dest`` as a vendored tree; return its version. + + Skips the same directories as `copy_running_nitrostack` (templates, caches). + """ + with zipfile.ZipFile(io.BytesIO(wheel)) as archive: + metadata_name = next( + ( + n for n in archive.namelist() + if re.fullmatch(r"nitrostack-[^/]+\.dist-info/METADATA", n) + ), + None, + ) + if metadata_name is None: + raise RuntimeError("The downloaded file is not a nitrostack wheel (no METADATA).") + metadata = email.parser.Parser().parsestr(archive.read(metadata_name).decode("utf-8")) + version = metadata.get("Version") + if not version: + raise RuntimeError("The nitrostack wheel has no version in its METADATA.") + requires = [ + req for req in metadata.get_all("Requires-Dist") or [] + if not re.search(r"\bextra\s*==", req) + ] + + root = dest.resolve() + for name in archive.namelist(): + parts = name.split("/") + if parts[0] != "nitrostack" or name.endswith("/"): + continue + if any(part in _SKIP_DIR_NAMES or part.endswith(".egg-info") for part in parts[:-1]): + continue + target = (dest / name).resolve() + if root not in target.parents: + raise RuntimeError(f"Refusing to extract {name!r} outside {dest}.") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(archive.read(name)) + + _write_minimal_pyproject(dest, version=version, dependencies=requires) + _check_vendored_tree(dest) + return version + + +def vendored_version(project: str) -> Optional[str]: + """Version of the SDK in ``project/vendor/nitrostack``, or None if not vendored.""" + pyproject = Path(project) / VENDOR_REL / "pyproject.toml" + if not pyproject.is_file(): + return None + try: + data = loads_toml(pyproject.read_text(encoding="utf-8")) + version = data.get("project", {}).get("version") + except Exception: + return None + return str(version) if version else None + + +def replace_vendored_nitrostack(project: str, wheel: Optional[bytes] = None) -> str: + """Swap ``vendor/nitrostack`` for the running SDK, or for ``wheel`` when given. + + The new tree is built next to the old one and swapped in afterwards, so a + failed download or extraction leaves the project's current SDK in place. + Returns the vendored version. + """ + dest = Path(os.path.abspath(project)) / VENDOR_REL + dest.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix=".nitrostack-new-", dir=dest.parent)) + backup = dest.parent / f".nitrostack-old-{os.getpid()}" + try: + if wheel is None: + copy_running_nitrostack(staging) + version = _distribution_version() + else: + version = extract_nitrostack_wheel(wheel, staging) + if dest.exists(): + os.replace(dest, backup) + try: + os.replace(staging, dest) + except OSError: + if backup.exists(): + os.replace(backup, dest) + raise + finally: + shutil.rmtree(staging, ignore_errors=True) + shutil.rmtree(backup, ignore_errors=True) + pin_project_to_vendor(Path(os.path.abspath(project))) + return version + + 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: @@ -164,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") @@ -190,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/core/app_config.py b/nitrostack/core/app_config.py index 47ff9e9..9e62fab 100644 --- a/nitrostack/core/app_config.py +++ b/nitrostack/core/app_config.py @@ -118,6 +118,7 @@ class ServerConfig: 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 diff --git a/nitrostack/core/app_definitions.py b/nitrostack/core/app_definitions.py index a101422..c4b3a44 100644 --- a/nitrostack/core/app_definitions.py +++ b/nitrostack/core/app_definitions.py @@ -1,5 +1,6 @@ """Definitions implementation mixin.""" +import copy import logging from typing import Any, Dict, Type @@ -25,6 +26,13 @@ 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. @@ -40,7 +48,8 @@ def _tool_input_schema(self, input_model: Type[BaseModel]) -> Dict[str, Any]: def _build_tool_definition(self, entry: _ToolEntry) -> types.Tool: cfg = entry.config - input_schema = self._tool_input_schema(entry.input_model) + 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] = { @@ -105,7 +114,7 @@ def _build_tool_definition(self, entry: _ToolEntry) -> types.Tool: output_schema = tool_json_schema(cfg.output_schema) if output_schema is not None: - if self._has_spillover(entry.method): + if entry.has_spillover: output_schema = { "type": "object", "anyOf": [output_schema, SPILLOVER_SCHEMA], diff --git a/nitrostack/core/app_entries.py b/nitrostack/core/app_entries.py index 2dd2a37..9177e15 100644 --- a/nitrostack/core/app_entries.py +++ b/nitrostack/core/app_entries.py @@ -2,7 +2,7 @@ import logging from dataclasses import dataclass, field -from typing import Any, Callable, List, Optional, Pattern, Type +from typing import Any, Callable, Dict, List, Optional, Pattern, Type from pydantic import BaseModel @@ -19,6 +19,8 @@ class _ToolEntry: instance: Any method: Callable component: Optional[Component] = None + input_json_schema: Optional[Dict[str, Any]] = None + has_spillover: Optional[bool] = None @dataclass 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_registration.py b/nitrostack/core/app_registration.py index 0d5f99b..6f6c0cf 100644 --- a/nitrostack/core/app_registration.py +++ b/nitrostack/core/app_registration.py @@ -6,7 +6,7 @@ import logging import time from pathlib import Path -from typing import Any, Callable, List, Set, Type +from typing import Any, Callable, List, Sequence, Set, Type from unittest.mock import NonCallableMock import mcp.types as types @@ -54,8 +54,9 @@ def _bootstrap(self) -> None: ) # 2. Resolve Module Tree recursively and register services - resolved_modules: Set[Type] = set() - self._resolve_modules(self.root_module, resolved_modules) + 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) @@ -127,16 +128,20 @@ def _bootstrap(self) -> None: # 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(): - 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) + 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: Set[Type], container: DIContainer + self, resolved_modules: Sequence[Type], container: DIContainer ) -> None: """Fail at bootstrap when a string ``deps=[...]`` token was never registered.""" missing: List[str] = [] @@ -166,15 +171,21 @@ def walk(cls: Any) -> None: "but never registered): " + "; ".join(missing) ) - def _resolve_modules(self, module_class: Type, resolved_modules: Set[Type]) -> None: - if module_class in resolved_modules: + def _resolve_modules( + self, + module_class: Type, + resolved_modules: List[Type], + resolved_seen: Set[Type], + ) -> None: + if module_class in resolved_seen: return - resolved_modules.add(module_class) + 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) + 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") @@ -220,6 +231,8 @@ def _register_tool(self, instance: Any, method: Callable, tool_config: ToolConfi 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( diff --git a/nitrostack/core/app_startup.py b/nitrostack/core/app_startup.py index 990922d..18efc6f 100644 --- a/nitrostack/core/app_startup.py +++ b/nitrostack/core/app_startup.py @@ -70,6 +70,7 @@ def get_combined_app( 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 diff --git a/nitrostack/core/context.py b/nitrostack/core/context.py index 7766389..15e5c03 100644 --- a/nitrostack/core/context.py +++ b/nitrostack/core/context.py @@ -209,6 +209,7 @@ class ExecutionContext: _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: diff --git a/nitrostack/core/pipeline.py b/nitrostack/core/pipeline.py index 1b0a765..929b6df 100644 --- a/nitrostack/core/pipeline.py +++ b/nitrostack/core/pipeline.py @@ -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) diff --git a/nitrostack/templates/flight-booking/.env.example b/nitrostack/templates/flight-booking/.env.example index 2ebf690..e53f573 100644 --- a/nitrostack/templates/flight-booking/.env.example +++ b/nitrostack/templates/flight-booking/.env.example @@ -5,7 +5,7 @@ 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 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/transports/http/app.py b/nitrostack/transports/http/app.py index 57e10c8..3bfb2f7 100644 --- a/nitrostack/transports/http/app.py +++ b/nitrostack/transports/http/app.py @@ -33,11 +33,12 @@ DEFAULT_ENDPOINT, logger, ) -from nitrostack.transports.http.env import _env_flag, _env_list +from nitrostack.transports.http.env import _env_flag, _env_list, resolve_json_body_limit from nitrostack.transports.http.handlers import make_handlers from nitrostack.transports.http.middleware import ( ExactEndpointSlashMiddleware, HeaderCompatMiddleware, + JsonBodyLimitMiddleware, SessionCapMiddleware, ) from nitrostack.transports.http.tracing import ( @@ -72,6 +73,7 @@ def build_http_app( protocol_era: ProtocolEra = "auto", wire_mode: WireMode = "stateless", http_engine: Optional[HttpEngine] = None, + json_body_limit: str | int | None = None, ) -> Starlette: """ Build the Starlette app exposing NitroStack's owned low-level server over @@ -264,6 +266,12 @@ async def lifespan(app): _enable_trace_logging() middleware.insert(0, Middleware(RequestTraceMiddleware)) + limit_bytes = resolve_json_body_limit(json_body_limit) + middleware.insert( + 0, + Middleware(JsonBodyLimitMiddleware, limit_bytes=limit_bytes), + ) + app = Starlette(routes=routes, middleware=middleware, lifespan=lifespan) app.state.protocol_era = protocol_era app.state.wire_mode = wire_mode diff --git a/nitrostack/transports/http/env.py b/nitrostack/transports/http/env.py index e205dc1..fa1a07b 100644 --- a/nitrostack/transports/http/env.py +++ b/nitrostack/transports/http/env.py @@ -2,7 +2,10 @@ from __future__ import annotations import os -from typing import List +import re +from typing import List, Union + +DEFAULT_JSON_BODY_LIMIT = "1mb" def _env_list(name: str) -> List[str]: @@ -13,4 +16,27 @@ def _env_list(name: str) -> List[str]: def _env_flag(name: str) -> bool: - return (os.environ.get(name) or "").strip().lower() in {"1", "true", "yes", "on"} \ No newline at end of file + return (os.environ.get(name) or "").strip().lower() in {"1", "true", "yes", "on"} + + +def parse_json_body_limit(value: Union[str, int]) -> int: + if isinstance(value, int): + return value + text = str(value).strip().lower().replace(" ", "") + match = re.fullmatch(r"(\d+)(b|kb|mb)?", text) + if not match: + raise ValueError(f"Invalid JSON body limit: {value!r}") + amount = int(match.group(1)) + unit = match.group(2) or "b" + if unit == "kb": + return amount * 1024 + if unit == "mb": + return amount * 1024 * 1024 + return amount + + +def resolve_json_body_limit(config_value: Union[str, int, None] = None) -> int: + """Config wins, then ``NITROSTACK_JSON_BODY_LIMIT`` / ``MCP_JSON_BODY_LIMIT``, else 1mb.""" + env = os.environ.get("NITROSTACK_JSON_BODY_LIMIT") or os.environ.get("MCP_JSON_BODY_LIMIT") + raw = config_value if config_value is not None else (env or DEFAULT_JSON_BODY_LIMIT) + return parse_json_body_limit(raw) \ No newline at end of file diff --git a/nitrostack/transports/http/middleware.py b/nitrostack/transports/http/middleware.py index 5fbf314..41f8728 100644 --- a/nitrostack/transports/http/middleware.py +++ b/nitrostack/transports/http/middleware.py @@ -10,6 +10,76 @@ from nitrostack.transports.http.constants import MCP_ACCEPT, logger +class JsonBodyLimitMiddleware: + """Reject oversized JSON HTTP bodies with 413 before the MCP stack parses them.""" + + def __init__(self, app: ASGIApp, *, limit_bytes: int) -> None: + self.app = app + self.limit_bytes = limit_bytes + + @staticmethod + def _json_media_type(value: bytes) -> bool: + media = value.decode("latin-1").split(";", 1)[0].strip().lower() + if media == "application/json": + return True + return media.startswith("application/") and media.endswith("+json") + + @staticmethod + def _is_json_post(scope: Scope) -> bool: + if scope.get("type") != "http" or scope.get("method") != "POST": + return False + for key, value in scope.get("headers") or []: + if key.lower() == b"content-type" and JsonBodyLimitMiddleware._json_media_type(value): + return True + return False + + async def _reject_too_large(self, scope: Scope, receive: Receive, send: Send) -> None: + response = JSONResponse({"error": "Payload too large"}, status_code=413) + await response(scope, receive, send) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if not self._is_json_post(scope): + await self.app(scope, receive, send) + return + + for key, value in scope.get("headers") or []: + if key.lower() == b"content-length": + try: + if int(value) > self.limit_bytes: + await self._reject_too_large(scope, receive, send) + return + except ValueError: + break + + buffered: List[Any] = [] + total = 0 + while True: + message = await receive() + if message["type"] != "http.request": + buffered.append(message) + break + chunk = message.get("body", b"") or b"" + total += len(chunk) + if total > self.limit_bytes: + await self._reject_too_large(scope, receive, send) + return + buffered.append(message) + if not message.get("more_body", False): + break + + replay_index = 0 + + async def replay_receive(): + nonlocal replay_index + if replay_index < len(buffered): + message = buffered[replay_index] + replay_index += 1 + return message + return await receive() + + await self.app(scope, replay_receive, send) + + class ExactEndpointSlashMiddleware: """Internally rewrite `/mcp` -> `/mcp/` so Starlette does not 307.""" diff --git a/nitrostack/widgets/preview_page.py b/nitrostack/widgets/preview_page.py index 007f428..1d9bb16 100644 --- a/nitrostack/widgets/preview_page.py +++ b/nitrostack/widgets/preview_page.py @@ -27,7 +27,7 @@

MCP Inspector Tools tab shows JSON. Open the Apps tab (or this page) to render the widget from the live tools/call result — - not sample data. Use NITROSTACK_APP_MODE=universal (the SDK default). + not sample data. Use NITROSTACK_APP_MODE=universal for MCP Apps + OpenAI together (default is openai). For open shops only, keep openNow: true (or map filter: open_now). This page is /widgets/preview — not the static widgets/preview.html file.

diff --git a/pyproject.toml b/pyproject.toml index a59108f..9739a17 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nitrostack" -version = "0.3.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" @@ -38,8 +38,14 @@ dev = [ "tox>=4.0.0", ] +[project.urls] +Homepage = "https://nitrostack.ai/" +Documentation = "https://docs.nitrostack.ai/python" +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/scripts/bump_version.py b/scripts/bump_version.py new file mode 100644 index 0000000..4b466ae --- /dev/null +++ b/scripts/bump_version.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Bump and sync the SDK version in pyproject.toml and uv.lock. + +Version sources of truth: + - pyproject.toml [project].version + - uv.lock [[package]] name = \"nitrostack\" (editable .) + +Template app versions (0.1.0) and README CLI examples are not the SDK release. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +import urllib.request +from typing import Optional, Sequence, Tuple + +PYPI_JSON = "https://pypi.org/pypi/nitrostack/json" +_PROJECT_VERSION = re.compile(r'(?m)^(version = ")([^"]+)(")') +_LOCK_NITROSTACK = re.compile( + r'(name = "nitrostack"\nversion = ")([^"]+)("\nsource = \{ editable = "\." \})', +) + + +def parse_x_y_z(raw: str) -> Tuple[int, int, int]: + parts = (raw or "").strip().split(".") + if len(parts) != 3 or not all(p.isdigit() for p in parts): + raise ValueError(f"Expected X.Y.Z version, got {raw!r}") + return int(parts[0]), int(parts[1]), int(parts[2]) + + +def bump_x_y_z(raw: str, kind: str) -> str: + major, minor, patch = parse_x_y_z(raw) + if kind == "major": + return f"{major + 1}.0.0" + if kind == "minor": + return f"{major}.{minor + 1}.0" + if kind == "patch": + return f"{major}.{minor}.{patch + 1}" + raise ValueError(f"Unknown bump kind {kind!r}") + + +def version_key(raw: str) -> Tuple[int, int, int]: + return parse_x_y_z(raw) + + +def read_project_version(pyproject_text: str) -> str: + match = _PROJECT_VERSION.search(pyproject_text) + if not match: + raise ValueError("pyproject.toml has no version = \"...\" field") + return match.group(2) + + +def set_project_version(pyproject_text: str, version: str) -> str: + updated, n = _PROJECT_VERSION.subn(rf"\g<1>{version}\3", pyproject_text, count=1) + if n != 1: + raise ValueError("Could not replace [project].version in pyproject.toml") + return updated + + +def set_lock_nitrostack_version(lock_text: str, version: str) -> str: + updated, n = _LOCK_NITROSTACK.subn(rf"\g<1>{version}\3", lock_text, count=1) + if n != 1: + raise ValueError("Could not replace editable nitrostack version in uv.lock") + return updated + + +def fetch_pypi(url: str = PYPI_JSON) -> dict: + with urllib.request.urlopen(url, timeout=30) as response: + return json.load(response) + + +def pypi_latest_and_released(payload: dict) -> Tuple[Optional[str], set]: + info = payload.get("info") or {} + latest = info.get("version") + released = set((payload.get("releases") or {}).keys()) + return latest, released + + +def plan_bump(git_ver: str, latest: Optional[str], released: set, kind: str) -> Optional[str]: + """Return the next version to write, or None if a bump PR is not needed. + + Unpublished git versions are left for the publish workflow (git not on PyPI). + Otherwise bump from max(git, PyPI latest) so a stale git version cannot + collide with a manual upload (e.g. git 0.3.2, PyPI 0.3.5 → 0.3.6). + """ + if git_ver not in released: + return None + base = git_ver + if latest: + base = git_ver if version_key(git_ver) >= version_key(latest) else latest + return bump_x_y_z(base, kind) + + +def should_publish(git_ver: str, released: set) -> bool: + return git_ver not in released + + +def _read(path: str) -> str: + with open(path, "r", encoding="utf-8") as handle: + return handle.read() + + +def _write(path: str, text: str) -> None: + with open(path, "w", encoding="utf-8") as handle: + handle.write(text) + + +def apply_version(root: str, version: str) -> None: + pyproject = f"{root}/pyproject.toml" + lock = f"{root}/uv.lock" + _write(pyproject, set_project_version(_read(pyproject), version)) + _write(lock, set_lock_nitrostack_version(_read(lock), version)) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default=".") + parser.add_argument("--bump", choices=("patch", "minor", "major"), default="patch") + parser.add_argument( + "--write", + action="store_true", + help="Write pyproject.toml and uv.lock. Prints the new version.", + ) + parser.add_argument( + "--if-unpublished", + action="store_true", + help="Exit 0 if the git version is not on PyPI (publish it); else exit 1.", + ) + args = parser.parse_args(argv) + + git_ver = read_project_version(_read(f"{args.root}/pyproject.toml")) + payload = fetch_pypi() + latest, released = pypi_latest_and_released(payload) + + if args.if_unpublished: + if should_publish(git_ver, released): + print(git_ver) + return 0 + print(f"skip: {git_ver} is already on PyPI", file=sys.stderr) + return 1 + + planned = plan_bump(git_ver, latest, released, args.bump) + if planned is None: + print( + f"skip: {git_ver} is not on PyPI yet (publish this version first)", + file=sys.stderr, + ) + return 0 + if args.write: + apply_version(args.root, planned) + print(planned) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100644 index 0000000..8042f2f --- /dev/null +++ b/scripts/release.sh @@ -0,0 +1,263 @@ +#!/usr/bin/env bash +# Release the SDK to PyPI from this machine. +# +# publish.yml uploads only through PyPI trusted publishing, and the Bump +# version workflow can't open its release PR (the org doesn't let GitHub +# Actions create pull requests). This script does both by hand. +# +# 1. Get a release branch, either way: +# - the Bump version workflow already pushed `release/X.Y.Z`: +# git switch release/X.Y.Z && git pull +# - or have this script make one from origin/main: +# scripts/release.sh --bump patch (or minor / major) +# 2. On that branch: scripts/release.sh +# checks, tests, builds, uploads to PyPI (asks first), verifies the +# install, tags the uploaded commit vX.Y.Z, and opens the release PR. +# 3. Merge the release PR (publish.yml sees the version on PyPI and skips). +# +# Options: +# --bump KIND patch|minor|major: create release/ from origin/main +# --skip-tests don't run the test suite before building +# --yes don't ask before uploading +# --dry-run stop before anything leaves this machine (no push, upload, +# PR or tag); --bump still creates the branch locally +# --tag only tag a version that's already on PyPI but untagged +# (the head of origin/release/X.Y.Z if it still exists, +# else origin/main) +# +# Needs uv, gh (for the PR) and a PyPI token, in ~/.pypirc ([pypi] with +# username __token__) or in TWINE_USERNAME=__token__ / TWINE_PASSWORD. +set -euo pipefail + +# bash reads a script while running it, and --bump switches branches, which +# can rewrite this file. Run from a copy. +if [ -z "${NITRO_RELEASE_ROOT:-}" ]; then + NITRO_RELEASE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + copy="$(mktemp)" + cp "${BASH_SOURCE[0]}" "$copy" + NITRO_RELEASE_ROOT="$NITRO_RELEASE_ROOT" NITRO_RELEASE_COPY="$copy" exec bash "$copy" "$@" +fi +trap 'rm -f "${NITRO_RELEASE_COPY:-}"' EXIT +ROOT="$NITRO_RELEASE_ROOT" +cd "$ROOT" + +BUMP="" +SKIP_TESTS=0 +YES=0 +DRY_RUN=0 +TAG_ONLY=0 +while [ $# -gt 0 ]; do + case "$1" in + --bump) + BUMP="${2:-}" + shift + ;; + --skip-tests) SKIP_TESTS=1 ;; + --yes) YES=1 ;; + --dry-run) DRY_RUN=1 ;; + --tag) TAG_ONLY=1 ;; + -h | --help) + sed -n '2,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//' + exit 0 + ;; + *) + echo "Unknown option: $1 (see --help)" >&2 + exit 2 + ;; + esac + shift +done +case "$BUMP" in "" | patch | minor | major) ;; *) + echo "--bump takes patch, minor or major" >&2 + exit 2 + ;; +esac + +step() { printf '\n==> %s\n' "$*"; } +fail() { + printf '\nerror: %s\n' "$*" >&2 + exit 1 +} + +# uv: a pyenv shim fails inside this repo when the pinned .python-version +# isn't installed in pyenv, so fall back to known install locations. +find_uv() { + local candidate + for candidate in "${UV:-}" "$(command -v uv 2>/dev/null || true)" \ + "$HOME/.local/bin/uv" "$HOME/.cargo/bin/uv" /opt/homebrew/bin/uv /usr/local/bin/uv \ + "$HOME"/.pyenv/versions/*/bin/uv; do + if [ -n "$candidate" ] && [ -x "$candidate" ] && "$candidate" --version >/dev/null 2>&1; then + echo "$candidate" + return 0 + fi + done + return 1 +} +UV="$(find_uv)" || fail "uv not found. Install it (https://docs.astral.sh/uv/) or set UV=/path/to/uv." +UVX="$(dirname "$UV")/uvx" +[ -x "$UVX" ] || UVX="$UV tool run" +PY=("$UV" run --no-project --quiet python) + +project_version() { "${PY[@]}" -c 'import re,sys; print(re.search(r"(?m)^version = \"([^\"]+)\"", sys.stdin.read()).group(1))'; } +# Exit 0 when VERSION is on PyPI, 1 when it isn't; stop on any other answer +# (offline, PyPI down) rather than guess. +on_pypi() { + local code + code="$(curl -s -o /dev/null -w '%{http_code}' "https://pypi.org/pypi/nitrostack/$1/json" || true)" + case "$code" in + 200) return 0 ;; + 404) return 1 ;; + *) fail "Couldn't check PyPI for $1 (HTTP ${code:-none}). Check your connection and try again." ;; + esac +} +tag_exists() { git rev-parse -q --verify "refs/tags/v$1" >/dev/null || [ -n "$(git ls-remote --tags origin "refs/tags/v$1")" ]; } + +step "Fetching origin" +git fetch -q --tags origin + +# --- Step 4: tag the merged release ------------------------------------- +if [ "$TAG_ONLY" = 1 ]; then + VERSION="$(git show origin/main:pyproject.toml | project_version)" + echo "origin/main is at $VERSION" + on_pypi "$VERSION" || fail "$VERSION isn't on PyPI. Release it first (scripts/release.sh on its release branch)." + tag_exists "$VERSION" && fail "Tag v$VERSION already exists." + # Tag what was uploaded: the release branch head, when it's still around. + TARGET=origin/main + if git rev-parse -q --verify "refs/remotes/origin/release/$VERSION" >/dev/null && + [ "$(git show "origin/release/$VERSION:pyproject.toml" | project_version)" = "$VERSION" ]; then + TARGET="origin/release/$VERSION" + fi + if [ "$DRY_RUN" = 1 ]; then + echo "Dry run: would tag $TARGET ($(git rev-parse --short "$TARGET")) as v$VERSION and push it." + exit 0 + fi + git tag -a "v$VERSION" "$TARGET" -m "nitrostack $VERSION" + git push -q origin "v$VERSION" + echo "Tagged and pushed v$VERSION." + exit 0 +fi + +[ -z "$(git status --porcelain --untracked-files=no)" ] || fail "Uncommitted changes. Commit or stash them first." + +# --- Step 1 (optional): make the release branch ------------------------- +if [ -n "$BUMP" ]; then + step "Creating a $BUMP release branch from origin/main" + MAIN_VERSION="$(git show origin/main:pyproject.toml | project_version)" + on_pypi "$MAIN_VERSION" || fail "origin/main's version $MAIN_VERSION isn't on PyPI yet. Release it as is (no --bump)." + # Plan from origin/main's files (and its bump_version.py) in a scratch + # folder, so nothing changes here until every check has passed. + PLAN="$(mktemp -d)" + for f in pyproject.toml uv.lock scripts/bump_version.py; do + mkdir -p "$PLAN/$(dirname "$f")" + git show "origin/main:$f" >"$PLAN/$f" + done + NEXT="$("${PY[@]}" "$PLAN/scripts/bump_version.py" --root "$PLAN" --bump "$BUMP" | tail -n 1)" + [ -n "$NEXT" ] || fail "PyPI's project index doesn't list $MAIN_VERSION yet (it's cached for up to 15 minutes after a release). Try again shortly." + git rev-parse -q --verify "refs/heads/release/$NEXT" >/dev/null && fail "Branch release/$NEXT already exists locally." + [ -z "$(git ls-remote --heads origin "release/$NEXT")" ] || fail "release/$NEXT already exists on origin. Use it: git switch release/$NEXT" + "${PY[@]}" "$PLAN/scripts/bump_version.py" --root "$PLAN" --bump "$BUMP" --write >/dev/null + git switch -q -c "release/$NEXT" origin/main + cp "$PLAN/pyproject.toml" "$PLAN/uv.lock" . + rm -rf "$PLAN" + git add pyproject.toml uv.lock + git commit -q -m "chore(release): $NEXT" + echo "Created release/$NEXT with the version bump." + if [ "$DRY_RUN" = 0 ]; then + git push -q -u origin "release/$NEXT" + fi +fi + +# --- Step 2: check, test, build, upload --------------------------------- +BRANCH="$(git branch --show-current)" +[ -n "$BRANCH" ] || fail "Not on a branch. Switch to the release branch first." +VERSION="$(project_version &2 + +step "Checking the release on PyPI" +for _ in $(seq 1 30); do + on_pypi "$VERSION" && break + sleep 10 +done +on_pypi "$VERSION" || fail "PyPI doesn't list $VERSION after 5 minutes. Check https://pypi.org/project/nitrostack/" +VENV="$(mktemp -d)/venv" +"$UV" venv --quiet "$VENV" +installed="" +for _ in $(seq 1 12); do + if "$UV" pip install --quiet --no-cache --python "$VENV" "nitrostack==$VERSION" 2>/dev/null; then + installed="$("$VENV/bin/python" -c 'import importlib.metadata as m, nitrostack; print(m.version("nitrostack"))')" + break + fi + sleep 10 +done +rm -rf "$(dirname "$VENV")" +[ "$installed" = "$VERSION" ] || fail "Couldn't install and import nitrostack==$VERSION from PyPI." +echo "OK: pip install nitrostack==$VERSION works and imports." + +# --- Release PR --------------------------------------------------------- +step "Release PR" +if ! command -v gh >/dev/null; then + echo "gh not found. Open a PR from $BRANCH to main, labelled 'release'." +else + PR="$(gh pr list --base main --head "$BRANCH" --json url --jq '.[0].url // empty')" + if [ -z "$PR" ]; then + PR="$(gh pr create --base main --head "$BRANCH" --title "chore(release): $VERSION" --label release --body "$( + cat <=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_upgrade_vendored.py b/tests/test_cli_upgrade_vendored.py new file mode 100644 index 0000000..45f3398 --- /dev/null +++ b/tests/test_cli_upgrade_vendored.py @@ -0,0 +1,236 @@ +"""`nitrostack-py upgrade` on projects shaped like `init` creates them. + +`init` vendors the SDK into vendor/nitrostack and points uv at it with a +`[tool.uv.sources]` entry, so upgrade must replace that copy and must not +touch the source entry. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import zipfile +from pathlib import Path +from unittest.mock import patch + +import pytest + +from nitrostack.cli import vendor +from nitrostack.cli._shared import loads_toml +from nitrostack.cli.upgrade import ( + UpgradeError, + fetch_nitrostack_wheel, + replace_nitrostack_spec, + upgrade_project, +) +from nitrostack.cli.vendor import ( + ensure_vendored_nitrostack, + extract_nitrostack_wheel, + vendored_version, +) + +INIT_PYPROJECT = ( + "[project]\n" + 'name = "demo"\n' + 'version = "0.1.0"\n' + 'requires-python = ">=3.10"\n' + "dependencies = [\n" + ' "nitrostack",\n' + "]\n\n" + "[tool.uv.sources]\n" + 'nitrostack = { path = "vendor/nitrostack" }\n' +) + + +def _wheel(version: str, extra_files: dict | None = None) -> bytes: + files = { + "nitrostack/__init__.py": f"VERSION = {version!r}\n", + "nitrostack/transports/assets/landing.html": "", + "nitrostack/templates/starter/main.py": "print('template')\n", + f"nitrostack-{version}.dist-info/METADATA": ( + "Metadata-Version: 2.1\n" + "Name: nitrostack\n" + f"Version: {version}\n" + "Requires-Dist: mcp<3,>=2\n" + "Requires-Dist: pydantic>=2.0.0\n" + 'Requires-Dist: tomli>=2.0.0; python_version < "3.11"\n' + 'Requires-Dist: pytest>=7.4.0; extra == "dev"\n' + ), + } + files.update(extra_files or {}) + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + for name, content in files.items(): + archive.writestr(name, content) + return buffer.getvalue() + + +@pytest.fixture +def no_skills(): + with patch( + "nitrostack.cli.upgrade.upgrade_agent_skills", return_value={"skipped": True} + ) as mock: + yield mock + + +@pytest.fixture +def project(tmp_path: Path) -> Path: + (tmp_path / "pyproject.toml").write_text(INIT_PYPROJECT, encoding="utf-8") + (tmp_path / "requirements.txt").write_text("nitrostack\n", encoding="utf-8") + assert ensure_vendored_nitrostack(str(tmp_path), quiet=True) + return tmp_path + + +def test_spec_rewrite_skips_the_uv_source_entry(tmp_path: Path, no_skills): + # Not vendored, but the pyproject still names nitrostack in [tool.uv.sources]. + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text(INIT_PYPROJECT, encoding="utf-8") + with patch("nitrostack.cli.upgrade.verify_nitrostack_version"): + upgrade_project(str(tmp_path), version="1.2.3", verify=False, allow_downgrade=True) + parsed = loads_toml(pyproject.read_text(encoding="utf-8")) + assert parsed["project"]["dependencies"] == ["nitrostack==1.2.3"] + assert parsed["tool"]["uv"]["sources"]["nitrostack"] == {"path": "vendor/nitrostack"} + + +def test_spec_rewrite_skips_vendor_paths(): + text = "-e ./vendor/nitrostack\nnitrostack>=0.3.0\n" + updated, count = replace_nitrostack_spec(text, "nitrostack>=9.9.9") + assert count == 1 + assert updated == "-e ./vendor/nitrostack\nnitrostack>=9.9.9\n" + + +def test_upgrade_replaces_the_vendored_sdk_from_the_wheel(project: Path, no_skills): + pyproject_before = (project / "pyproject.toml").read_text(encoding="utf-8") + with ( + patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value="9.9.9"), + patch( + "nitrostack.cli.upgrade.fetch_nitrostack_wheel", return_value=_wheel("9.9.9") + ) as fetch, + ): + result = upgrade_project(str(project)) + + fetch.assert_called_once_with("9.9.9") + assert result["written"] == ["vendor/nitrostack"] + assert result["changes"][0]["to"] == "9.9.9" + assert vendored_version(str(project)) == "9.9.9" + sdk = project / "vendor" / "nitrostack" + assert (sdk / "nitrostack" / "__init__.py").read_text(encoding="utf-8") == "VERSION = '9.9.9'\n" + assert not (sdk / "nitrostack" / "templates").exists() + deps = loads_toml((sdk / "pyproject.toml").read_text(encoding="utf-8"))["project"][ + "dependencies" + ] + 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 + 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-")] + + +def test_upgrade_to_the_running_version_copies_it(project: Path, no_skills): + running = vendor._distribution_version() + (project / "vendor" / "nitrostack" / "pyproject.toml").write_text( + '[project]\nname = "nitrostack"\nversion = "0.0.1"\n', encoding="utf-8" + ) + with ( + patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value=running), + patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel") as fetch, + ): + upgrade_project(str(project)) + fetch.assert_not_called() + assert vendored_version(str(project)) == running + + +def test_upgrade_vendored_dry_run_same_version_and_downgrade(project: Path, no_skills): + current = vendored_version(str(project)) + snapshot = sorted(p.relative_to(project) for p in project.rglob("*")) + + with ( + patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value="9.9.9"), + patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel") as fetch, + ): + dry = upgrade_project(str(project), dry_run=True) + fetch.assert_not_called() + assert dry["changes"] == [{"file": "vendor/nitrostack", "from": current, "to": "9.9.9"}] + assert dry["written"] == [] + + with ( + patch("nitrostack.cli.upgrade.verify_nitrostack_version"), + patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel") as fetch, + ): + same = upgrade_project(str(project), version=current) + with pytest.raises(UpgradeError, match="allow-downgrade"): + upgrade_project(str(project), version="0.0.1") + fetch.assert_not_called() + assert same["changes"] == [] and same["written"] == [] + assert sorted(p.relative_to(project) for p in project.rglob("*")) == snapshot + + +def test_failed_download_or_bad_wheel_keeps_the_current_sdk(project: Path, no_skills): + current = vendored_version(str(project)) + with patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value="9.9.9"): + with patch( + "nitrostack.cli.upgrade.fetch_nitrostack_wheel", side_effect=UpgradeError("offline") + ): + with pytest.raises(UpgradeError, match="offline"): + upgrade_project(str(project)) + with patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel", return_value=b"not a zip"): + with pytest.raises(zipfile.BadZipFile): + upgrade_project(str(project)) + assert vendored_version(str(project)) == current + assert ( + project / "vendor" / "nitrostack" / "nitrostack" / "transports" / "assets" / "landing.html" + ).is_file() + assert not [p for p in (project / "vendor").iterdir() if p.name.startswith(".nitrostack-")] + + +def test_extract_refuses_paths_outside_the_vendor_dir(tmp_path: Path): + evil = _wheel("9.9.9", {"nitrostack/../../escaped.py": "boom"}) + with pytest.raises(RuntimeError, match="outside"): + extract_nitrostack_wheel(evil, tmp_path / "sdk") + assert not (tmp_path / "escaped.py").exists() + + +class _Response(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def _pypi(wheel: bytes, digest: str): + payload = { + "urls": [ + { + "packagetype": "sdist", + "filename": "nitrostack-9.9.9.tar.gz", + "url": "https://x/sdist", + "digests": {}, + }, + { + "packagetype": "bdist_wheel", + "filename": "nitrostack-9.9.9-py3-none-any.whl", + "url": "https://x/wheel", + "digests": {"sha256": digest}, + }, + ] + } + + def urlopen(request, timeout=None): + url = request.full_url + return _Response(json.dumps(payload).encode() if url.endswith("/json") else wheel) + + return urlopen + + +def test_fetch_wheel_checks_sha256(): + wheel = _wheel("9.9.9") + good = hashlib.sha256(wheel).hexdigest() + with patch("urllib.request.urlopen", side_effect=_pypi(wheel, good)): + assert fetch_nitrostack_wheel("9.9.9") == wheel + with patch("urllib.request.urlopen", side_effect=_pypi(wheel, "0" * 64)): + with pytest.raises(UpgradeError, match="sha256"): + fetch_nitrostack_wheel("9.9.9") 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_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_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_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_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 index 2c3f1a1..fd6f94d 100644 --- a/tests/test_project_templates.py +++ b/tests/test_project_templates.py @@ -21,6 +21,12 @@ 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): @@ -54,6 +60,17 @@ def test_new_templates_in_cli_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) @@ -66,10 +83,11 @@ def test_generated_project_lifecycle(name, kind, tmp_path): run([kind], project) if kind == "code-mode": run(["cleanup"], project) - run(["cli", "upgrade", "--version", "0.3.2"], 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() - assert "nitrostack==0.3.2" in requirements if kind == "code-mode": assert "quickjs>=1.19.4" in requirements assert "quickjs>=1.19.4" in (project / "pyproject.toml").read_text() diff --git a/tests/test_readme_examples.py b/tests/test_readme_examples.py index 9bc8541..843fa98 100644 --- a/tests/test_readme_examples.py +++ b/tests/test_readme_examples.py @@ -1,23 +1,166 @@ -"""README code blocks marked with must run as written.""" +"""README examples must stay true to the SDK: PyPI shows this README. +Every ```python block must compile and import only names the SDK has. The +Quick Start and Building Blocks examples are also run through the testing +harness. +""" from __future__ import annotations import asyncio +import importlib +import os import re -from pathlib import Path +import sys +import types import pytest -README = Path(__file__).resolve().parent.parent / "README.md" -BLOCKS = re.findall(r"\n```python\n(.*?)```", README.read_text(encoding="utf-8"), re.S) +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +sys.path.insert(0, ROOT) + +from nitrostack import DIContainer, NitroTestingModule, module # noqa: E402 +from nitrostack.core.additional_decorators import HealthCheckRegistry # noqa: E402 +from nitrostack.events.event_emitter import EventEmitter # noqa: E402 + +README = open(os.path.join(ROOT, "README.md"), encoding="utf-8").read() +FENCE = re.compile(r"^```python\n(.*?)^```", re.S | re.M) + + +def _section(title: str) -> str: + match = re.search(rf"^## {re.escape(title)}\n(.*?)(?=^## |\Z)", README, re.S | re.M) + assert match, f"README has no '## {title}' section" + return match.group(1) + + +def _blocks(text: str): + return FENCE.findall(text) + + +@pytest.fixture(autouse=True) +def fresh_globals(): + DIContainer.reset() + EventEmitter.reset() + HealthCheckRegistry._bound_checks.clear() + yield + DIContainer.reset() + EventEmitter.reset() + HealthCheckRegistry._bound_checks.clear() + + +def test_every_python_block_compiles(): + blocks = _blocks(README) + assert len(blocks) >= 10 + for i, code in enumerate(blocks): + compile(code, f"README.md python block {i + 1}", "exec") + + +def test_every_nitrostack_import_exists(): + imports = re.compile(r"^from (nitrostack[\w.]*) import (\([^)]*\)|[^\n]*)", re.M) + checked = 0 + for code in _blocks(README): + for mod_name, names in imports.findall(code): + mod = importlib.import_module(mod_name) + for name in re.split(r"[,\s()]+", names): + if not name or name.startswith("#"): + continue + assert hasattr(mod, name), f"README imports {name!r} from {mod_name}, which doesn't have it" + checked += 1 + assert checked >= 30 + + +def test_quick_start_runs(): + code = _blocks(_section("Quick Start"))[0] + app = types.ModuleType("readme_quick_start_app") + exec(compile(code, "README quick start", "exec"), app.__dict__) + + async def run(): + harness = await NitroTestingModule.create(app.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" + + asyncio.run(run()) + + +def test_building_blocks_run(monkeypatch): + monkeypatch.setenv("WEATHER_API_KEY", "test") + monkeypatch.setenv("API_KEY", "secret") + monkeypatch.delenv("OAUTH_REQUIRED", raising=False) + + # The section's blocks build on each other; keep every controller and + # service each block defines (several reuse the name WeatherController). + namespace: dict = {"__name__": "readme_building_blocks"} + controllers, providers = [], [] + for i, code in enumerate(_blocks(_section("Building Blocks"))): + before = dict(namespace) + exec(compile(code, f"README building block {i + 1}", "exec"), namespace) + for name, value in namespace.items(): + if not isinstance(value, type) or before.get(name) is value: + continue + if name.endswith("Controller"): + controllers.append(value) + elif name in ("WeatherService", "OrderService", "AuditLog"): + providers.append(value) + + @module(name="app", imports=[namespace["ApiKeyModule"].for_root()], controllers=controllers, providers=providers) + class AppModule: + pass + + async def run(): + h = await NitroTestingModule.create(AppModule) + assert await h.call_tool("get_weather", {"city": "Paris"}) == {"city": "Paris", "temp": 21, "units": "metric"} + assert await h.call_tool("whats_new", {}) == "Try get_weather." + assert await h.read_resource("weather://units") == "metric" + messages = await h.get_prompt("forecast_brief", {"city": "Oslo"}) + assert "Oslo" in str(messages) + + assert await h.call_tool("get_forecast", {"city": "Rome"}) == {"city": "Rome", "forecast": "sunny"} + assert "Access denied" in str(await h.call_tool("get_balance", {})) + assert "Not authenticated" in str(await h.call_tool("close_account", {})) + + assert [await h.call_tool("ping", {}) for _ in range(10)] == ["pong"] * 10 + assert "Rate limit exceeded" in str(await h.call_tool("ping", {})) + + service = DIContainer.get_instance().resolve(namespace["WeatherService"]) + assert await service.lookup("Paris") is await service.lookup("Paris") + + assert await h.call_tool("build_report", {"steps": 1}) == {"steps": 1} + + await DIContainer.get_instance().resolve(namespace["OrderService"]).place("A1") + assert DIContainer.get_instance().resolve(namespace["AuditLog"]).entries == ["A1"] + assert await h.read_resource("health://status") == {"audit": "healthy"} + + asyncio.run(run()) + + +def test_config_service_example(tmp_path, monkeypatch): + code = _blocks(_section("Quick Start"))[1] + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("WEATHER_API_KEY", "k") + monkeypatch.delenv("WEATHER_UNITS", raising=False) + namespace: dict = {"__name__": "readme_config"} + exec(compile(code, "README config example", "exec"), namespace) + + async def run(): + await NitroTestingModule.create(namespace["AppModule"]) + service = DIContainer.get_instance().resolve(namespace["WeatherService"]) + 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 BLOCKS + assert _README_TEST_BLOCKS -@pytest.mark.parametrize("source", BLOCKS) -def test_readme_example_runs(source): +@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)] 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_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_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_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_vendor.py b/tests/test_vendor.py index f80ca7f..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): @@ -86,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_widgets.py b/tests/test_widgets.py index 82908b0..efad2b9 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -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 diff --git a/uv.lock b/uv.lock index 9077aeb..a0154ab 100644 --- a/uv.lock +++ b/uv.lock @@ -758,7 +758,7 @@ wheels = [ [[package]] name = "nitrostack" -version = "0.3.2" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "anyio" },