From 50484d840797ff018b43402698ae10063d4e87b0 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Tue, 15 Sep 2026 12:37:22 +0530 Subject: [PATCH 001/146] fix: remove duplicate MCP JSON-RPC sidecar --- nitrostack/__init__.py | 3 - nitrostack/core/app.py | 35 +- nitrostack/protocol/__init__.py | 2 - nitrostack/protocol/jsonrpc.py | 5 - nitrostack/transports/__init__.py | 16 +- nitrostack/transports/dispatch.py | 558 ------------------------ nitrostack/transports/http.py | 3 +- nitrostack/transports/middleware.py | 524 ---------------------- tests/test_mcp22_official_http_owner.py | 98 +++++ 9 files changed, 105 insertions(+), 1139 deletions(-) delete mode 100644 nitrostack/transports/dispatch.py delete mode 100644 nitrostack/transports/middleware.py create mode 100644 tests/test_mcp22_official_http_owner.py diff --git a/nitrostack/__init__.py b/nitrostack/__init__.py index 9f1c3d5..d918872 100644 --- a/nitrostack/__init__.py +++ b/nitrostack/__init__.py @@ -135,7 +135,6 @@ from nitrostack.tasks import InMemoryTaskStore, TaskAccessContext, TaskStore from nitrostack.tasks.authorization import check_task_access, extract_task_access_context from nitrostack.runtime import StatelessInvariants, assert_stateless_headers -from nitrostack.transports import wrap_stateless_transport, StatelessIngressPipeline __all__ = [ @@ -242,6 +241,4 @@ "extract_task_access_context", "StatelessInvariants", "assert_stateless_headers", - "wrap_stateless_transport", - "StatelessIngressPipeline", ] diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index a0bc83e..581ab88 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -1769,37 +1769,10 @@ def get_combined_app( http_engine=http_engine, ) - if http_engine == "sessionless": - from nitrostack.transports.middleware import wrap_stateless_transport - - def _discover_handler(_request): - return self.handle_server_discover() - - def _initialize_handler(request): - params = getattr(request, "params", None) or {} - requested = params.get("protocolVersion") if isinstance(params, dict) else None - return self.handle_sessionless_initialize( - requested if isinstance(requested, str) else None - ) - - http_app = wrap_stateless_transport( - http_app, - server_name=self.server_config.name, - server_version=self.server_config.version, - protocol_version=protocol_version_for_era(era, self.server_config.protocol_version), - advertise_tasks=self._advertise_tasks_extension(), - advertise_app=any( - getattr(entry, "component", None) is not None - for entry in getattr(self, "_tools", {}).values() - ), - custom_extensions=self._custom_extensions(), - wire_mode=wire_mode, - protocol_era=era, - enable_cors=enable_cors, - discover_handler=_discover_handler, - initialize_handler=_initialize_handler, - ) - + # The official MCP SDK owns the complete Streamable HTTP request lifecycle + # mounted by ``build_http_app``. Do not wrap it in a second JSON-RPC + # dispatcher: a sidecar would answer ping/initialize/tools/call itself and + # could diverge from the protocol and session behaviour of the SDK. return http_app async def _run_stdio(self) -> None: diff --git a/nitrostack/protocol/__init__.py b/nitrostack/protocol/__init__.py index 86dad4b..1aaf760 100644 --- a/nitrostack/protocol/__init__.py +++ b/nitrostack/protocol/__init__.py @@ -32,7 +32,6 @@ from nitrostack.protocol.extensions import MCPExtensionId from nitrostack.protocol.jsonrpc import ( JsonRpcWireError, - build_ping_response, build_tool_error_result, jsonrpc_error, jsonrpc_success, @@ -166,7 +165,6 @@ "build_sessionless_initialize_result", "build_discover_result", "parse_jsonrpc_request", - "build_ping_response", "jsonrpc_success", "jsonrpc_error", "build_tool_error_result", diff --git a/nitrostack/protocol/jsonrpc.py b/nitrostack/protocol/jsonrpc.py index 24239e2..43c7e87 100644 --- a/nitrostack/protocol/jsonrpc.py +++ b/nitrostack/protocol/jsonrpc.py @@ -239,11 +239,6 @@ def jsonrpc_error(request_id: Any, code: int, message: str, data: Any = None) -> return {"jsonrpc": JSONRPC_VERSION, "id": request_id, "error": error} -def build_ping_response(request_id: Any) -> dict[str, Any]: - """Ping fast path.""" - return jsonrpc_success(request_id, {}) - - def build_tool_error_result(message: str, *, text_type: str = "text") -> dict[str, Any]: """ Tool business failure — JSON-RPC success with isError: true. diff --git a/nitrostack/transports/__init__.py b/nitrostack/transports/__init__.py index 6cf62b1..32d0742 100644 --- a/nitrostack/transports/__init__.py +++ b/nitrostack/transports/__init__.py @@ -1,12 +1,4 @@ -"""MCP transport adapters (stdio, stateless HTTP).""" - -from nitrostack.transports.dispatch import ( - DispatchStage, - IngressContext, - StatelessIngressPipeline, - is_task_wire_interception, -) -from nitrostack.transports.middleware import StatelessTransportMiddleware, wrap_stateless_transport +"""MCP transport adapters (stdio and the official Streamable HTTP engine).""" from nitrostack.transports.sse import format_sse_message, sse_connect_headers, sse_notification from nitrostack.transports.subscriptions import ( http_listen_requires_auth, @@ -15,12 +7,6 @@ ) __all__ = [ - "DispatchStage", - "IngressContext", - "StatelessIngressPipeline", - "StatelessTransportMiddleware", - "wrap_stateless_transport", - "is_task_wire_interception", "format_sse_message", "sse_connect_headers", "sse_notification", diff --git a/nitrostack/transports/dispatch.py b/nitrostack/transports/dispatch.py deleted file mode 100644 index f4005b9..0000000 --- a/nitrostack/transports/dispatch.py +++ /dev/null @@ -1,558 +0,0 @@ -"""Stateless HTTP ingress pipeline.""" - -from __future__ import annotations - -import json -from dataclasses import dataclass -from enum import Enum -from collections.abc import Awaitable -from typing import Any, Callable, Optional, Union - -from nitrostack.protocol.deprecated import ( - deprecated_method_message, - rejects_deprecated_method, -) -from nitrostack.protocol.discovery import ( - INITIALIZE_METHOD, - INITIALIZED_NOTIFICATION, - SERVER_DISCOVER_METHOD, - build_sessionless_initialize_result, -) -from nitrostack.protocol.errors import ERROR_CODE_MESSAGES, JsonRpcErrorCode -from nitrostack.protocol.jsonrpc import ( - HeaderBodyMismatchError, - InvalidRequestError, - JsonRpcParseError, - JsonRpcRequest, - JsonRpcWireError, - MethodNotFoundError, - build_ping_response, - jsonrpc_error, - jsonrpc_success, - parse_jsonrpc_request, - validate_header_body_method, - validate_header_body_name, - UnsupportedProtocolVersionError, - validate_protocol_version_header_meta, - validate_required_mcp_method, - validate_required_mcp_name, - validate_supported_protocol_version, -) -from nitrostack.protocol.method_contract import ( - mcp_method_is_required, - mcp_name_field, - mcp_name_is_required, -) -from nitrostack.protocol.meta import envelope_protocol_version -from nitrostack.protocol.version import ( - LEGACY_PROTOCOL_VERSION, - ProtocolEra, - WireMode, - accepts_sessionless_initialize, - protocol_era_for_wire_mode, - rejects_legacy_initialize, - supported_protocol_versions_for_era, -) -from nitrostack.runtime.stateless import ( - is_unsupported_protocol_version, - request_protocol_version, - sessionless_strips_incoming_session_id, -) -from nitrostack.transports.headers import ( - HEADER_MCP_METHOD, - HEADER_MCP_NAME, - HEADER_MCP_PROTOCOL_VERSION, - first_oversized_mcp_param, - get_header, - strip_legacy_session_headers, -) - -TaskDispatchHandler = Callable[[JsonRpcRequest], Awaitable[Optional[dict[str, Any]]]] -RegistryDispatchHandler = Callable[[JsonRpcRequest], Awaitable[Optional[dict[str, Any]]]] -DiscoverHandler = Callable[[JsonRpcRequest], Union[Awaitable[dict[str, Any]], dict[str, Any]]] -InitializeHandler = Callable[[JsonRpcRequest], Union[Awaitable[dict[str, Any]], dict[str, Any]]] - - -class DispatchStage(str, Enum): - """Six-step stateless HTTP ingress lifecycle.""" - - CORS_SECURITY = "cors_security" - BODY_PARSING = "body_parsing" - PING_FAST_PATH = "ping_fast_path" - TASK_INTERCEPTION = "task_interception" - REGISTRY_DISPATCH = "registry_dispatch" - RESPONSE_SERIALIZATION = "response_serialization" - - -TASK_METHOD_PREFIX = "tasks/" -TOOLS_CALL_METHOD = "tools/call" -PING_METHOD = "ping" -LEGACY_HANDSHAKE_METHODS = frozenset({"initialize", "notifications/initialized"}) - - -def is_header_only_ping(raw_body: bytes, request_headers: dict[str, str]) -> bool: - """True when ``Mcp-Method: ping`` and the body is empty or not JSON-RPC. - - A parsed JSON-RPC body is never header-only: header/body match still applies. - Other ``Mcp-Method`` values are not answered from the header alone. - """ - header_method = get_header(request_headers, HEADER_MCP_METHOD) - if header_method is None or header_method.strip() != PING_METHOD: - return False - if not raw_body or not raw_body.strip(): - return True - try: - parse_jsonrpc_request(raw_body) - except (JsonRpcParseError, JsonRpcWireError): - return True - return False - - -@dataclass -class IngressContext: - server_name: str - server_version: str - protocol_version: str - advertise_tasks: bool = True - advertise_app: bool = False - custom_extensions: Optional[dict[str, str]] = None - wire_mode: WireMode = "stateless" - protocol_era: Optional[ProtocolEra] = None - - def resolved_era(self) -> ProtocolEra: - if self.protocol_era is not None: - return self.protocol_era - return protocol_era_for_wire_mode(self.wire_mode) - - def accepts_sessionless_initialize(self) -> bool: - """True when this engine answers 2025 ``initialize`` without a session.""" - return accepts_sessionless_initialize(self.resolved_era()) - - def rejects_legacy_initialize(self) -> bool: - """True when this engine rejects 2025 ``initialize`` / ``initialized``.""" - return rejects_legacy_initialize(self.resolved_era()) - - -def prepare_sessionless_request_headers( - request_headers: dict[str, str], - wire_mode: WireMode, -) -> dict[str, str]: - """ - Drop client ``Mcp-Session-Id`` on sessionless engines (``modern`` / ``auto``). - - Obsolete session headers must not become a dependency; they are ignored rather - than rejected so stateless clients stay unambiguous. - """ - if not sessionless_strips_incoming_session_id(wire_mode): - return request_headers - return strip_legacy_session_headers(request_headers) - - -def reject_legacy_handshake( - request: JsonRpcRequest, - era: ProtocolEra, -) -> Optional[tuple[int, dict[str, Any]]]: - """Era ``modern`` answers ``initialize`` / ``initialized`` as method-not-found.""" - return reject_legacy_handshake_method(request.method, request.id, era) - - -def reject_legacy_handshake_method( - method: str, - request_id: Any, - era: ProtocolEra, -) -> Optional[tuple[int, dict[str, Any]]]: - """Era ``modern`` answers handshake methods as method-not-found.""" - if not rejects_legacy_initialize(era): - return None - if method not in LEGACY_HANDSHAKE_METHODS: - return None - return 200, MethodNotFoundError(method).to_response(request_id) - - -def reject_deprecated_method( - request: JsonRpcRequest, - era: ProtocolEra, -) -> Optional[tuple[int, dict[str, Any]]]: - """Era ``modern`` answers retired 2025 methods as method-not-found.""" - return reject_deprecated_method_name(request.method, request.id, era) - - -def reject_deprecated_method_name( - method: str, - request_id: Any, - era: ProtocolEra, -) -> Optional[tuple[int, dict[str, Any]]]: - """Same retired-method error used on POST, GET, and replay.""" - if not rejects_deprecated_method(method, era): - return None - message = deprecated_method_message(method) - return 200, jsonrpc_error( - request_id, - int(JsonRpcErrorCode.METHOD_NOT_FOUND), - message or f"Method not found: {method}", - ) - - -def reject_modern_method_policy( - method: str, - request_id: Any, - era: ProtocolEra, -) -> Optional[tuple[int, dict[str, Any]]]: - """Handshake then retired-method policy. ``auto`` does not error here.""" - handshake = reject_legacy_handshake_method(method, request_id, era) - if handshake is not None: - return handshake - return reject_deprecated_method_name(method, request_id, era) - - -def reject_legacy_wire( - request: JsonRpcRequest, - request_headers: dict[str, str], - era: ProtocolEra, -) -> Optional[tuple[int, dict[str, Any]]]: - """ - Era ``modern`` fails closed on 2025 handshake and 2025 protocol versions. - - Official v2 ``legacy: 'reject'`` is not mounted yet; this is the sidecar - stand-in. Handshake methods are method-not-found before header contracts. - Incoming session ids are rejected earlier. - """ - handshake = reject_legacy_handshake(request, era) - if handshake is not None: - return handshake - - if not rejects_legacy_initialize(era): - return None - - header_version = get_header(request_headers, HEADER_MCP_PROTOCOL_VERSION) - body_version = request.params.get("protocolVersion") - if header_version == LEGACY_PROTOCOL_VERSION or body_version == LEGACY_PROTOCOL_VERSION: - return 400, jsonrpc_error( - request.id, - int(JsonRpcErrorCode.UNSUPPORTED_PROTOCOL_VERSION), - ERROR_CODE_MESSAGES[JsonRpcErrorCode.UNSUPPORTED_PROTOCOL_VERSION], - ) - - return None - - -def is_task_wire_interception(method: str, params: dict[str, Any]) -> bool: - """Ingress step 4 — route to the task subsystem when matched.""" - if method.startswith(TASK_METHOD_PREFIX): - return True - return method == TOOLS_CALL_METHOD and bool(params.get("task")) - - -def reject_required_mcp_name( - request: JsonRpcRequest, - request_headers: dict[str, str], - wire_mode: WireMode, -) -> Optional[tuple[int, dict[str, Any]]]: - """Require or cross-check ``Mcp-Name`` on name-scoped methods.""" - if not mcp_name_is_required(request.method): - return None - field = mcp_name_field(request.method) or "name" - header_name = get_header(request_headers, HEADER_MCP_NAME) - body_name = request.params.get(field) - body_value = body_name if isinstance(body_name, str) else None - try: - if wire_mode == "stateless": - if header_name is not None: - validate_header_body_name(header_name, body_value) - elif not (body_value and body_value.strip()): - raise InvalidRequestError( - f"{field!r} is required in params for {request.method!r}" - ) - else: - validate_required_mcp_name( - header_name, - body_value, - body_label=field, - ) - except HeaderBodyMismatchError as exc: - return 400, exc.to_response(request.id) - except InvalidRequestError as exc: - return 400, exc.to_response(request.id) - return None - - -def reject_required_mcp_method( - request: JsonRpcRequest, - request_headers: dict[str, str], - wire_mode: WireMode, -) -> Optional[tuple[int, dict[str, Any]]]: - """Require or optionally cross-check ``Mcp-Method`` against the JSON-RPC method.""" - header_method = get_header(request_headers, HEADER_MCP_METHOD) - try: - if mcp_method_is_required(request.method, wire_mode): - validate_required_mcp_method(header_method, request.method) - else: - validate_header_body_method(header_method, request.method) - except HeaderBodyMismatchError as exc: - return 400, exc.to_response(request.id) - return None - - -def reject_protocol_version_mismatch( - request: JsonRpcRequest, - request_headers: dict[str, str], -) -> Optional[tuple[int, dict[str, Any]]]: - """Reject when header and ``_meta.mcp.protocolVersion`` both exist and differ.""" - header_version = get_header(request_headers, HEADER_MCP_PROTOCOL_VERSION) - meta_version = envelope_protocol_version(request.meta) - try: - validate_protocol_version_header_meta(header_version, meta_version) - except HeaderBodyMismatchError as exc: - return 400, exc.to_response(request.id) - return None - - -def reject_unsupported_protocol_version( - request: JsonRpcRequest, - request_headers: dict[str, str], - era: ProtocolEra, -) -> Optional[tuple[int, dict[str, Any]]]: - """ - Reject a present protocol version that the era does not support. - - Absent header and envelope versions are allowed (legacy default). The - header is not required on ``modern`` in this sidecar. - """ - header_version = get_header(request_headers, HEADER_MCP_PROTOCOL_VERSION) - meta_version = envelope_protocol_version(request.meta) - version = request_protocol_version(header_version, meta_version) - if not is_unsupported_protocol_version(version, era): - return None - try: - validate_supported_protocol_version(version, supported_protocol_versions_for_era(era)) - except UnsupportedProtocolVersionError as exc: - return 400, exc.to_response(request.id) - return None - - -class StatelessIngressPipeline: - """ - Deterministic JSON-RPC pre-dispatch for stateless POST /mcp. - - Handles ping and deprecated-method rejection inline. - ``server/discover`` is forwarded to the HTTP engine handler when provided. - Task and tool methods always return None so ``TaskManager`` plus the - low-level MCP server remain the only production task path. - """ - - def __init__( - self, - context: IngressContext, - *, - task_handler: Optional[TaskDispatchHandler] = None, - registry_handler: Optional[RegistryDispatchHandler] = None, - discover_handler: Optional[DiscoverHandler] = None, - initialize_handler: Optional[InitializeHandler] = None, - ) -> None: - self._context = context - self._task_handler = task_handler - self._registry_handler = registry_handler - self._discover_handler = discover_handler - self._initialize_handler = initialize_handler - - def reject_tools_call_mcp_name( - self, - raw_body: bytes, - request_headers: dict[str, str], - ) -> Optional[tuple[int, dict[str, Any]]]: - """Replay-path ``Mcp-Name`` check for name-scoped methods.""" - try: - request = parse_jsonrpc_request(raw_body) - except (JsonRpcParseError, JsonRpcWireError): - return None - return reject_required_mcp_name( - request, request_headers, self._context.wire_mode - ) - - def reject_jsonrpc_mcp_method( - self, - raw_body: bytes, - request_headers: dict[str, str], - ) -> Optional[tuple[int, dict[str, Any]]]: - """Replay-path ``Mcp-Method`` check for JSON-RPC POST.""" - try: - request = parse_jsonrpc_request(raw_body) - except (JsonRpcParseError, JsonRpcWireError): - return None - return reject_required_mcp_method(request, request_headers, self._context.wire_mode) - - def reject_protocol_version_cross_check( - self, - raw_body: bytes, - request_headers: dict[str, str], - ) -> Optional[tuple[int, dict[str, Any]]]: - """Replay-path header vs envelope protocol version check.""" - try: - request = parse_jsonrpc_request(raw_body) - except (JsonRpcParseError, JsonRpcWireError): - return None - return reject_protocol_version_mismatch(request, request_headers) - - def reject_unsupported_protocol_version_header( - self, - raw_body: bytes, - request_headers: dict[str, str], - ) -> Optional[tuple[int, dict[str, Any]]]: - """Replay-path unsupported protocol version check.""" - try: - request = parse_jsonrpc_request(raw_body) - except (JsonRpcParseError, JsonRpcWireError): - return None - return reject_unsupported_protocol_version( - request, request_headers, self._context.resolved_era() - ) - - def reject_method_policy( - self, - raw_body: bytes, - request_headers: dict[str, str], - ) -> Optional[tuple[int, dict[str, Any]]]: - """Handshake and retired-method policy for POST, GET, and replay.""" - era = self._context.resolved_era() - try: - request = parse_jsonrpc_request(raw_body) - except (JsonRpcParseError, JsonRpcWireError): - header_method = get_header(request_headers, HEADER_MCP_METHOD) - if header_method is None: - return None - return reject_modern_method_policy(header_method.strip(), None, era) - return reject_modern_method_policy(request.method, request.id, era) - - def response_protocol_version(self) -> str: - """Advertised version used when the request does not name a supported one.""" - return self._context.protocol_version - - def response_supported_versions(self) -> frozenset[str]: - return supported_protocol_versions_for_era(self._context.resolved_era()) - - async def handle_post( - self, - raw_body: bytes, - request_headers: dict[str, str], - ) -> Optional[tuple[int, dict[str, Any]]]: - """ - Run ingress steps 2–5. Returns None to delegate to the underlying MCP app. - Step 1 (CORS) is handled by transport middleware. - """ - request_headers = prepare_sessionless_request_headers( - request_headers, self._context.wire_mode - ) - - if is_header_only_ping(raw_body, request_headers): - return 200, build_ping_response(None) - - try: - request = parse_jsonrpc_request(raw_body) - except JsonRpcParseError as exc: - return 400, exc.to_response(None) - except JsonRpcWireError as exc: - return 400, exc.to_response(None) - - rejected_handshake = reject_legacy_handshake( - request, self._context.resolved_era() - ) - if rejected_handshake is not None: - return rejected_handshake - - required_method = reject_required_mcp_method( - request, request_headers, self._context.wire_mode - ) - if required_method is not None: - return required_method - - required_name = reject_required_mcp_name( - request, request_headers, self._context.wire_mode - ) - if required_name is not None: - return required_name - - oversized = first_oversized_mcp_param(request_headers) - if oversized is not None: - return 400, InvalidRequestError( - "Mcp-Param header exceeds the maximum size" - ).to_response(request.id) - - header_name = get_header(request_headers, HEADER_MCP_NAME) - name_field = mcp_name_field(request.method) - body_name = request.params.get(name_field) if name_field else ( - request.params.get("name") or request.params.get("uri") - ) - if not mcp_name_is_required(request.method) and isinstance(body_name, str): - try: - validate_header_body_name(header_name, body_name) - except HeaderBodyMismatchError as exc: - return 400, exc.to_response(request.id) - - version_mismatch = reject_protocol_version_mismatch(request, request_headers) - if version_mismatch is not None: - return version_mismatch - - unsupported = reject_unsupported_protocol_version( - request, request_headers, self._context.resolved_era() - ) - if unsupported is not None: - return unsupported - - rejected = reject_legacy_wire(request, request_headers, self._context.resolved_era()) - if rejected is not None: - return rejected - - deprecated = reject_deprecated_method(request, self._context.resolved_era()) - if deprecated is not None: - return deprecated - - if request.method == PING_METHOD: - return 200, build_ping_response(request.id) - - if self._context.accepts_sessionless_initialize(): - if request.method == INITIALIZE_METHOD: - if self._initialize_handler is not None: - result = self._initialize_handler(request) - if isinstance(result, Awaitable): - result = await result - else: - requested = request.params.get("protocolVersion") - result = build_sessionless_initialize_result( - server_name=self._context.server_name, - server_version=self._context.server_version, - requested_version=requested if isinstance(requested, str) else None, - protocol_version=self._context.protocol_version, - advertise_tasks=self._context.advertise_tasks, - advertise_app=self._context.advertise_app, - custom_extensions=self._context.custom_extensions, - ) - return 200, jsonrpc_success(request.id, result) - if request.method == INITIALIZED_NOTIFICATION: - return 202, {} - - if request.method == SERVER_DISCOVER_METHOD: - if self._discover_handler is None: - return None - result = self._discover_handler(request) - if isinstance(result, Awaitable): - result = await result - return 200, jsonrpc_success(request.id, result) - - if is_task_wire_interception(request.method, request.params): - if self._task_handler is not None: - response = await self._task_handler(request) - if response is not None: - return 200, response - return None - - if self._registry_handler is not None: - response = await self._registry_handler(request) - if response is not None: - return 200, response - - return None - - @staticmethod - def serialize_response(jsonrpc_response: dict[str, Any]) -> bytes: - """Step 6 — JSON-RPC response serialization.""" - return json.dumps(jsonrpc_response).encode("utf-8") diff --git a/nitrostack/transports/http.py b/nitrostack/transports/http.py index a343747..86f7546 100644 --- a/nitrostack/transports/http.py +++ b/nitrostack/transports/http.py @@ -311,7 +311,8 @@ class HeaderCompatMiddleware: version checks see what the client sent. Stack order on the HTTP app: CORS → this middleware (preserve) → handler. - Sidecar version checks run on the combined app outside this mount. + This middleware only normalizes transport headers; JSON-RPC dispatch remains + owned by the official MCP Streamable HTTP manager. """ def __init__(self, app: ASGIApp, *, drop_session_headers: bool = False) -> None: diff --git a/nitrostack/transports/middleware.py b/nitrostack/transports/middleware.py deleted file mode 100644 index 314f097..0000000 --- a/nitrostack/transports/middleware.py +++ /dev/null @@ -1,524 +0,0 @@ -"""Stateless HTTP ASGI middleware.""" - -from __future__ import annotations - -from typing import Any, Callable, Optional - -from nitrostack.protocol.errors import JsonRpcErrorCode -from nitrostack.protocol.jsonrpc import jsonrpc_error, jsonrpc_method_from_body -from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION, ProtocolEra, WireMode -from nitrostack.runtime.stateless import assert_stateless_headers -from nitrostack.transports.cors import build_cors_headers, cors_preflight_response_headers -from nitrostack.transports.dispatch import ( - DiscoverHandler, - IngressContext, - InitializeHandler, - StatelessIngressPipeline, -) -from nitrostack.transports.headers import ( - MCP_HTTP_PATH, - build_mcp_echo_headers, - decode_asgi_headers, - get_header, - scope_with_header_snapshot, - scope_without_session_headers, - snapshot_validated_asgi_headers, - strip_legacy_session_headers, -) - -ASGIApp = Callable[..., Any] - -MCP_POST_PATHS = (MCP_HTTP_PATH, f"{MCP_HTTP_PATH}/") - - -class StatelessTransportMiddleware: - """ - ASGI wrapper implementing stateless HTTP transport invariants: - - OPTIONS 204 CORS preflight on MCP paths only - - Legacy session header stripping - - MCP response headers on all responses - - Pre-dispatch for POST /mcp (ping, server/discover) - """ - - def __init__( - self, - app: ASGIApp, - *, - pipeline: Optional[StatelessIngressPipeline] = None, - mcp_paths: tuple[str, ...] = MCP_POST_PATHS, - enable_cors: bool = True, - ) -> None: - self.app = app - self.pipeline = pipeline - self.mcp_paths = mcp_paths - self.enable_cors = enable_cors - - async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None: - if scope.get("type") != "http": - await self.app(scope, receive, send) - return - - method = scope.get("method", "GET").upper() - path = scope.get("path", "") - - if method == "OPTIONS" and path in self.mcp_paths and self.enable_cors: - await self._send_options(scope, receive, send) - return - - buffered_body: Optional[bytes] = None - header_snapshot: Optional[tuple[tuple[bytes, bytes], ...]] = None - if method == "POST" and path in self.mcp_paths and self.pipeline is not None: - scope = self._strip_sessionless_scope(scope) - buffered_body = await self._read_body(receive) - handled = await self._try_pre_dispatch(scope, buffered_body, send) - if handled: - return - live_headers = decode_asgi_headers(list(scope.get("headers") or [])) - rejected = self._reject_replay_headers(buffered_body, live_headers) - if rejected is not None: - await self._send_pipeline_response( - scope, send, live_headers, rejected, body=buffered_body - ) - return - header_snapshot = snapshot_validated_asgi_headers(list(scope.get("headers") or [])) - snapshot_headers = decode_asgi_headers(list(header_snapshot)) - rejected = self._reject_replay_headers(buffered_body, snapshot_headers) - if rejected is not None: - await self._send_pipeline_response( - scope, send, snapshot_headers, rejected, body=buffered_body - ) - return - receive = self._replay_receive(buffered_body, receive) - scope = scope_with_header_snapshot(scope, header_snapshot) - - if path in self.mcp_paths and self.pipeline is not None: - scope = self._strip_sessionless_scope(scope) - raw_headers = decode_asgi_headers(list(scope.get("headers") or [])) - if method == "GET": - rejected = self.pipeline.reject_method_policy(b"", raw_headers) - if rejected is not None: - await self._send_pipeline_response( - scope, send, raw_headers, rejected, body=b"" - ) - return - - await self._forward_with_stateless_headers( - scope, receive, send, body=buffered_body - ) - - def _reject_replay_headers( - self, - raw_body: bytes, - request_headers: dict[str, str], - ) -> Optional[tuple[int, dict[str, Any]]]: - """Re-apply method policy, ``-32020``, and ``-32022`` on replay.""" - assert self.pipeline is not None - policy_rejected = self.pipeline.reject_method_policy(raw_body, request_headers) - if policy_rejected is not None: - return policy_rejected - method_rejected = self.pipeline.reject_jsonrpc_mcp_method(raw_body, request_headers) - if method_rejected is not None: - return method_rejected - name_rejected = self.pipeline.reject_tools_call_mcp_name(raw_body, request_headers) - if name_rejected is not None: - return name_rejected - version_rejected = self.pipeline.reject_protocol_version_cross_check( - raw_body, request_headers - ) - if version_rejected is not None: - return version_rejected - return self.pipeline.reject_unsupported_protocol_version_header( - raw_body, request_headers - ) - - async def _send_options(self, scope: dict[str, Any], receive: Any, send: Any) -> None: - headers_list = scope.get("headers") or [] - req_headers = { - k.decode("latin-1"): v.decode("latin-1") for k, v in headers_list - } - cors = cors_preflight_response_headers(req_headers) - response_headers = self._echo_headers(req_headers, extra=cors) - assert_stateless_headers(response_headers) - - await send( - { - "type": "http.response.start", - "status": 204, - "headers": self._encode_headers(response_headers), - } - ) - await send({"type": "http.response.body", "body": b""}) - - async def _try_pre_dispatch( - self, - scope: dict[str, Any], - body: bytes, - send: Any, - ) -> bool: - headers_list = scope.get("headers") or [] - raw_headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in headers_list} - - assert self.pipeline is not None - result = await self.pipeline.handle_post(body, raw_headers) - if result is None: - return False - - await self._send_pipeline_response(scope, send, raw_headers, result, body=body) - return True - - async def _send_pipeline_response( - self, - scope: dict[str, Any], - send: Any, - raw_headers: dict[str, str], - result: tuple[int, dict[str, Any]], - *, - body: Optional[bytes] = None, - ) -> None: - status, jsonrpc_response = result - origin = get_header(raw_headers, "Origin") - cors = build_cors_headers(origin=origin) - response_headers = self._echo_headers(raw_headers, extra=cors, body=body) - assert_stateless_headers(response_headers) - assert self.pipeline is not None - if status == 202 and jsonrpc_response == {}: - payload = b"" - else: - payload = self.pipeline.serialize_response(jsonrpc_response) - await send( - { - "type": "http.response.start", - "status": status, - "headers": self._encode_headers(response_headers), - } - ) - await send({"type": "http.response.body", "body": payload}) - - async def _send_session_id_rejected( - self, - scope: dict[str, Any], - send: Any, - raw_headers: dict[str, str], - ) -> None: - origin = get_header(raw_headers, "Origin") - cors = build_cors_headers(origin=origin) - response_headers = self._echo_headers(raw_headers, extra=cors) - assert_stateless_headers(response_headers) - payload = StatelessIngressPipeline.serialize_response( - jsonrpc_error( - None, - int(JsonRpcErrorCode.INVALID_REQUEST), - "Invalid Request: Mcp-Session-Id is not supported", - ) - ) - await send( - { - "type": "http.response.start", - "status": 400, - "headers": self._encode_headers(response_headers), - } - ) - await send({"type": "http.response.body", "body": payload}) - - async def _forward_with_stateless_headers( - self, - scope: dict[str, Any], - receive: Any, - send: Any, - *, - body: Optional[bytes] = None, - ) -> None: - async def send_wrapper(message: dict[str, Any]) -> None: - if message["type"] == "http.response.start": - raw_headers = { - k.decode("latin-1"): v.decode("latin-1") - for k, v in message.get("headers", []) - } - req_headers = { - k.decode("latin-1"): v.decode("latin-1") - for k, v in (scope.get("headers") or []) - } - inner_headers = { - k: v - for k, v in strip_legacy_session_headers(raw_headers).items() - if k.lower() != "content-type" - } - merged = self._echo_headers( - req_headers, - content_type=raw_headers.get("content-type", "application/json"), - extra={ - **inner_headers, - **build_cors_headers(origin=get_header(req_headers, "Origin")), - }, - body=body, - ) - assert_stateless_headers(merged) - message = { - **message, - "headers": self._encode_headers(merged), - } - await send(message) - - await self.app( - scope_with_header_snapshot( - scope, - snapshot_validated_asgi_headers(list(scope.get("headers") or [])), - ), - receive, - send_wrapper, - ) - - def _strip_sessionless_scope(self, scope: dict[str, Any]) -> dict[str, Any]: - if self.pipeline is None: - return scope - from nitrostack.runtime.stateless import sessionless_strips_incoming_session_id - - if sessionless_strips_incoming_session_id(self.pipeline._context.wire_mode): - return scope_without_session_headers(scope) - return scope - - def _echo_headers( - self, - request_headers: dict[str, str], - *, - extra: Optional[dict[str, str]] = None, - content_type: str = "application/json", - body: Optional[bytes] = None, - ) -> dict[str, str]: - fallback = MODERN_PROTOCOL_VERSION - supported = None - if self.pipeline is not None: - fallback = self.pipeline.response_protocol_version() - supported = self.pipeline.response_supported_versions() - return build_mcp_echo_headers( - request_headers, - protocol_version=fallback, - method=jsonrpc_method_from_body(body), - supported_versions=supported, - content_type=content_type, - extra=extra, - ) - - @staticmethod - async def _read_body(receive: Any) -> bytes: - body = b"" - while True: - message = await receive() - if message["type"] == "http.request": - body += message.get("body", b"") - if not message.get("more_body", False): - break - return body - - @staticmethod - def _replay_receive(body: bytes, original_receive: Any) -> Any: - sent = False - - async def replay() -> dict[str, Any]: - nonlocal sent - if not sent: - sent = True - return {"type": "http.request", "body": body, "more_body": False} - # Body was already buffered. Wait for a real client disconnect - # instead of synthesizing one — Streamable HTTP treats disconnect - # as an abort of the in-flight request. - while True: - message = await original_receive() - if message.get("type") == "http.disconnect": - return message - - return replay - - @staticmethod - def _encode_headers(headers: dict[str, str]) -> list[tuple[bytes, bytes]]: - return [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()] - - -class SessionlessHttpGuard: - """ - Transport invariants official mcp 2.x does not own on sessionless ``/mcp``. - - Does not parse or answer ``tools/call``. Forwards those to the v2 app. - """ - - def __init__( - self, - app: ASGIApp, - *, - protocol_era: ProtocolEra = "auto", - enable_cors: bool = True, - discover_handler: Optional[DiscoverHandler] = None, - ) -> None: - self.app = app - self.protocol_era = protocol_era - self.enable_cors = enable_cors - self.discover_handler = discover_handler - wire_mode: WireMode = "reject" if protocol_era == "modern" else "stateless" - self._sender = StatelessTransportMiddleware( - app, - pipeline=StatelessIngressPipeline( - IngressContext( - server_name="", - server_version="", - protocol_version=MODERN_PROTOCOL_VERSION, - wire_mode=wire_mode, - protocol_era=protocol_era, - ), - discover_handler=discover_handler, - ), - enable_cors=enable_cors, - ) - - async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None: - if scope.get("type") != "http": - await self.app(scope, receive, send) - return - method = scope.get("method", "").upper() - path = scope.get("path", "") - if method == "OPTIONS" and path in MCP_POST_PATHS and self.enable_cors: - await self._sender._send_options(scope, receive, send) - return - scope = scope_without_session_headers(scope) - raw_headers = decode_asgi_headers(list(scope.get("headers") or [])) - from nitrostack.transports.dispatch import ( - is_header_only_ping, - reject_modern_method_policy, - ) - from nitrostack.transports.headers import HEADER_MCP_METHOD, get_header - if path in MCP_POST_PATHS and method == "GET": - header_method = get_header(raw_headers, HEADER_MCP_METHOD) - if header_method is not None: - rejected = reject_modern_method_policy( - header_method.strip(), None, self.protocol_era - ) - if rejected is not None: - await self._sender._send_pipeline_response( - scope, send, raw_headers, rejected, body=b"" - ) - return - if method != "POST" or path not in MCP_POST_PATHS: - await self.app(scope, receive, send) - return - - body = await StatelessTransportMiddleware._read_body(receive) - if is_header_only_ping(body, raw_headers): - from nitrostack.protocol.jsonrpc import build_ping_response - - await self._sender._send_pipeline_response( - scope, send, raw_headers, (200, build_ping_response(None)), body=body - ) - return - - from nitrostack.protocol.jsonrpc import ( - JsonRpcParseError, - JsonRpcWireError, - parse_jsonrpc_request, - validate_header_body_method, - ) - try: - request = parse_jsonrpc_request(body) - except (JsonRpcParseError, JsonRpcWireError): - await self.app( - scope, - StatelessTransportMiddleware._replay_receive(body, receive), - send, - ) - return - - rejected = reject_modern_method_policy( - request.method, request.id, self.protocol_era - ) - if rejected is not None: - await self._sender._send_pipeline_response( - scope, send, raw_headers, rejected, body=body - ) - return - - header_method = get_header(raw_headers, HEADER_MCP_METHOD) - if header_method is not None: - try: - validate_header_body_method(header_method, request.method) - except Exception as exc: - from nitrostack.protocol.jsonrpc import map_exception_to_jsonrpc - - await self._sender._send_pipeline_response( - scope, - send, - raw_headers, - (400, map_exception_to_jsonrpc(exc, request.id)), - body=body, - ) - return - - if request.method == "server/discover" and self.discover_handler is not None: - from nitrostack.protocol.jsonrpc import jsonrpc_success - - await self._sender._send_pipeline_response( - scope, - send, - raw_headers, - (200, jsonrpc_success(request.id, self.discover_handler())), - body=body, - ) - return - - await self._sender._forward_with_stateless_headers( - scope, - StatelessTransportMiddleware._replay_receive(body, receive), - send, - body=body, - ) - - -def wrap_sessionless_http( - app: ASGIApp, - *, - protocol_era: ProtocolEra = "auto", - enable_cors: bool = True, - discover_handler: Optional[DiscoverHandler] = None, -) -> ASGIApp: - """Sessionless transport guard; official mcp 2.x still owns ``tools/call``.""" - return SessionlessHttpGuard( - app, - protocol_era=protocol_era, - enable_cors=enable_cors, - discover_handler=discover_handler, - ) - - -def wrap_modern_handshake_reject(app: ASGIApp, *, enable_cors: bool = True) -> ASGIApp: - """Reject 2025 ``initialize`` on era ``modern``; leave the v2 app otherwise.""" - return wrap_sessionless_http(app, protocol_era="modern", enable_cors=enable_cors) - - -def wrap_stateless_transport( - app: ASGIApp, - *, - server_name: str, - server_version: str, - protocol_version: str, - advertise_tasks: bool = True, - advertise_app: bool = False, - custom_extensions: Optional[dict[str, str]] = None, - wire_mode: WireMode = "stateless", - protocol_era: Optional[ProtocolEra] = None, - enable_cors: bool = True, - discover_handler: Optional[DiscoverHandler] = None, - initialize_handler: Optional[InitializeHandler] = None, -) -> ASGIApp: - """Wrap an ASGI app with stateless HTTP middleware.""" - pipeline = StatelessIngressPipeline( - IngressContext( - server_name=server_name, - server_version=server_version, - protocol_version=protocol_version, - advertise_tasks=advertise_tasks, - advertise_app=advertise_app, - custom_extensions=custom_extensions, - wire_mode=wire_mode, - protocol_era=protocol_era, - ), - discover_handler=discover_handler, - initialize_handler=initialize_handler, - ) - return StatelessTransportMiddleware(app, pipeline=pipeline, enable_cors=enable_cors) diff --git a/tests/test_mcp22_official_http_owner.py b/tests/test_mcp22_official_http_owner.py new file mode 100644 index 0000000..7d33053 --- /dev/null +++ b/tests/test_mcp22_official_http_owner.py @@ -0,0 +1,98 @@ +"""Regression tests for Issue #22: one official owner for ``/mcp``.""" + +import asyncio +import json +from pathlib import Path + +import httpx + +from nitrostack import module +from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app + + +@module(name="issue22_probe", controllers=[]) +class Issue22ProbeModule: + pass + + +@mcp_app( + module=Issue22ProbeModule, + server=ServerConfig(name="issue22-probe", protocol_era="auto"), +) +class Issue22ProbeApp: + pass + + +def _request(path: str, *, method: str = "GET", payload: dict | None = None): + async def run(): + application = await McpApplicationFactory.create(Issue22ProbeApp) + http_app = application.get_combined_app(json_response=True) + transport = httpx.ASGITransport(app=http_app) + async with http_app.router.lifespan_context(http_app): + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + return await client.request( + method, + path, + headers={ + "content-type": "application/json", + "accept": "application/json, text/event-stream", + }, + content=json.dumps(payload) if payload is not None else None, + ) + + return asyncio.run(run()) + + +def test_combined_app_has_no_jsonrpc_sidecar_call(): + source = Path("nitrostack/core/app.py").read_text(encoding="utf-8") + assert "wrap_stateless_transport" not in source + assert "return http_app" in source + + +def test_sidecar_modules_and_ping_helpers_are_not_production_code(): + assert not Path("nitrostack/transports/middleware.py").exists() + assert not Path("nitrostack/transports/dispatch.py").exists() + production = "\n".join( + path.read_text(encoding="utf-8") + for path in Path("nitrostack").rglob("*.py") + ) + for symbol in ( + "wrap_stateless_transport", + "wrap_sessionless_http", + "wrap_modern_handshake_reject", + "StatelessIngressPipeline", + "build_ping_response", + "is_header_only_ping", + ): + assert symbol not in production + + +def test_health_endpoint_remains_available(): + response = _request("/mcp/health") + assert response.status_code == 200 + assert response.json()["status"] == "ok" + + +def test_official_mcp_handles_ping_without_a_default_session_id(): + response = _request( + "/mcp", + method="POST", + payload={"jsonrpc": "2.0", "id": 1, "method": "ping"}, + ) + assert response.status_code == 200 + assert response.headers.get("mcp-session-id") is None + assert response.json() == {"jsonrpc": "2.0", "id": 1, "result": {}} + + +def test_official_mcp_returns_jsonrpc_error_for_unknown_method(): + response = _request( + "/mcp", + method="POST", + payload={"jsonrpc": "2.0", "id": 2, "method": "issue22/unknown"}, + ) + assert response.status_code == 200 + body = response.json() + assert body["jsonrpc"] == "2.0" + assert body["id"] == 2 + assert body["error"]["code"] == -32601 + assert "Method not found" in body["error"]["message"] From 94b2876e499aa0cd16fcf7f39510bf6a6f8f4c0a Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Tue, 15 Sep 2026 12:58:32 +0530 Subject: [PATCH 002/146] fix: hide incomplete tasks surface on MCP 2026 --- nitrostack/core/app.py | 25 ++-- nitrostack/core/context.py | 5 +- nitrostack/protocol/method_contract.py | 12 +- nitrostack/runtime/acceptance.py | 4 +- nitrostack/runtime/conformance.py | 2 +- nitrostack/runtime/stateless.py | 3 +- nitrostack/tasks/notify.py | 194 ------------------------- nitrostack/testing/__init__.py | 12 +- tests/test_mcp20_task_authorization.py | 5 +- tests/test_mcp20_tasks.py | 25 +++- tests/test_mcp25_hide_tasks.py | 173 ++++++++++++++++++++++ tests/test_tasks.py | 2 +- 12 files changed, 231 insertions(+), 231 deletions(-) delete mode 100644 nitrostack/tasks/notify.py create mode 100644 tests/test_mcp25_hide_tasks.py diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index 581ab88..481ab6b 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -75,7 +75,7 @@ strip_tool_arguments, ) from nitrostack.protocol.observability import TraceContext, extract_trace_context -from nitrostack.runtime.correlation import InFlightRegistry, new_correlation_id +from nitrostack.runtime.correlation import new_correlation_id from nitrostack.transports.headers import ( extract_mcp_param_headers, extract_mcp_scope_headers, @@ -541,7 +541,6 @@ def __init__(self, app_class: Type): self._prompts: Dict[str, _PromptEntry] = {} self._initial_tools: List[Tuple[Any, Callable, ToolConfig]] = [] self.task_manager = TaskManager() - self._in_flight = InFlightRegistry() self._bootstrap() @@ -766,6 +765,11 @@ async def health_status_resource(context: ExecutionContext) -> str: # ------------------------------------------------------------------ def _advertise_tasks_extension(self) -> bool: + # Tasks remain available to in-process callers and the legacy wire only. + # MCP 2026 has no complete tasks surface (notably tasks/update), so + # advertising this partial implementation would make discovery lie. + if self.protocol_era in ("auto", "modern"): + return False return any( entry.config.task_support in ("optional", "required") for entry in self._tools.values() @@ -1275,6 +1279,11 @@ async def _call_tool(self, name: str, arguments: Dict[str, Any], task: Any = Non trace = _trace_context_from_request_ctx(rc) is_task = task_metadata is not None + if self.protocol_era in ("auto", "modern") and is_task: + raise MCPError( + types.INVALID_PARAMS, + "Server does not support task augmentation on the MCP 2026 wire", + ) if cfg.task_support == "forbidden" and task_metadata is not None: raise MCPError( types.METHOD_NOT_FOUND, @@ -1369,7 +1378,6 @@ async def background_execution(): trace=trace, ) _apply_request_envelope(ctx, rc) - ticket = self._in_flight.register(correlation_id, jsonrpc_id=jsonrpc_id) try: result = await run_pipeline( handler=entry.method, @@ -1391,13 +1399,6 @@ async def background_execution(): content=[types.TextContent(type="text", text=str(exc))], isError=True, ) - finally: - self._in_flight.discard(correlation_id) - if ticket.cancel_requested.is_set(): - return types.CallToolResult( - content=[types.TextContent(type="text", text="Request was cancelled.")], - isError=True, - ) return self._to_call_tool_result(result, entry.component, ctx) async def _read_resource(self, uri: str) -> List[ReadResourceContents]: @@ -1546,6 +1547,10 @@ def _build_get_task_result(self, task) -> types.GetTaskResult: return GetTaskResult(**payload) def _register_task_handlers(self, server: NitroStackMcpServer) -> None: + if self.protocol_era in ("auto", "modern"): + server.has_task_support = False + return + async def handle_list_tasks(req): if rejects_deprecated_method("tasks/list", self.protocol_era): message = deprecated_method_message("tasks/list") diff --git a/nitrostack/core/context.py b/nitrostack/core/context.py index 42cf129..440e2ad 100644 --- a/nitrostack/core/context.py +++ b/nitrostack/core/context.py @@ -107,8 +107,9 @@ class TaskContext: whichever transport (STDIO or Streamable HTTP) initiated the task — transport-agnostic since both use the same ``mcp.server.session.ServerSession``. The client only receives these if it supplied a ``progressToken`` in the - original ``tools/call`` request's ``_meta``; ``TaskManager``-backed polling via - ``tasks/get`` always works regardless, so this is additive, not required. + original ``tools/call`` request's ``_meta``. TaskManager-backed polling is + retained for in-process callers and the legacy wire; the incomplete Tasks + surface is deliberately not advertised on MCP 2026. """ def __init__( diff --git a/nitrostack/protocol/method_contract.py b/nitrostack/protocol/method_contract.py index b9142ab..2c3403d 100644 --- a/nitrostack/protocol/method_contract.py +++ b/nitrostack/protocol/method_contract.py @@ -1,8 +1,8 @@ """SEP-2243 method contracts for the 2026 method surface. -Official v2 owns this table once mounted. Until then the sidecar validator -reads one row per method: required ``Mcp-Method``, optional ``Mcp-Name`` field, -and whether ``auto`` requires the method header. +The official MCP SDK owns request dispatch. This table records the method/header +contract used by the 2026 protocol checks: required ``Mcp-Method``, optional +``Mcp-Name`` field, and whether ``auto`` requires the method header. """ from __future__ import annotations @@ -63,10 +63,6 @@ def _contract( _contract("prompts/get", name_field=NAME_FIELD_NAME), _contract("notifications/prompts/list_changed"), _contract("completion/complete"), - _contract("tasks/get"), - _contract("tasks/cancel"), - _contract("tasks/result"), - _contract("tasks/list"), _contract("logging/setLevel"), ) @@ -82,8 +78,6 @@ def _contract( # (``initialize``, ``notifications/initialized``) are not in this table: # ``modern`` rejects them as method-not-found; ``auto`` still answers them. DEPRECATED_MODERN_METHODS: dict[str, str] = { - "tasks/result": "Method 'tasks/result' is not supported in MCP 2026-07-28; use 'tasks/get'.", - "tasks/list": "Method 'tasks/list' is not supported in modern stateless MCP 2026-07-28.", "resources/subscribe": ( "Method 'resources/subscribe' is not supported in stateless MCP 2026-07-28; " "use SSE subscriptions/listen." diff --git a/nitrostack/runtime/acceptance.py b/nitrostack/runtime/acceptance.py index 17992ed..7183445 100644 --- a/nitrostack/runtime/acceptance.py +++ b/nitrostack/runtime/acceptance.py @@ -103,7 +103,7 @@ class AcceptanceCriterion: ), ProtocolDeliverable( ProtocolArea.ASYNC_TASKS, - "Task state machine and tasks/get embedded result", + "Legacy/in-process Task state machine and embedded result", "tests/test_mcp20_tasks.py", ), ProtocolDeliverable( @@ -146,7 +146,7 @@ class AcceptanceCriterion: ), AcceptanceCriterion( "task_cancellation", - "tasks/cancel marks cancelled; terminal cancel returns -32602", + "Legacy tasks/cancel marks cancelled; terminal cancel returns -32602", "tests/test_mcp20_tasks.py", ), AcceptanceCriterion( diff --git a/nitrostack/runtime/conformance.py b/nitrostack/runtime/conformance.py index dc352b0..177c169 100644 --- a/nitrostack/runtime/conformance.py +++ b/nitrostack/runtime/conformance.py @@ -32,7 +32,7 @@ class ConformanceArea(str, Enum): "Standard JSON-RPC error codes; deprecated methods rejected on modern wire" ), ConformanceArea.TASKS: ( - "Task-augmented tools/call, tasks/get lifecycle, cancel, terminal-only TTL eviction" + "MCP 2026 hides the incomplete Tasks surface; legacy/in-process task lifecycle remains" ), ConformanceArea.MULTI_TENANT: ( "Cross-tenant task access raises TaskNotFoundError without enumeration" diff --git a/nitrostack/runtime/stateless.py b/nitrostack/runtime/stateless.py index cb849db..778b90d 100644 --- a/nitrostack/runtime/stateless.py +++ b/nitrostack/runtime/stateless.py @@ -47,7 +47,8 @@ def request_protocol_version( The header wins when present. Otherwise ``_meta.mcp.protocolVersion`` is used. When neither is present the request proceeds (legacy default). The - header is not required on ``modern`` in this sidecar. + header is not required on ``modern`` because the official SDK owns the + HTTP request lifecycle. """ for raw in (header_version, envelope_version): if isinstance(raw, str) and raw.strip(): diff --git a/nitrostack/tasks/notify.py b/nitrostack/tasks/notify.py deleted file mode 100644 index fc81677..0000000 --- a/nitrostack/tasks/notify.py +++ /dev/null @@ -1,194 +0,0 @@ -"""Fan-out for ``notifications/tasks/status`` across live transports.""" - -from __future__ import annotations - -import logging -from typing import Any, Callable, Optional, Protocol - -from nitrostack.tasks.authorization import entry_matches_access_context -from nitrostack.tasks.types import TaskAccessContext, TaskEntry - -logger = logging.getLogger(__name__) - -TASK_STATUS_METHOD = "notifications/tasks/status" - - -def build_task_status_notification( - task_id: str, - status: str, - *, - status_message: Optional[str] = None, -) -> dict[str, Any]: - """Wire notification for a task status or progress change.""" - params: dict[str, Any] = {"taskId": task_id, "status": status} - if status_message is not None: - params["statusMessage"] = status_message - return {"method": TASK_STATUS_METHOD, "params": params} - - -class TaskStatusSink(Protocol): - """One connected transport that can receive task status.""" - - access: Optional[TaskAccessContext] - session_id: Optional[str] - task_id: Optional[str] - - async def send(self, notification: dict[str, Any]) -> None: - """Deliver one status notification. Must not raise to the router.""" - ... - - -class CallbackTaskSink: - """Test and in-process sink that records or forwards notifications.""" - - def __init__( - self, - callback: Callable[[dict[str, Any]], Any], - *, - access: Optional[TaskAccessContext] = None, - session_id: Optional[str] = None, - task_id: Optional[str] = None, - ) -> None: - self._callback = callback - self.access = access - self.session_id = session_id - self.task_id = task_id - - async def send(self, notification: dict[str, Any]) -> None: - result = self._callback(notification) - if hasattr(result, "__await__"): - await result - - -class QueueTaskSink: - """Push notifications onto an asyncio queue (listen / SSE attach).""" - - def __init__( - self, - put: Callable[[dict[str, Any]], None], - *, - access: Optional[TaskAccessContext] = None, - session_id: Optional[str] = None, - task_id: Optional[str] = None, - ) -> None: - self._put = put - self.access = access - self.session_id = session_id - self.task_id = task_id - - async def send(self, notification: dict[str, Any]) -> None: - self._put(notification) - - -class StreamTaskSink: - """Write a JSON-RPC notification onto an official stream write side.""" - - def __init__( - self, - write_stream: Any, - *, - access: Optional[TaskAccessContext] = None, - session_id: Optional[str] = None, - task_id: Optional[str] = None, - ) -> None: - self._write_stream = write_stream - self.access = access - self.session_id = session_id - self.task_id = task_id - - async def send(self, notification: dict[str, Any]) -> None: - from mcp.shared.message import SessionMessage - from mcp_types import jsonrpc_message_adapter - - message = jsonrpc_message_adapter.validate_python( - { - "jsonrpc": "2.0", - "method": notification["method"], - "params": notification.get("params") or {}, - } - ) - await self._write_stream.send(SessionMessage(message)) - - -class SessionTaskSink: - """Notify the originating MCP session (stdio or legacy SSE).""" - - def __init__( - self, - session: Any, - *, - access: Optional[TaskAccessContext] = None, - session_id: Optional[str] = None, - task_id: Optional[str] = None, - ) -> None: - self._session = session - self.access = access - self.session_id = session_id - self.task_id = task_id - - async def send(self, notification: dict[str, Any]) -> None: - session = self._session - if session is None: - return - method = notification["method"] - params = notification.get("params") or {} - sender = getattr(session, "send_notification", None) - if sender is not None: - await sender(method, params) - return - outbound = getattr(session, "outbound", None) - notify = getattr(outbound, "notify", None) if outbound is not None else None - if notify is not None: - await notify(method, params) - - -def _sink_accepts(sink: TaskStatusSink, entry: TaskEntry) -> bool: - task_id = getattr(sink, "task_id", None) - if task_id is not None and task_id != entry.task_id: - return False - session_id = getattr(sink, "session_id", None) - if session_id is not None and entry.session_id and session_id != entry.session_id: - return False - access = getattr(sink, "access", None) - if access is not None and not entry_matches_access_context(entry, access): - return False - return True - - -class TaskStatusRouter: - """Deliver task status to every live channel. A failed send is ignored.""" - - def __init__(self) -> None: - self._sinks: dict[object, TaskStatusSink] = {} - - def register(self, sink: TaskStatusSink) -> Callable[[], None]: - token = object() - self._sinks[token] = sink - - def unsubscribe() -> None: - self._sinks.pop(token, None) - - return unsubscribe - - async def notify_task_status( - self, - entry: TaskEntry, - *, - status: Optional[str] = None, - status_message: Optional[str] = None, - ) -> None: - """Fan out one status change. Never raises to the task lifecycle.""" - notification = build_task_status_notification( - entry.task_id, - status if status is not None else entry.status, - status_message=status_message - if status_message is not None - else entry.data.status_message, - ) - for sink in list(self._sinks.values()): - if not _sink_accepts(sink, entry): - continue - try: - await sink.send(notification) - except Exception: - logger.exception("task status notify failed; continuing") diff --git a/nitrostack/testing/__init__.py b/nitrostack/testing/__init__.py index 0db12b6..d10766d 100644 --- a/nitrostack/testing/__init__.py +++ b/nitrostack/testing/__init__.py @@ -15,9 +15,17 @@ class NitroTestingModule: `request_handlers` (the same dict the real stdio/HTTP transports use). """ @classmethod - async def create(cls, app_module: Type) -> "NitroTestingModule": + async def create( + cls, + app_module: Type, + *, + protocol_era: str = "auto", + ) -> "NitroTestingModule": # Construct a dummy App class decorated with @mcp_app - @mcp_app(module=app_module, server=ServerConfig(name="test-server")) + @mcp_app( + module=app_module, + server=ServerConfig(name="test-server", protocol_era=protocol_era), + ) class TestApp: pass diff --git a/tests/test_mcp20_task_authorization.py b/tests/test_mcp20_task_authorization.py index 3c6eb35..67e9617 100644 --- a/tests/test_mcp20_task_authorization.py +++ b/tests/test_mcp20_task_authorization.py @@ -167,7 +167,10 @@ async def owner_tool(self, input: EchoInput, context: ExecutionContext) -> str: class AuthModule: pass - @mcp_app(module=AuthModule, server=ServerConfig(name="task-auth")) + @mcp_app( + module=AuthModule, + server=ServerConfig(name="task-auth", protocol_era="legacy"), + ) class AuthApp: pass diff --git a/tests/test_mcp20_tasks.py b/tests/test_mcp20_tasks.py index da6bf1d..2e611c5 100644 --- a/tests/test_mcp20_tasks.py +++ b/tests/test_mcp20_tasks.py @@ -96,7 +96,10 @@ async def sync_only(self, input: EchoInput, context: ExecutionContext) -> str: class ForbiddenModule: pass - @mcp_app(module=ForbiddenModule, server=ServerConfig(name="tasks-forbidden")) + @mcp_app( + module=ForbiddenModule, + server=ServerConfig(name="tasks-forbidden", protocol_era="legacy"), + ) class ForbiddenApp: pass @@ -164,7 +167,10 @@ async def noop(self, input: EchoInput, context: ExecutionContext) -> str: class GetModule: pass - @mcp_app(module=GetModule, server=ServerConfig(name="tasks-get")) + @mcp_app( + module=GetModule, + server=ServerConfig(name="tasks-get", protocol_era="legacy"), + ) class GetApp: pass @@ -203,10 +209,7 @@ class ListApp: async def _run(): app = await McpApplicationFactory.create(ListApp) - handler = app.mcp_server.request_handlers[types.ListTasksRequest] - with pytest.raises(McpError) as exc: - await handler(types.ListTasksRequest(method="tasks/list", params={})) - assert exc.value.error.code == types.METHOD_NOT_FOUND + assert types.ListTasksRequest not in app.mcp_server.request_handlers asyncio.run(_run()) @@ -226,7 +229,10 @@ async def noop3(self, input: EchoInput, context: ExecutionContext) -> str: class CancelModule: pass - @mcp_app(module=CancelModule, server=ServerConfig(name="tasks-cancel")) + @mcp_app( + module=CancelModule, + server=ServerConfig(name="tasks-cancel", protocol_era="legacy"), + ) class CancelApp: pass @@ -256,7 +262,10 @@ async def slow_echo(self, input: EchoInput, context: ExecutionContext) -> str: class CreateModule: pass - @mcp_app(module=CreateModule, server=ServerConfig(name="tasks-create")) + @mcp_app( + module=CreateModule, + server=ServerConfig(name="tasks-create", protocol_era="legacy"), + ) class CreateApp: pass diff --git a/tests/test_mcp25_hide_tasks.py b/tests/test_mcp25_hide_tasks.py new file mode 100644 index 0000000..72a9a33 --- /dev/null +++ b/tests/test_mcp25_hide_tasks.py @@ -0,0 +1,173 @@ +"""Issue #25: the partial Tasks surface is hidden on the 2026 wire.""" + +import asyncio +import json + +import httpx +import mcp.types as types +import pytest +from mcp import MCPError +from pydantic import BaseModel + +from nitrostack import ExecutionContext, injectable, module, tool +from nitrostack.core.app import McpApplicationFactory, ServerConfig, mcp_app +from nitrostack.core.di import DIContainer +from nitrostack.core.errors import TaskNotFoundError + + +class TaskInput(BaseModel): + value: str = "" + + +@injectable() +class HideTasksController: + @tool( + name="taskable", + description="taskable", + input_schema=TaskInput, + task_support="optional", + ) + async def taskable(self, input: TaskInput, context: ExecutionContext) -> str: + return "ok" + + +@module(name="hide_tasks", controllers=[HideTasksController]) +class HideTasksModule: + pass + + +def _app(era: str): + @mcp_app(module=HideTasksModule, server=ServerConfig(name="hide-tasks", protocol_era=era)) + class App: + pass + + return asyncio.run(McpApplicationFactory.create(App)) + + +def setup_function() -> None: + DIContainer.reset() + + +def teardown_function() -> None: + DIContainer.reset() + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_capabilities_and_handlers_hide_tasks(era): + app = _app(era) + server = app.mcp_server + assert server is not None + assert server.has_task_support is False + assert server.get_capabilities(protocol_version="2026-07-28").tasks is None + assert types.GetTaskRequest not in server.request_handlers + assert types.CancelTaskRequest not in server.request_handlers + assert types.GetTaskPayloadRequest not in server.request_handlers + + +def test_legacy_keeps_the_existing_in_process_task_handlers(): + app = _app("legacy") + server = app.mcp_server + assert server is not None + assert server.has_task_support is True + assert types.GetTaskRequest in server.request_handlers + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_task_augmented_tool_call_is_rejected_without_creating_a_task(era): + app = _app(era) + + async def run(): + with pytest.raises(MCPError) as exc_info: + await app._call_tool( + "taskable", + {}, + task=types.TaskMetadata(ttl=60_000), + ) + assert getattr(exc_info.value, "error", None).code == types.INVALID_PARAMS + with pytest.raises(TaskNotFoundError): + await app.task_manager.get_task("task_does_not_exist") + + asyncio.run(run()) + + +def _http_request(app, payload: dict, *, extra_headers: dict[str, str] | None = None): + async def run(): + http_app = app.get_combined_app(json_response=True) + transport = httpx.ASGITransport(app=http_app) + async with http_app.router.lifespan_context(http_app): + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + headers = { + "content-type": "application/json", + "accept": "application/json, text/event-stream", + } + headers.update(extra_headers or {}) + return await client.post( + "/mcp", + headers=headers, + content=json.dumps(payload), + ) + + return asyncio.run(run()) + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_discover_does_not_advertise_tasks(era): + response = _http_request( + _app(era), + { + "jsonrpc": "2.0", + "id": 1, + "method": "server/discover", + "params": { + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + } + }, +}, + extra_headers={ + "Mcp-Method": "server/discover", + "MCP-Protocol-Version": "2026-07-28", + }, + ) + assert response.status_code == 200 + body = response.json() + if "error" in body: + # Modern discovery is optional in auto; when present it must still + # agree with the low-level capabilities and never advertise Tasks. + assert body["error"]["code"] == -32601 + return + capabilities = body["result"].get("capabilities", {}) + assert "tasks" not in capabilities + assert "io.modelcontextprotocol/tasks" not in capabilities.get("extensions", {}) + + +@pytest.mark.parametrize("method", ["tasks/get", "tasks/list", "tasks/result", "tasks/cancel"]) +def test_2026_task_methods_are_method_not_found(method): + response = _http_request( + _app("auto"), + {"jsonrpc": "2.0", "id": 1, "method": method, "params": {}}, + ) + assert response.status_code == 200 + body = response.json() + assert body["error"]["code"] == -32601 + + +def test_2026_task_augmented_http_call_is_not_a_task_result(): + response = _http_request( + _app("auto"), + { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "taskable", + "arguments": {}, + "task": {"ttl": 60_000}, + }, + }, + ) + assert response.status_code == 200 + body = response.json() + assert body["error"]["code"] == -32602 + assert "resultType" not in body.get("result", {}) diff --git a/tests/test_tasks.py b/tests/test_tasks.py index b1dad3c..08bde04 100644 --- a/tests/test_tasks.py +++ b/tests/test_tasks.py @@ -471,7 +471,7 @@ class TestTasksModule: async def _mcp_task_flow(): - harness = await NitroTestingModule.create(TestTasksModule) + harness = await NitroTestingModule.create(TestTasksModule, protocol_era="legacy") req = types.CallToolRequest( method="tools/call", From 416fe9857f76941268a0132f53ed90e293b987a4 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Wed, 14 Oct 2026 16:38:24 +0530 Subject: [PATCH 003/146] fix(tools): keep null branch in registered outputSchema --- nitrostack/core/app.py | 4 +-- tests/test_tool_output_schema.py | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 tests/test_tool_output_schema.py diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index 9d9b069..4786db9 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -306,10 +306,10 @@ def tool_json_schema(schema_spec: Any) -> Optional[Dict[str, Any]]: if schema_spec is None: return None if isinstance(schema_spec, dict): - return normalize_output_schema(inspector_friendly_schema(schema_spec)) + return normalize_output_schema(schema_spec) model = get_pydantic_model(schema_spec) if model is not None: - return normalize_output_schema(inspector_friendly_schema(model.model_json_schema())) + return normalize_output_schema(model.model_json_schema()) return None diff --git a/tests/test_tool_output_schema.py b/tests/test_tool_output_schema.py new file mode 100644 index 0000000..669d77c --- /dev/null +++ b/tests/test_tool_output_schema.py @@ -0,0 +1,49 @@ +from typing import Any, Dict, Optional + +import jsonschema +from pydantic import BaseModel + +from nitrostack.core.app import inspector_friendly_schema, tool_json_schema + + +class Out(BaseModel): + maybe: Optional[str] = None + n: Optional[int] = None + required_str: str = "x" + + +def _accepts_null(prop: Dict[str, Any]) -> bool: + for key in ("anyOf", "oneOf"): + if any(v.get("type") == "null" for v in prop.get(key, [])): + return True + types = prop.get("type") + return isinstance(types, list) and "null" in types + + +def test_output_schema_keeps_null_for_model(): + props = tool_json_schema(Out)["properties"] + assert _accepts_null(props["maybe"]) + assert _accepts_null(props["n"]) + + +def test_output_schema_keeps_null_for_dict(): + props = tool_json_schema(Out.model_json_schema())["properties"] + assert _accepts_null(props["maybe"]) + assert _accepts_null(props["n"]) + + +def test_output_schema_does_not_loosen_required_fields(): + props = tool_json_schema(Out)["properties"] + assert not _accepts_null(props["required_str"]) + assert props["required_str"]["type"] == "string" + + +def test_output_schema_validates_null_payload(): + jsonschema.validate({"maybe": None, "n": None, "required_str": "x"}, tool_json_schema(Out)) + + +def test_input_schema_still_unwraps_optional_for_inspector(): + props = inspector_friendly_schema(Out.model_json_schema())["properties"] + assert not _accepts_null(props["maybe"]) + assert props["maybe"]["type"] == "string" + assert props["n"]["type"] == "integer" \ No newline at end of file From c6a6bb46b4f403f8b0de1e072d1ce57e7571ac6b Mon Sep 17 00:00:00 2001 From: Aadarsh Mahesh K Date: Thu, 22 Oct 2026 23:49:21 +0530 Subject: [PATCH 004/146] fix(auth): deny CIMD host mismatch, require pinned IP for outbound peer, remove duplicate helpers --- nitrostack/auth/cimd.py | 31 +-------------- nitrostack/auth/oauth_module.py | 26 +++++++++---- nitrostack/auth/request.py | 11 +++--- tests/test_mcp20_oauth_cimd.py | 68 ++++++++++++++++++++++++++++----- 4 files changed, 84 insertions(+), 52 deletions(-) diff --git a/nitrostack/auth/cimd.py b/nitrostack/auth/cimd.py index f9aa7a3..5ff4366 100644 --- a/nitrostack/auth/cimd.py +++ b/nitrostack/auth/cimd.py @@ -125,16 +125,10 @@ def _pick_pinned_ip(resolved_ips: set[str]) -> str: def cimd_peer_is_acceptable(peer: str, pinned_ip: str) -> bool: - """Require the direct socket peer to match the pinned IP. - - A configured trusted proxy hop is the only exception; untrusted peers - cannot stand in for the destination. - """ + """Require the direct socket peer to match the pinned IP.""" if peer == pinned_ip: return not is_blocked_ip(peer) - from nitrostack.transports.proxy import peer_is_trusted - - return peer_is_trusted(peer) + return False def request_host_for_cimd( @@ -369,24 +363,3 @@ def resolve_cimd_sync( resolve_cimd(client_id_url, allow_loopback=allow_loopback, timeout_sec=timeout_sec) ) raise CimdFetchError("CIMD resolution cannot run nested on a running event loop") - - -def looks_like_cimd_url(value: Any) -> bool: - """Return True when ``value`` is an http(s) client identifier URL.""" - return isinstance(value, str) and value.startswith(("https://", "http://")) - - -def resolve_cimd_sync( - client_id_url: str, - *, - allow_loopback: bool = False, - timeout_sec: float = CIMD_FETCH_TIMEOUT_SEC, -) -> dict[str, Any]: - """Synchronous wrapper for registration / other non-async callers.""" - try: - asyncio.get_running_loop() - except RuntimeError: - return asyncio.run( - resolve_cimd(client_id_url, allow_loopback=allow_loopback, timeout_sec=timeout_sec) - ) - raise CimdFetchError("CIMD resolution cannot run nested on a running event loop") diff --git a/nitrostack/auth/oauth_module.py b/nitrostack/auth/oauth_module.py index b2585c4..bfc59d1 100644 --- a/nitrostack/auth/oauth_module.py +++ b/nitrostack/auth/oauth_module.py @@ -112,22 +112,32 @@ def apply_cimd_to_registration_body( honored only when the peer is trusted, so an untrusted ``X-Forwarded-Host`` cannot rebind the CIMD host comparison. """ - from nitrostack.auth.cimd import cimd_host_matches_request, request_host_for_cimd + from nitrostack.auth.cimd import ( + CimdValidationError, + cimd_host_matches_request, + request_host_for_cimd, + ) payload = dict(body or {}) client_id = payload.get("client_id") if not looks_like_cimd_url(client_id): return payload document = resolve_cimd_sync(str(client_id)) - payload["client_id"] = document["client_id"] - payload["_cimd"] = document - if headers is not None: - payload["_cimd_request_host"] = request_host_for_cimd(headers, peer) - payload["_cimd_host_matches_request"] = cimd_host_matches_request( + if headers is not None or peer is not None: + req_headers = headers if headers is not None else {} + if not cimd_host_matches_request( str(document["client_id"]), - headers, + req_headers, peer, - ) + ): + req_host = request_host_for_cimd(req_headers, peer) + raise CimdValidationError( + f"CIMD client_id URL host does not match request host: {req_host!r}" + ) + payload["_cimd_request_host"] = request_host_for_cimd(req_headers, peer) + payload["_cimd_host_matches_request"] = True + payload["client_id"] = document["client_id"] + payload["_cimd"] = document return payload diff --git a/nitrostack/auth/request.py b/nitrostack/auth/request.py index b3c22c4..6804951 100644 --- a/nitrostack/auth/request.py +++ b/nitrostack/auth/request.py @@ -108,12 +108,13 @@ def authorization_token_from_request(rc: Any) -> Optional[str]: def verify_bearer_payload(token: str) -> Optional[dict[str, Any]]: - try: - from nitrostack.auth.jwt import JWTService - from nitrostack.core.di import DIContainer + from nitrostack.auth.jwt import JWTService + from nitrostack.core.di import DIContainer - payload = DIContainer.get_instance().resolve(JWTService).verify_token(token) - except Exception: + service = DIContainer.get_instance().resolve(JWTService) + try: + payload = service.verify_token(token) + except ValueError: return None return payload if isinstance(payload, dict) else None diff --git a/tests/test_mcp20_oauth_cimd.py b/tests/test_mcp20_oauth_cimd.py index b269faa..fc72ce0 100644 --- a/tests/test_mcp20_oauth_cimd.py +++ b/tests/test_mcp20_oauth_cimd.py @@ -176,9 +176,10 @@ def test_direct_peer_must_match_pin(self, monkeypatch): assert cimd_peer_is_acceptable("8.8.8.8", "8.8.8.8") is True assert cimd_peer_is_acceptable("1.2.3.4", "8.8.8.8") is False - def test_trusted_proxy_peer_is_acceptable(self, monkeypatch): + def test_trusted_proxy_peer_is_not_acceptable_for_outbound(self, monkeypatch): monkeypatch.setenv("TRUSTED_PROXIES", "10.0.0.5") - assert cimd_peer_is_acceptable("10.0.0.5", "8.8.8.8") is True + # Trusted proxies apply to inbound headers, NOT outbound socket fetch pins. + assert cimd_peer_is_acceptable("10.0.0.5", "8.8.8.8") is False assert cimd_peer_is_acceptable("10.0.0.9", "8.8.8.8") is False def test_untrusted_forwarded_host_cannot_rebind_cimd(self, monkeypatch): @@ -191,7 +192,7 @@ def test_untrusted_forwarded_host_cannot_rebind_cimd(self, monkeypatch): assert request_host_for_cimd(headers, peer="8.8.8.8") == "mcp.nitrostack.io" assert cimd_host_matches_request(url, headers, peer="8.8.8.8") is False - def test_apply_cimd_records_untrusted_request_host(self, monkeypatch): + def test_apply_cimd_denies_untrusted_request_host_mismatch(self, monkeypatch): monkeypatch.delenv("TRUSTED_PROXIES", raising=False) url = "https://app.nitrostack.io/oauth/client-metadata.json" headers = { @@ -202,13 +203,13 @@ def test_apply_cimd_records_untrusted_request_host(self, monkeypatch): "nitrostack.auth.oauth_module.resolve_cimd_sync", return_value={"client_id": url, "client_name": "Studio"}, ): - body = apply_cimd_to_registration_body( - {"client_id": url}, - headers=headers, - peer="8.8.8.8", - ) - assert body["_cimd_request_host"] == "mcp.nitrostack.io" - assert body["_cimd_host_matches_request"] is False + with pytest.raises(CimdValidationError) as exc_info: + apply_cimd_to_registration_body( + {"client_id": url}, + headers=headers, + peer="8.8.8.8", + ) + assert "host" in str(exc_info.value).lower() def test_apply_cimd_honors_trusted_forwarded_host(self, monkeypatch): monkeypatch.setenv("TRUSTED_PROXIES", "10.0.0.5") @@ -229,6 +230,12 @@ def test_apply_cimd_honors_trusted_forwarded_host(self, monkeypatch): assert body["_cimd_request_host"] == "app.nitrostack.io" assert body["_cimd_host_matches_request"] is True + def test_cimd_helpers_defined_once(self): + from pathlib import Path + source = Path("nitrostack/auth/cimd.py").read_text(encoding="utf-8") + assert source.count("def looks_like_cimd_url") == 1 + assert source.count("def resolve_cimd_sync") == 1 + class TestCimdRegistrationWiring: def test_applies_cimd_document_to_registration_body(self): @@ -266,3 +273,44 @@ def test_rejects_missing_iss(self): def test_rejects_mismatched_iss(self): with pytest.raises(AuthorizationIssuerMismatchError, match="mismatch"): validate_authorization_iss("https://evil.example", "https://auth.nitrostack.io") + + +class TestVerifyBearerPayload: + def test_returns_payload_for_valid_token(self): + from nitrostack.auth.jwt import JWTService + from nitrostack.auth.request import verify_bearer_payload + from nitrostack.core.di import DIContainer + + DIContainer.reset() + service = JWTService() + DIContainer.get_instance().register_value(JWTService, service) + token = service.create_token({"sub": "user_123", "tenant_id": "org_abc"}) + payload = verify_bearer_payload(token) + assert payload is not None + assert payload["sub"] == "user_123" + assert payload["tenant_id"] == "org_abc" + + def test_returns_none_for_invalid_token(self): + from nitrostack.auth.jwt import JWTService + from nitrostack.auth.request import verify_bearer_payload + from nitrostack.core.di import DIContainer + + DIContainer.reset() + service = JWTService() + DIContainer.get_instance().register_value(JWTService, service) + assert verify_bearer_payload("invalid.token.structure") is None + assert verify_bearer_payload("not-a-jwt") is None + + def test_raises_on_di_misconfig(self): + from nitrostack.auth.request import verify_bearer_payload + from nitrostack.core.di import DIContainer + from nitrostack.core.errors import DependencyResolutionError + + DIContainer.reset() + with patch.object( + DIContainer.get_instance(), + "resolve", + side_effect=DependencyResolutionError("JWTService missing"), + ): + with pytest.raises(DependencyResolutionError): + verify_bearer_payload("header.payload.signature") From 41ca887d391a27fdd785f377509c356f4d8d22cd Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Fri, 23 Oct 2026 20:20:01 +0530 Subject: [PATCH 005/146] test: capture tools/list baseline before transform pipeline (#61) --- scripts/capture_tools_baseline.py | 56 +++++++++++++++++++++++++ tests/fixtures/tools_list_baseline.json | 5 +++ 2 files changed, 61 insertions(+) create mode 100644 scripts/capture_tools_baseline.py create mode 100644 tests/fixtures/tools_list_baseline.json diff --git a/scripts/capture_tools_baseline.py b/scripts/capture_tools_baseline.py new file mode 100644 index 0000000..50b52a2 --- /dev/null +++ b/scripts/capture_tools_baseline.py @@ -0,0 +1,56 @@ + +"""Capture real tools/list responses from the unmodified base SDK.""" +import asyncio +import json +import pathlib +import sys + +ROOT = pathlib.Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +import mcp.types as types + +from nitrostack.testing import NitroTestingModule +from tests._baseline_catalog import ERAS, M + +OUT = ROOT / "tests" / "fixtures" / "tools_list_baseline.json" + + +async def list_tools(era: str) -> str: + harness = await NitroTestingModule.create(M, protocol_era=era) + server = harness.app.mcp_server + + response = ( + await server.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list") + ) + ).root + + return response.model_dump_json( + by_alias=True, + exclude_none=True, + ) + + +async def main() -> None: + baseline = {} + + for era in ERAS: + serialized = await list_tools(era) + baseline[era] = serialized + names = [ + item["name"] + for item in json.loads(serialized)["tools"] + ] + print(f"{era}: {names}") + + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text( + json.dumps(baseline, indent=2), + encoding="utf-8", + ) + print(f"Wrote {OUT} ({OUT.stat().st_size} bytes)") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tests/fixtures/tools_list_baseline.json b/tests/fixtures/tools_list_baseline.json new file mode 100644 index 0000000..6edb97d --- /dev/null +++ b/tests/fixtures/tools_list_baseline.json @@ -0,0 +1,5 @@ +{ + "legacy": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}", + "auto": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}", + "modern": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}" +} \ No newline at end of file From 0bae98a044167b457a1d53360bfda5e64e9fe005 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Fri, 23 Oct 2026 20:21:13 +0530 Subject: [PATCH 006/146] feat(transforms): add McpTransform protocol, CatalogTransform and TransformPipeline (#61) --- nitrostack/transforms/__init__.py | 20 +++++ nitrostack/transforms/pipeline.py | 112 ++++++++++++++++++++++++ nitrostack/transforms/transform.py | 128 ++++++++++++++++++++++++++++ nitrostack/transforms/validation.py | 29 +++++++ tests/test_transforms_pipeline.py | 104 ++++++++++++++++++++++ tests/test_transforms_reentrancy.py | 50 +++++++++++ 6 files changed, 443 insertions(+) create mode 100644 nitrostack/transforms/__init__.py create mode 100644 nitrostack/transforms/pipeline.py create mode 100644 nitrostack/transforms/transform.py create mode 100644 nitrostack/transforms/validation.py create mode 100644 tests/test_transforms_pipeline.py create mode 100644 tests/test_transforms_reentrancy.py diff --git a/nitrostack/transforms/__init__.py b/nitrostack/transforms/__init__.py new file mode 100644 index 0000000..667e7d7 --- /dev/null +++ b/nitrostack/transforms/__init__.py @@ -0,0 +1,20 @@ +from nitrostack.transforms.transform import ( + CatalogTransform, + McpTransform, + McpTransformBase, + TransformContext, + active_bypass, + bypassing, +) +from nitrostack.transforms.pipeline import ( + TransformError, + TransformPipeline, + TransformRegistry, +) +from nitrostack.transforms.validation import ToolArgumentError, validate_tool_arguments + +__all__ = [ + "CatalogTransform", "McpTransform", "McpTransformBase", "TransformContext", + "TransformError", "TransformPipeline", "TransformRegistry", + "ToolArgumentError", "validate_tool_arguments", "active_bypass", "bypassing", +] \ No newline at end of file diff --git a/nitrostack/transforms/pipeline.py b/nitrostack/transforms/pipeline.py new file mode 100644 index 0000000..282de09 --- /dev/null +++ b/nitrostack/transforms/pipeline.py @@ -0,0 +1,112 @@ +"""Ordered execution of transforms for tools/list and tools/call resolution.""" +from __future__ import annotations + +import logging +from typing import Any, Awaitable, Callable, List, Optional, Sequence + +from nitrostack.transforms.transform import ( + NextResolver, Tool, TransformContext, active_bypass, maybe_await, +) + +logger = logging.getLogger(__name__) + +BaseResolver = Callable[[str], Any] # returns Tool | None (sync or async) + + +class TransformError(Exception): + """A transform hook raised. The app maps this to a JSON-RPC error.""" + + def __init__(self, transform_name: str, hook: str) -> None: + super().__init__(f"Transform '{transform_name}' failed in {hook}.") + self.transform_name = transform_name + self.hook = hook + + +class TransformRegistry: + """Read-only view passed to ``on_register``.""" + + def __init__(self, list_tools: Callable[[], Sequence[Tool]]) -> None: + self._list_tools = list_tools + + def list_tools(self) -> List[Tool]: + return list(self._list_tools()) + + +class TransformPipeline: + def __init__(self, transforms: Optional[Sequence[Any]] = None) -> None: + self._transforms: List[Any] = list(transforms or []) + names = [t.name for t in self._transforms] + if len(set(names)) != len(names): + raise ValueError(f"Transform names must be unique, got {names}") + + @property + def enabled(self) -> bool: + return bool(self._transforms) + + def register(self, registry: TransformRegistry) -> None: + for t in self._transforms: + try: + t.on_register(registry) + except Exception as exc: + raise TransformError(t.name, "on_register") from exc + + async def transform_tools( + self, tools: Sequence[Tool], ctx: TransformContext + ) -> List[Tool]: + current = list(tools) + if not self._transforms: + return current + skipped = active_bypass() + for t in self._transforms: + if t.name in skipped: + continue + try: + current = list(await maybe_await(t.transform_tools(current, ctx))) + except TransformError: + raise + except Exception as exc: + logger.exception("Transform %s failed in transform_tools", t.name) + raise TransformError(t.name, "transform_tools") from exc + return current + + async def resolve_tool( + self, name: str, base: BaseResolver, ctx: TransformContext + ) -> Optional[Tool]: + """First declared transform is outermost; each chains through ``next``. + + ``base`` must only look the tool up (return None if unknown). Guards and + argument validation happen after resolution, in the app's invoker. + """ + if not self._transforms: + return await maybe_await(base(name)) + + transforms = self._transforms + + async def run(index: int, tool_name: str) -> Optional[Tool]: + skipped = active_bypass() + while index < len(transforms) and transforms[index].name in skipped: + index += 1 + if index >= len(transforms): + return await maybe_await(base(tool_name)) + t = transforms[index] + + async def nxt(n: str) -> Optional[Tool]: + return await run(index + 1, n) + + try: + return await maybe_await(t.resolve_tool(tool_name, nxt, ctx)) + except TransformError: + raise + except Exception as exc: + logger.exception("Transform %s failed in resolve_tool", t.name) + raise TransformError(t.name, "resolve_tool") from exc + + return await run(0, name) + + async def dispose(self) -> None: + """Dispose in reverse order; one failure must not stop the others.""" + for t in reversed(self._transforms): + try: + await maybe_await(t.dispose()) + except Exception: + logger.exception("Transform %s failed in dispose", t.name) \ No newline at end of file diff --git a/nitrostack/transforms/transform.py b/nitrostack/transforms/transform.py new file mode 100644 index 0000000..f3f7a83 --- /dev/null +++ b/nitrostack/transforms/transform.py @@ -0,0 +1,128 @@ +"""Transform protocol, base classes, context and re-entrancy bypass.""" +from __future__ import annotations + +import contextlib +import contextvars +import inspect +from abc import abstractmethod +from dataclasses import dataclass, field +from typing import ( + Any, Awaitable, Callable, Dict, Iterator, List, Optional, Protocol, + Sequence, runtime_checkable, +) + +Tool = Any # mcp.types.Tool in practice; kept loose so transforms may add synthetic tools +NextResolver = Callable[[str], Awaitable[Optional[Tool]]] +ToolInvoker = Callable[[str, Dict[str, Any], "TransformContext"], Awaitable[Any]] + +# Names of transforms to skip for the current call chain. Set while a synthetic +# tool calls a real tool, so the issuing transform is not re-applied. +_BYPASS: contextvars.ContextVar[frozenset] = contextvars.ContextVar( + "nitrostack_transform_bypass", default=frozenset() +) + + +def active_bypass() -> frozenset: + return _BYPASS.get() + + +@contextlib.contextmanager +def bypassing(name: str) -> Iterator[None]: + token = _BYPASS.set(_BYPASS.get() | {name}) + try: + yield + finally: + _BYPASS.reset(token) + + +async def maybe_await(value: Any) -> Any: + if inspect.isawaitable(value): + return await value + return value + + +@dataclass +class TransformContext: + """Per-request context handed to every transform hook.""" + + session_id: Optional[str] = None + execution_context: Any = None # the ExecutionContext of the originating request + metadata: Dict[str, Any] = field(default_factory=dict) + _invoker: Optional[ToolInvoker] = None + + async def call_tool( + self, + name: str, + arguments: Optional[Dict[str, Any]] = None, + *, + caller: Optional[str] = None, + ) -> Any: + """Invoke a real tool from a synthetic tool. + + Goes through the same path as a normal tools/call, so guards and argument + validation run for the real tool. If ``caller`` is given, that transform + is skipped for the duration of the call (no re-entrancy loop). + """ + if self._invoker is None: + raise RuntimeError("TransformContext has no tool invoker attached.") + args = arguments or {} + if caller: + with bypassing(caller): + return await self._invoker(name, args, self) + return await self._invoker(name, args, self) + + +@runtime_checkable +class McpTransform(Protocol): + name: str + + def on_register(self, registry: Any) -> Any: ... + async def dispose(self) -> None: ... + async def transform_tools( + self, tools: Sequence[Tool], ctx: TransformContext + ) -> List[Tool]: ... + async def resolve_tool( + self, name: str, next: NextResolver, ctx: TransformContext + ) -> Optional[Tool]: ... + + +class McpTransformBase: + """Convenience base: every hook defaults to a pass-through. Hooks may be sync or async.""" + + name: str = "transform" + + def on_register(self, registry: Any) -> None: + return None + + async def dispose(self) -> None: + return None + + async def transform_tools(self, tools: Sequence[Tool], ctx: TransformContext) -> List[Tool]: + return list(tools) + + async def resolve_tool( + self, name: str, next: NextResolver, ctx: TransformContext + ) -> Optional[Tool]: + return await next(name) + + def is_bypassed(self) -> bool: + return self.name in _BYPASS.get() + + +class CatalogTransform(McpTransformBase): + """Base for transforms that rewrite the catalog. + + Subclasses implement ``apply_transform``. While this transform's own synthetic + tool is calling a real tool, ``transform_tools`` returns the catalog unchanged. + """ + + @abstractmethod + def apply_transform( + self, tools: Sequence[Tool], ctx: TransformContext + ) -> Any: # list or awaitable of list + ... + + async def transform_tools(self, tools: Sequence[Tool], ctx: TransformContext) -> List[Tool]: + if self.is_bypassed(): + return list(tools) + return list(await maybe_await(self.apply_transform(tools, ctx))) \ No newline at end of file diff --git a/nitrostack/transforms/validation.py b/nitrostack/transforms/validation.py new file mode 100644 index 0000000..621537a --- /dev/null +++ b/nitrostack/transforms/validation.py @@ -0,0 +1,29 @@ +"""One place that validates tool arguments, shared by normal and re-entrant calls.""" +from __future__ import annotations + +from typing import Any, Dict, Optional, Type + +from pydantic import BaseModel, ValidationError + + +class ToolArgumentError(ValueError): + """Arguments did not match the tool's input schema.""" + + def __init__(self, tool_name: str, errors: list) -> None: + super().__init__(f"Invalid arguments for tool '{tool_name}'.") + self.tool_name = tool_name + self.errors = errors + + +def validate_tool_arguments( + tool_name: str, + input_model: Optional[Type[BaseModel]], + arguments: Dict[str, Any], +) -> Any: + """Return the validated input object (or the raw dict if the tool has no model).""" + if input_model is None: + return arguments + try: + return input_model.model_validate(arguments) + except ValidationError as exc: + raise ToolArgumentError(tool_name, exc.errors(include_url=False)) from exc \ No newline at end of file diff --git a/tests/test_transforms_pipeline.py b/tests/test_transforms_pipeline.py new file mode 100644 index 0000000..dd37e31 --- /dev/null +++ b/tests/test_transforms_pipeline.py @@ -0,0 +1,104 @@ +import pytest + +from nitrostack.transforms import ( + CatalogTransform, McpTransformBase, TransformContext, TransformError, TransformPipeline, +) + + +class Tag(McpTransformBase): + def __init__(self, name, log): + self.name = name + self.log = log + + async def transform_tools(self, tools, ctx): + self.log.append(self.name) + return [t + f"+{self.name}" for t in tools] + + async def resolve_tool(self, name, next, ctx): + self.log.append(f"resolve:{self.name}") + found = await next(name) + return None if found is None else f"{found}|{self.name}" + + +@pytest.mark.asyncio +async def test_empty_pipeline_is_identity(): + p = TransformPipeline([]) + assert not p.enabled + tools = ["a", "b"] + assert await p.transform_tools(tools, TransformContext()) == ["a", "b"] + assert await p.resolve_tool("a", lambda n: n, TransformContext()) == "a" + + +@pytest.mark.asyncio +async def test_list_transforms_apply_in_declared_order(): + log = [] + p = TransformPipeline([Tag("one", log), Tag("two", log)]) + out = await p.transform_tools(["x"], TransformContext()) + assert out == ["x+one+two"] + assert log == ["one", "two"] + + +@pytest.mark.asyncio +async def test_resolve_chains_through_next_first_is_outermost(): + log = [] + p = TransformPipeline([Tag("one", log), Tag("two", log)]) + out = await p.resolve_tool("x", lambda n: n, TransformContext()) + assert out == "x|two|one" + assert log == ["resolve:one", "resolve:two"] + + +@pytest.mark.asyncio +async def test_resolve_unknown_tool_returns_none(): + p = TransformPipeline([Tag("one", [])]) + assert await p.resolve_tool("nope", lambda n: None, TransformContext()) is None + + +@pytest.mark.asyncio +async def test_raising_transform_becomes_transform_error(): + class Boom(McpTransformBase): + name = "boom" + + async def transform_tools(self, tools, ctx): + raise RuntimeError("bad") + + p = TransformPipeline([Boom()]) + with pytest.raises(TransformError) as e: + await p.transform_tools(["a"], TransformContext()) + assert e.value.transform_name == "boom" + # the pipeline is still usable afterwards + assert await TransformPipeline([]).transform_tools(["a"], TransformContext()) == ["a"] + + +@pytest.mark.asyncio +async def test_dispose_runs_all_in_reverse_even_if_one_fails(): + order = [] + + class D(McpTransformBase): + def __init__(self, name, fail=False): + self.name, self.fail = name, fail + + async def dispose(self): + order.append(self.name) + if self.fail: + raise RuntimeError("x") + + p = TransformPipeline([D("a"), D("b", fail=True), D("c")]) + await p.dispose() + assert order == ["c", "b", "a"] + + +def test_duplicate_names_rejected(): + with pytest.raises(ValueError): + TransformPipeline([Tag("same", []), Tag("same", [])]) + + +@pytest.mark.asyncio +async def test_catalog_transform_applies_and_supports_sync_apply(): + class Upper(CatalogTransform): + name = "upper" + + def apply_transform(self, tools, ctx): + return [t.upper() for t in tools] + + p = TransformPipeline([Upper()]) + assert await p.transform_tools(["a"], TransformContext()) == ["A"] \ No newline at end of file diff --git a/tests/test_transforms_reentrancy.py b/tests/test_transforms_reentrancy.py new file mode 100644 index 0000000..ee549c1 --- /dev/null +++ b/tests/test_transforms_reentrancy.py @@ -0,0 +1,50 @@ +import pytest + +from nitrostack.transforms import ( + CatalogTransform, TransformContext, TransformPipeline, bypassing, +) + + +class Hide(CatalogTransform): + name = "hide" + + def __init__(self): + self.applied = 0 + + def apply_transform(self, tools, ctx): + self.applied += 1 + return [t for t in tools if t != "secret"] + + +@pytest.mark.asyncio +async def test_transform_is_skipped_while_its_own_call_is_running(): + h = Hide() + p = TransformPipeline([h]) + ctx = TransformContext() + + assert await p.transform_tools(["a", "secret"], ctx) == ["a"] + assert h.applied == 1 + + with bypassing("hide"): + assert await p.transform_tools(["a", "secret"], ctx) == ["a", "secret"] + assert h.applied == 1 # not re-run + + assert await p.transform_tools(["a", "secret"], ctx) == ["a"] # bypass was released + assert h.applied == 2 + + +@pytest.mark.asyncio +async def test_call_tool_with_caller_bypasses_that_transform_only(): + seen = {} + + async def invoker(name, args, ctx): + from nitrostack.transforms import active_bypass + seen["bypass"] = set(active_bypass()) + return f"called {name}" + + ctx = TransformContext(_invoker=invoker) + assert await ctx.call_tool("real", {}, caller="hide") == "called real" + assert seen["bypass"] == {"hide"} + + await ctx.call_tool("real", {}) + assert seen["bypass"] == set() \ No newline at end of file From 1211d6bb7fca873646859ee744b50bb7d8afdbd4 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Fri, 23 Oct 2026 20:21:52 +0530 Subject: [PATCH 007/146] feat(core): apply transforms to tools/list and tools/call, share argument validation (#61) --- nitrostack/core/app.py | 55 +++++++++++--- nitrostack/testing/__init__.py | 25 +++++-- tests/test_transformsapp.py | 127 +++++++++++++++++++++++++++++++++ 3 files changed, 193 insertions(+), 14 deletions(-) create mode 100644 tests/test_transformsapp.py diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index 9d9b069..222ddc5 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -25,6 +25,12 @@ UnsubscribeRequestParams, ) from pydantic import BaseModel, create_model +from nitrostack.transforms import ( + TransformContext, + TransformError, + TransformPipeline, + TransformRegistry, +) from nitrostack.core.context import ExecutionContext, TaskContext from nitrostack.core.decorators import ToolConfig, ResourceConfig, PromptConfig, widget_resource_uri @@ -206,17 +212,20 @@ class ServerConfig: description: Optional[str] = None -def mcp_app(module: Type, server: ServerConfig): - """ - Decorator to declare the main application class. - Specifies the root AppModule and ServerConfig. - """ +def mcp_app( + module: Type, + server: ServerConfig, + transforms: Optional[List[Any]] = None, +): + """Declare an MCP application and its optional tool-list transforms.""" + def decorator(cls: Type): cls._mcp_app_module = module cls._mcp_app_server = server + cls._mcp_transforms = list(transforms or []) return cls - return decorator + return decorator def get_pydantic_model(schema: Any) -> Type[BaseModel]: """Helper to resolve or construct a Pydantic model for input validation.""" @@ -601,6 +610,15 @@ def __init__(self, app_class: Type): self._bootstrap() + # Initialize the transform pipeline + # Initialize transforms before registering handlers. Handlers use + # this pipeline when tools/list is requested. + self._transforms = TransformPipeline( + getattr(self.app_class, "_mcp_transforms", None) or [] + ) + + self._bootstrap() + def _bootstrap(self) -> None: # 1. Construct the low-level server directly. self.mcp_server = NitroStackMcpServer( @@ -880,9 +898,30 @@ def _list_endpoint_cache_meta(self) -> Dict[str, Any]: return build_list_endpoint_cache_hint_meta() def _setup_handlers(self, server: NitroStackMcpServer) -> None: - async def _list_tools(_ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams]): + async def _list_tools( + _ctx: ServerRequestContext, + _params: Optional[PaginatedRequestParams], + ): + tools = [ + self._build_tool_definition(entry) + for entry in self._tools.values() + ] + + if self._transforms.enabled: + try: + context = TransformContext() + tools = await self._transforms.transform_tools( + tools, + context, + ) + except TransformError as exc: + raise MCPError( + types.INTERNAL_ERROR, + str(exc), + ) from exc + return types.ListToolsResult( - tools=[self._build_tool_definition(entry) for entry in self._tools.values()], + tools=tools, _meta=self._list_endpoint_cache_meta(), ) diff --git a/nitrostack/testing/__init__.py b/nitrostack/testing/__init__.py index 0db12b6..25f0efb 100644 --- a/nitrostack/testing/__init__.py +++ b/nitrostack/testing/__init__.py @@ -14,19 +14,32 @@ class NitroTestingModule: Dispatches through the owned low-level `mcp.server.lowlevel.Server` `request_handlers` (the same dict the real stdio/HTTP transports use). """ + def __init__(self, app: McpApplication): + self.app = app @classmethod - async def create(cls, app_module: Type) -> "NitroTestingModule": - # Construct a dummy App class decorated with @mcp_app - @mcp_app(module=app_module, server=ServerConfig(name="test-server")) + async def create( + cls, + app_module: Type, + *, + protocol_era: Optional[str] = None, + transforms: Optional[list] = None, + ) -> "NitroTestingModule": + server_config = ServerConfig( + name="test-server", + protocol_era=protocol_era, + ) + + @mcp_app( + module=app_module, + server=server_config, + transforms=transforms, + ) class TestApp: pass app = await McpApplicationFactory.create(TestApp) return cls(app) - def __init__(self, app: McpApplication): - self.app = app - @staticmethod def _extract_text(text_val: Optional[str]) -> Any: if text_val is None: diff --git a/tests/test_transformsapp.py b/tests/test_transformsapp.py new file mode 100644 index 0000000..779cd7b --- /dev/null +++ b/tests/test_transformsapp.py @@ -0,0 +1,127 @@ + +import json +import pathlib + +import mcp.types as types +import pytest + +from nitrostack.testing import NitroTestingModule +from nitrostack.transforms import CatalogTransform, McpTransformBase +from tests._baseline_catalog import ERAS, In, M + + +BASELINE = ( + pathlib.Path(__file__).parent + / "fixtures" + / "tools_list_baseline.json" +) + + +async def _list(h): + srv = h.app.mcp_server + response = ( + await srv.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list") + ) + ).root + return response + + +@pytest.mark.asyncio +@pytest.mark.parametrize("era", ERAS) +async def test_no_transforms_output_is_byte_identical_to_baseline( + era, monkeypatch +): + monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", era) + + h = await NitroTestingModule.create(M) + response = await _list(h) + + expected = json.loads( + BASELINE.read_text(encoding="utf-8") + )[era] + + actual = response.model_dump_json( + by_alias=True, + exclude_none=True, + ) + + assert actual == expected + + +class DropBeta(CatalogTransform): + name = "drop_beta" + + def apply_transform(self, tools, ctx): + return [tool for tool in tools if tool.name != "beta"] + + +class Suffix(CatalogTransform): + name = "suffix" + + def apply_transform(self, tools, ctx): + return [ + tool.model_copy( + update={ + "description": (tool.description or "") + "!" + } + ) + for tool in tools + ] + + +@pytest.mark.asyncio +async def test_two_transforms_compose_in_declared_order_for_list(): + h = await NitroTestingModule.create( + M, + transforms=[DropBeta(), Suffix()], + ) + + response = await _list(h) + + assert [tool.name for tool in response.tools] == ["alpha"] + assert response.tools[0].description == "first!" + + +class Boom(McpTransformBase): + name = "boom" + + async def transform_tools(self, tools, ctx): + raise RuntimeError("bad transform") + + +@pytest.mark.asyncio +async def test_failing_transform_returns_error_and_server_keeps_serving(): + h = await NitroTestingModule.create( + M, + transforms=[Boom()], + ) + + with pytest.raises(Exception): + await _list(h) + + # A transform failure must not stop the server from handling tool calls. + result = await h.call_tool("alpha", {"input": {"q": "x"}}) + assert result is not None + + +@pytest.mark.asyncio +async def test_dispose_runs_on_shutdown(): + disposed = [] + + class D(McpTransformBase): + name = "d" + + async def dispose(self): + disposed.append(True) + + h = await NitroTestingModule.create( + M, + transforms=[D()], + ) + + # Exercise disposal directly because this harness may not expose + # a public application-shutdown method. + await h.app._transforms.dispose() + + assert disposed == [True] From 8464d8a4e08172faeea97ba29ea203226369b42c Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Fri, 23 Oct 2026 00:35:14 +0530 Subject: [PATCH 008/146] security: mitigate eMudhra/emSign CA incident (certifi floor, secure pip bootstrap, uv gate) --- .github/workflows/test.yml | 8 +- README.md | 12 +++ nitrostack/cli/install.py | 76 +++++++++++++- pyproject.toml | 3 +- requirements.txt | 1 + tests/test_cli_install.py | 3 + tests/test_cli_install_security.py | 158 +++++++++++++++++++++++++++++ tests/test_security_config.py | 53 ++++++++++ uv.lock | 34 +++++-- 9 files changed, 333 insertions(+), 15 deletions(-) create mode 100644 tests/test_cli_install_security.py create mode 100644 tests/test_security_config.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 910f9c0..a18cf80 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -21,10 +21,14 @@ jobs: with: python-version: ${{ matrix.python-version }} + - name: Secure pip bootstrap (eMudhra/emSign advisory) + run: | + python -m pip install "pip @ https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl#sha256=fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70" + python -m pip install --upgrade "certifi>=2026.10.19" + - name: Install dependencies run: | - python -m pip install --upgrade pip - pip install -e ".[dev]" + python -m pip install -e ".[dev]" - name: Run pytest with coverage run: pytest tests --cov=nitrostack --cov-report=term-missing --timeout=60 diff --git a/README.md b/README.md index 6074a49..01dcd2a 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,18 @@ pip install -e . ``` --- +### Security: eMudhra/emSign CA incident + +A [security incident](https://discuss.python.org/t/information-for-python-users-regarding-emudhra-emsign-ca-certificate-security-incident/109576) affecting eMudhra intermediate certificates means older packaging tools can be man-in-the-middled. Use at least: + +- pip 26.2.2 +- uv 0.13.4 +- certifi 2026.10.19 (this SDK now requires it) + +Upgrade pip and uv in existing virtual environments, refresh lockfiles (`uv lock --upgrade-package certifi`), and rebuild container images. The official `python:3.11` and `3.12` Docker images keep an older pip, so upgrade it with the hash-pinned command from the advisory. + +`nitrostack-py install` upgrades the pip in the project `.venv` to a hash-pinned 26.2.2 before installing anything, and refuses to run `uv` older than 0.13.4. + ## Scaffolding a New Project (Recommended) diff --git a/nitrostack/cli/install.py b/nitrostack/cli/install.py index 2bb09d3..ac8c64e 100644 --- a/nitrostack/cli/install.py +++ b/nitrostack/cli/install.py @@ -1,20 +1,29 @@ """Dependency installation wrapper for `nitrostack-py install`.""" from __future__ import annotations - import os import re import shutil import subprocess import sys -from typing import List, Optional - +from typing import List, Optional, Tuple from nitrostack.cli._shared import write_text_atomic _TRUE_TOKENS = frozenset({"1", "true", "yes", "on"}) _PEP503_KEEP = re.compile(r"[^A-Za-z0-9._-]+") _PEP503_DASH = re.compile(r"[-_.]+") +# eMudhra/emSign CA incident minimums (python.org advisory). +MIN_PIP_VERSION = (26, 2, 2) +MIN_UV_VERSION = (0, 13, 4) +# Hash-pinned wheel taken verbatim from the advisory. Do not edit by hand. +SECURE_PIP_SPEC = ( + "pip @ https://files.pythonhosted.org/packages/" + "3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/" + "pip-26.2.2-py3-none-any.whl" + "#sha256=fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70" +) + def _read(path: str) -> str: with open(path, "r", encoding="utf-8") as handle: @@ -115,8 +124,68 @@ def ensure_project_venv(root: str) -> str: return python +def _parse_version(text: str, tool: str) -> Optional[Tuple[int, int, int]]: + """Parse `pip 24.0 from ...` or `uv 0.13.4 (abc 2026-10-20)` into a tuple.""" + match = re.search(rf"\b{tool}\s+(\d+)\.(\d+)(?:\.(\d+))?", text or "") + if not match: + return None + major, minor, patch = match.groups() + return (int(major), int(minor), int(patch or 0)) + + +def _tool_version(cmd: List[str], tool: str) -> Optional[Tuple[int, int, int]]: + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + except OSError: + return None + if result.returncode != 0: + return None + return _parse_version(result.stdout, tool) + + +def _get_pip_version(python: str) -> Optional[Tuple[int, int, int]]: + return _tool_version([python, "-m", "pip", "--version"], "pip") + + +def _get_uv_version(uv: str) -> Optional[Tuple[int, int, int]]: + return _tool_version([uv, "--version"], "uv") + + +def _ensure_secure_pip(python: str, cwd: str) -> None: + """Make sure the venv's pip is >= 26.2.2 before it downloads anything. + + The venv pip is whatever the interpreter bundled, which can trust the + compromised emSign intermediates. The pinned wheel is verified by sha256, + so the bootstrap itself cannot be tampered with. + """ + version = _get_pip_version(python) + if version is not None and version >= MIN_PIP_VERSION: + return + print("Updating pip securely before installing dependencies (eMudhra/emSign advisory).") + result = subprocess.run([python, "-m", "pip", "install", SECURE_PIP_SPEC], cwd=cwd) + if result.returncode != 0: + raise RuntimeError( + "Secure pip upgrade failed. Upgrade pip using the python.org eMudhra/emSign " + "advisory instructions, then retry `nitrostack-py install`." + ) + version = _get_pip_version(python) + if version is None or version < MIN_PIP_VERSION: + raise RuntimeError( + "pip is still below 26.2.2 after the secure upgrade. " + "Upgrade pip manually, then retry `nitrostack-py install`." + ) + +def _check_uv_version(uv: str) -> None: + version = _get_uv_version(uv) + if version is None or version < MIN_UV_VERSION: + raise RuntimeError( + "uv 0.13.4 or later is required (eMudhra/emSign CA incident). " + "Upgrade uv (`uv self update` or reinstall) and retry." + ) + def _run_pip(args: List[str], cwd: str) -> None: python = ensure_project_venv(cwd) + _ensure_secure_pip(python, cwd) cmd = [python, "-m", "pip", "install", *args] print(f"Running: {' '.join(cmd)}") result = subprocess.run(cmd, cwd=cwd) @@ -131,6 +200,7 @@ def _run_uv(args: List[str], cwd: str) -> None: uv = _uv_bin() if not uv: raise RuntimeError("uv is not installed") + _check_uv_version(uv) cmd = [uv, *args] print(f"Running: {' '.join(cmd)}") result = subprocess.run(cmd, cwd=cwd) diff --git a/pyproject.toml b/pyproject.toml index 5b4a3b3..78c3fb8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,7 @@ dependencies = [ "watchfiles>=0.18.0", "anyio>=4.0.0", "packaging>=23.0.0", + "certifi>=2026.10.19", "tomli>=2.0.0; python_version < '3.11'", ] @@ -85,4 +86,4 @@ exclude_lines = [ "pragma: no cover", "if TYPE_CHECKING:", "if __name__ == .__main__.:", -] +] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index ebe86ba..982a4e3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,5 @@ uvicorn>=0.20.0 watchfiles>=0.18.0 anyio>=4.0.0 packaging>=23.0.0 +certifi>=2026.10.19 tomli>=2.0.0; python_version < "3.11" diff --git a/tests/test_cli_install.py b/tests/test_cli_install.py index 2088914..3d2b3c5 100644 --- a/tests/test_cli_install.py +++ b/tests/test_cli_install.py @@ -24,6 +24,9 @@ def _uv_absent(monkeypatch): """Keep the existing pip-path tests off a real uv binary on PATH.""" monkeypatch.setattr("nitrostack.cli.install._uv_bin", lambda: None) + # pip/uv version gates are covered in test_cli_install_security.py + monkeypatch.setattr("nitrostack.cli.install._ensure_secure_pip", lambda *a, **k: None) + monkeypatch.setattr("nitrostack.cli.install._check_uv_version", lambda *a, **k: None) def test_optional_extra_names_parses_pyproject(): diff --git a/tests/test_cli_install_security.py b/tests/test_cli_install_security.py new file mode 100644 index 0000000..2649b01 --- /dev/null +++ b/tests/test_cli_install_security.py @@ -0,0 +1,158 @@ +"""eMudhra/emSign remediation: secure pip bootstrap and uv version gate.""" +from __future__ import annotations + +import os +import sys +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from nitrostack.cli.install import ( # noqa: E402 + SECURE_PIP_SPEC, + _check_uv_version, + _ensure_secure_pip, + _get_pip_version, + _parse_version, + _run_pip, + _run_uv, +) + +MOD = "nitrostack.cli.install" + + +def _ok(stdout: str = "") -> SimpleNamespace: + return SimpleNamespace(returncode=0, stdout=stdout, stderr="") + + +def _fail() -> SimpleNamespace: + return SimpleNamespace(returncode=1, stdout="", stderr="") + + +# ---- version parsing ------------------------------------------------------ + +def test_parse_pip_two_and_three_part_versions(): + assert _parse_version("pip 24.0 from /x/pip (python 3.12)", "pip") == (24, 0, 0) + assert _parse_version("pip 26.2.2 from /x/pip (python 3.12)", "pip") == (26, 2, 2) + + +def test_parse_uv_version_with_build_suffix(): + assert _parse_version("uv 0.13.4 (abc123 2026-10-20)", "uv") == (0, 13, 4) + + +def test_parse_garbage_returns_none(): + assert _parse_version("command not found", "pip") is None + assert _parse_version("", "uv") is None + + +def test_get_pip_version_none_when_command_fails(): + with patch(f"{MOD}.subprocess.run", return_value=_fail()): + assert _get_pip_version("python") is None + + +def test_get_pip_version_none_when_python_missing(): + with patch(f"{MOD}.subprocess.run", side_effect=OSError("nope")): + assert _get_pip_version("python") is None + + +# ---- pip bootstrap -------------------------------------------------------- + +@pytest.mark.parametrize("version", [(26, 2, 2), (26, 3, 0), (27, 0, 0)]) +def test_pip_already_secure_skips_bootstrap(version, tmp_path): + with patch(f"{MOD}._get_pip_version", return_value=version): + with patch(f"{MOD}.subprocess.run") as run: + _ensure_secure_pip("python", str(tmp_path)) + run.assert_not_called() + + +def test_outdated_pip_is_upgraded_with_pinned_wheel(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[(24, 0, 0), (26, 2, 2)]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()) as run: + _ensure_secure_pip("python", str(tmp_path)) + run.assert_called_once() + assert run.call_args.args[0] == ["python", "-m", "pip", "install", SECURE_PIP_SPEC] + assert "#sha256=" in SECURE_PIP_SPEC + + +def test_unknown_pip_version_triggers_upgrade(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[None, (26, 2, 2)]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()) as run: + _ensure_secure_pip("python", str(tmp_path)) + run.assert_called_once() + + +def test_pip_upgrade_failure_raises_actionable_error(tmp_path): + with patch(f"{MOD}._get_pip_version", return_value=(24, 0, 0)): + with patch(f"{MOD}.subprocess.run", return_value=_fail()): + with pytest.raises(RuntimeError, match="Secure pip upgrade failed"): + _ensure_secure_pip("python", str(tmp_path)) + + +def test_pip_still_old_after_upgrade_raises(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[(24, 0, 0), (24, 0, 0)]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()): + with pytest.raises(RuntimeError, match="still below 26.2.2"): + _ensure_secure_pip("python", str(tmp_path)) + + +def test_pip_version_unverifiable_after_upgrade_raises(tmp_path): + with patch(f"{MOD}._get_pip_version", side_effect=[(24, 0, 0), None]): + with patch(f"{MOD}.subprocess.run", return_value=_ok()): + with pytest.raises(RuntimeError, match="still below 26.2.2"): + _ensure_secure_pip("python", str(tmp_path)) + + +def test_run_pip_stops_before_installing_when_bootstrap_fails(tmp_path): + with patch(f"{MOD}.ensure_project_venv", return_value="python"): + with patch(f"{MOD}._ensure_secure_pip", side_effect=RuntimeError("boom")): + with patch(f"{MOD}.subprocess.run") as run: + with pytest.raises(RuntimeError, match="boom"): + _run_pip(["-e", "."], cwd=str(tmp_path)) + run.assert_not_called() + + +def test_run_pip_bootstraps_before_installing(tmp_path): + order: list[str] = [] + with patch(f"{MOD}.ensure_project_venv", return_value="python"): + with patch(f"{MOD}._ensure_secure_pip", side_effect=lambda *a, **k: order.append("bootstrap")): + with patch( + f"{MOD}.subprocess.run", + side_effect=lambda *a, **k: order.append("install") or _ok(), + ): + _run_pip(["-e", "."], cwd=str(tmp_path)) + assert order == ["bootstrap", "install"] + + +# ---- uv gate -------------------------------------------------------------- + +@pytest.mark.parametrize("version", [(0, 13, 4), (0, 14, 0), (1, 0, 0)]) +def test_uv_meeting_minimum_is_allowed(version): + with patch(f"{MOD}._get_uv_version", return_value=version): + _check_uv_version("/usr/bin/uv") + + +@pytest.mark.parametrize("version", [(0, 13, 3), (0, 9, 0), None]) +def test_old_or_unknown_uv_is_blocked(version): + with patch(f"{MOD}._get_uv_version", return_value=version): + with pytest.raises(RuntimeError, match="0.13.4"): + _check_uv_version("/usr/bin/uv") + + +def test_run_uv_blocked_before_any_download(tmp_path): + with patch(f"{MOD}._uv_bin", return_value="/usr/bin/uv"): + with patch(f"{MOD}._get_uv_version", return_value=(0, 13, 3)): + with patch(f"{MOD}.subprocess.run") as run: + with pytest.raises(RuntimeError, match="uv 0.13.4"): + _run_uv(["sync"], cwd=str(tmp_path)) + run.assert_not_called() + + +def test_run_uv_runs_when_version_ok(tmp_path): + with patch(f"{MOD}._uv_bin", return_value="/usr/bin/uv"): + with patch(f"{MOD}._get_uv_version", return_value=(0, 13, 4)): + with patch(f"{MOD}.subprocess.run", return_value=_ok()) as run: + _run_uv(["sync"], cwd=str(tmp_path)) + run.assert_called_once() + assert run.call_args.args[0] == ["/usr/bin/uv", "sync"] \ No newline at end of file diff --git a/tests/test_security_config.py b/tests/test_security_config.py new file mode 100644 index 0000000..b172bbf --- /dev/null +++ b/tests/test_security_config.py @@ -0,0 +1,53 @@ +"""eMudhra/emSign remediation: lockfile, dependency floor and CI workflow guards.""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest +from packaging.version import Version + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from nitrostack.cli.install import SECURE_PIP_SPEC # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +MIN_CERTIFI = Version("2026.10.19") + + +def test_lock_resolves_fixed_certifi(): + data = tomllib.loads((ROOT / "uv.lock").read_text(encoding="utf-8")) + versions = [Version(p["version"]) for p in data["package"] if p["name"] == "certifi"] + assert versions, "certifi missing from uv.lock" + assert all(v >= MIN_CERTIFI for v in versions), versions + + +def test_pyproject_declares_certifi_floor(): + data = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8")) + assert "certifi>=2026.10.19" in data["project"]["dependencies"] + + +def test_requirements_declares_certifi_floor(): + lines = (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines() + assert "certifi>=2026.10.19" in [line.strip() for line in lines] + + +@pytest.mark.parametrize( + "name, later_command", + [ + ("test.yml", 'pip install -e ".[dev]"'), + ("publish.yml", "pip install -U build"), + ], +) +def test_workflow_bootstraps_secure_pip_before_other_installs(name, later_command): + text = (ROOT / ".github" / "workflows" / name).read_text(encoding="utf-8") + assert SECURE_PIP_SPEC in text, "workflow pip spec must match install.SECURE_PIP_SPEC" + assert 'python -m pip install --upgrade "certifi>=2026.10.19"' in text + assert "pip install --upgrade pip" not in text + assert text.index(SECURE_PIP_SPEC) < text.index(later_command) \ No newline at end of file diff --git a/uv.lock b/uv.lock index ed009ff..40b12e7 100644 --- a/uv.lock +++ b/uv.lock @@ -1,10 +1,10 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", - "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", + "python_full_version == '3.11.*' or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", "python_full_version < '3.11'", ] @@ -51,11 +51,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.7.22" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -390,7 +390,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -433,8 +433,8 @@ name = "httpcore2" version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, - { name = "truststore", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, + { name = "h11" }, + { name = "truststore" }, ] sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" } wheels = [ @@ -572,6 +572,7 @@ version = "0.3.2" source = { editable = "." } dependencies = [ { name = "anyio" }, + { name = "certifi" }, { name = "mcp" }, { name = "packaging" }, { name = "pydantic" }, @@ -586,18 +587,21 @@ dev = [ { name = "httpx" }, { name = "pytest" }, { name = "pytest-cov" }, + { name = "pytest-timeout" }, { name = "tox" }, ] [package.metadata] requires-dist = [ { name = "anyio", specifier = ">=4.0.0" }, + { name = "certifi", specifier = ">=2026.10.19" }, { name = "httpx", marker = "extra == 'dev'", specifier = ">=0.27.0" }, { name = "mcp", specifier = ">=2,<3" }, { name = "packaging", specifier = ">=23.0.0" }, { name = "pydantic", specifier = ">=2.0.0" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.4.0" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.1.0" }, + { name = "pytest-timeout", marker = "extra == 'dev'", specifier = ">=2.3.0" }, { name = "starlette", specifier = ">=0.30.0" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.0" }, { name = "tox", marker = "extra == 'dev'", specifier = ">=4.0.0" }, @@ -856,6 +860,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, ] +[[package]] +name = "pytest-timeout" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/82/4c9ecabab13363e72d880f2fb504c5f750433b2b6f16e99f4ec21ada284c/pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a", size = 17973, upload-time = "2025-05-05T19:44:34.99Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/b6/3127540ecdf1464a00e5a01ee60a1b09175f6913f0644ac748494d9c4b21/pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2", size = 14382, upload-time = "2025-05-05T19:44:33.502Z" }, +] + [[package]] name = "python-discovery" version = "1.6.0" @@ -1049,7 +1065,7 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", - "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", + "python_full_version == '3.11.*' or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } wheels = [ From da07f89b7926be15c6ec6f021e2c1348a9c168ca Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sat, 24 Oct 2026 16:28:41 +0530 Subject: [PATCH 009/146] test: add baseline catalog, package marker and fixture for transform parity test (#61) --- tests/__init__.py | 0 tests/_baseline_catalog.py | 26 ++++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/_baseline_catalog.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/_baseline_catalog.py b/tests/_baseline_catalog.py new file mode 100644 index 0000000..3092d9f --- /dev/null +++ b/tests/_baseline_catalog.py @@ -0,0 +1,26 @@ +"""Catalog used by both the baseline capture script and the parity test.""" +from pydantic import BaseModel + +from nitrostack import ExecutionContext, injectable, module, tool + +ERAS = ("legacy", "auto", "modern") + + +class In(BaseModel): + q: str = "" + + +@injectable() +class C: + @tool(name="alpha", description="first", input_schema=In) + async def alpha(self, input: In, context: ExecutionContext) -> str: + return "a" + + @tool(name="beta", description="second", input_schema=In) + async def beta(self, input: In, context: ExecutionContext) -> str: + return "b" + + +@module(name="m", controllers=[C]) +class M: + pass \ No newline at end of file From 0468fe5c507106437cce1f0f48daded064e3062a Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sat, 24 Oct 2026 16:37:03 +0530 Subject: [PATCH 010/146] build: add pytest-asyncio to dev extras for transform tests (#61) --- pyproject.toml | 3 ++- uv.lock | 53 +++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5b4a3b3..cfb3513 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,8 +21,9 @@ dependencies = [ [project.optional-dependencies] dev = [ - "pytest>=7.4.0", "pytest-cov>=4.1.0", + "pytest>=8", + "pytest-asyncio>=0.23", "pytest-timeout>=2.3.0", "httpx>=0.27.0", "tox>=4.0.0", diff --git a/uv.lock b/uv.lock index ed009ff..a000f51 100644 --- a/uv.lock +++ b/uv.lock @@ -1,10 +1,10 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", - "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", + "python_full_version == '3.11.*' or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", "python_full_version < '3.11'", ] @@ -40,6 +40,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] +[[package]] +name = "backports-asyncio-runner" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8e/ff/70dca7d7cb1cbc0edb2c6cc0c38b65cba36cccc491eca64cabd5fe7f8670/backports_asyncio_runner-1.2.0.tar.gz", hash = "sha256:a5aa7b2b7d8f8bfcaa2b57313f70792df84e32a2a746f585213373f900b42162", size = 69893, upload-time = "2025-07-02T02:27:15.685Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/59/76ab57e3fe74484f48a53f8e337171b4a2349e506eabe136d7e01d059086/backports_asyncio_runner-1.2.0-py3-none-any.whl", hash = "sha256:0da0a936a8aeb554eccb426dc55af3ba63bcdc69fa1a600b5bb305413a4477b5", size = 12313, upload-time = "2025-07-02T02:27:14.263Z" }, +] + [[package]] name = "cachetools" version = "7.1.8" @@ -390,7 +399,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -433,8 +442,8 @@ name = "httpcore2" version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, - { name = "truststore", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, + { name = "h11" }, + { name = "truststore" }, ] sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" } wheels = [ @@ -585,7 +594,9 @@ dependencies = [ dev = [ { name = "httpx" }, { name = "pytest" }, + { name = "pytest-asyncio" }, { name = "pytest-cov" }, + { name = "pytest-timeout" }, { name = "tox" }, ] @@ -596,8 +607,10 @@ requires-dist = [ { name = "mcp", specifier = ">=2,<3" }, { name = "packaging", specifier = ">=23.0.0" }, { name = "pydantic", specifier = ">=2.0.0" }, - { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.4.0" }, + { name = "pytest", marker = "extra == 'dev'", specifier = ">=8" }, + { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.23" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.1.0" }, + { name = "pytest-timeout", marker = "extra == 'dev'", specifier = ">=2.3.0" }, { name = "starlette", specifier = ">=0.30.0" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.0" }, { name = "tox", marker = "extra == 'dev'", specifier = ">=4.0.0" }, @@ -842,6 +855,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] +[[package]] +name = "pytest-asyncio" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "backports-asyncio-runner", marker = "python_full_version < '3.11'" }, + { name = "pytest" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, +] + [[package]] name = "pytest-cov" version = "7.1.0" @@ -856,6 +883,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, ] +[[package]] +name = "pytest-timeout" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/82/4c9ecabab13363e72d880f2fb504c5f750433b2b6f16e99f4ec21ada284c/pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a", size = 17973, upload-time = "2025-05-05T19:44:34.99Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/b6/3127540ecdf1464a00e5a01ee60a1b09175f6913f0644ac748494d9c4b21/pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2", size = 14382, upload-time = "2025-05-05T19:44:33.502Z" }, +] + [[package]] name = "python-discovery" version = "1.6.0" @@ -1049,7 +1088,7 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", - "(python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')", + "python_full_version == '3.11.*' or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } wheels = [ From 61480e040fa6919a2b9be032101157c5893127fb Mon Sep 17 00:00:00 2001 From: Shreyavemana <128345703+Shreyavemana@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:45:35 +0530 Subject: [PATCH 011/146] Update test_security_config.py --- tests/test_security_config.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_security_config.py b/tests/test_security_config.py index b172bbf..65d1621 100644 --- a/tests/test_security_config.py +++ b/tests/test_security_config.py @@ -42,12 +42,12 @@ def test_requirements_declares_certifi_floor(): "name, later_command", [ ("test.yml", 'pip install -e ".[dev]"'), - ("publish.yml", "pip install -U build"), ], ) + def test_workflow_bootstraps_secure_pip_before_other_installs(name, later_command): text = (ROOT / ".github" / "workflows" / name).read_text(encoding="utf-8") assert SECURE_PIP_SPEC in text, "workflow pip spec must match install.SECURE_PIP_SPEC" assert 'python -m pip install --upgrade "certifi>=2026.10.19"' in text assert "pip install --upgrade pip" not in text - assert text.index(SECURE_PIP_SPEC) < text.index(later_command) \ No newline at end of file + assert text.index(SECURE_PIP_SPEC) < text.index(later_command) From 0c59e9d0736d0bf335fbc53bb99c68d8a45e8184 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sun, 25 Oct 2026 16:25:32 +0530 Subject: [PATCH 012/146] feat(transforms): add SyntheticTool and run it from _invoke_tool (#62) --- nitrostack/core/app.py | 70 ++++++++- nitrostack/transforms/__init__.py | 3 +- nitrostack/transforms/search/__init__.py | 12 ++ nitrostack/transforms/search/base.py | 160 ++++++++++++++++++++ nitrostack/transforms/search/models.py | 43 ++++++ nitrostack/transforms/search/regex.py | 68 +++++++++ nitrostack/transforms/search/regex_match.py | 63 ++++++++ nitrostack/transforms/search/serializer.py | 95 ++++++++++++ nitrostack/transforms/synthetic.py | 35 +++++ tests/test_transforms_search.py | 0 tests/test_transforms_search_app.py | 0 11 files changed, 541 insertions(+), 8 deletions(-) create mode 100644 nitrostack/transforms/search/__init__.py create mode 100644 nitrostack/transforms/search/base.py create mode 100644 nitrostack/transforms/search/models.py create mode 100644 nitrostack/transforms/search/regex.py create mode 100644 nitrostack/transforms/search/regex_match.py create mode 100644 nitrostack/transforms/search/serializer.py create mode 100644 nitrostack/transforms/synthetic.py create mode 100644 tests/test_transforms_search.py create mode 100644 tests/test_transforms_search_app.py diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index 222ddc5..ed372f2 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -10,7 +10,9 @@ from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Pattern, Set, Tuple, Type - +from nitrostack.transforms import ( + SyntheticTool, ToolArgumentError, TransformContext, validate_tool_arguments, +) import mcp.types as types from mcp import MCPError from mcp.server.context import ServerRequestContext @@ -608,17 +610,19 @@ def __init__(self, app_class: Type): self.task_manager = TaskManager() self._in_flight = InFlightRegistry() - self._bootstrap() - - # Initialize the transform pipeline - # Initialize transforms before registering handlers. Handlers use - # this pipeline when tools/list is requested. + # Pipeline first: handlers consult it lazily when requests arrive. self._transforms = TransformPipeline( getattr(self.app_class, "_mcp_transforms", None) or [] ) self._bootstrap() + # Tools are registered now, so transforms can see the catalog. + self._transforms.register(TransformRegistry(self._base_tool_list)) + + def _base_tool_list(self) -> List[types.Tool]: + return [self._build_tool_definition(entry) for entry in self._tools.values()] + def _bootstrap(self) -> None: # 1. Construct the low-level server directly. self.mcp_server = NitroStackMcpServer( @@ -1205,6 +1209,12 @@ def _pipeline_stages(self, method: Callable) -> Tuple[List[Type], List[Type], Li getattr(method, "_mcp_pipes", []), getattr(method, "_mcp_filters", []), ) + def _base_lookup(self, name: str): + return self._tools.get(name) + + async def _invoke_for_transform(self, name: str, arguments: dict, tctx: TransformContext): + # Re-enter the normal call path so guards and validation run for the real tool. + return await self._call_tool(name, arguments, _tctx=tctx) def _to_call_tool_result( self, @@ -1273,6 +1283,52 @@ def _to_call_tool_result( isError=False, ) + async def _call_tool( + self, + name: str, + arguments: Dict[str, Any], + task: Any = None, + _tctx: Optional[TransformContext] = None, + ): + """Resolve through the transform pipeline, then run the real tool path.""" + if not self._transforms.enabled: + return await self._call_real_tool(name, arguments, task=task) + + tctx = _tctx or TransformContext(_invoker=self._invoke_for_transform) + try: + resolved = await self._transforms.resolve_tool(name, self._base_lookup, tctx) + except Exception as exc: + logger.exception("Transform failed resolving tool %s", name) + return types.CallToolResult( + content=[types.TextContent(type="text", text=str(exc))], isError=True + ) + + if isinstance(resolved, SyntheticTool): + payload = arguments or {} + inner = payload.get("input") + if ( + isinstance(inner, dict) + and set(payload) <= {"input"} + and "input" not in resolved.input_model.model_fields + ): + payload = inner # accept the older {"input": {...}} wrap + try: + validated = validate_tool_arguments(resolved.name, resolved.input_model, payload) + result = await resolved.handler(validated, tctx) + except ToolArgumentError as exc: + return types.CallToolResult( + content=[types.TextContent(type="text", text=f"{exc}: {exc.errors}")], + isError=True, + ) + except Exception as exc: + logger.exception("Synthetic tool %s failed", name) + return types.CallToolResult( + content=[types.TextContent(type="text", text=str(exc))], isError=True + ) + return self._to_call_tool_result(result) + + return await self._call_real_tool(name, arguments, task=task) + @staticmethod def _call_tool_result_meta(result: types.CallToolResult) -> Optional[Dict[str, Any]]: """Read caller ``_meta`` from the field or pydantic extra (alias vs extra).""" @@ -1320,7 +1376,7 @@ def _widget_result_content(self, structured: Dict[str, Any], component: Optional ) return content - async def _call_tool(self, name: str, arguments: Dict[str, Any], task: Any = None): + async def _call_real_tool(self, name: str, arguments: Dict[str, Any], task: Any = None): entry = self._tools.get(name) if entry is None: return types.CallToolResult( diff --git a/nitrostack/transforms/__init__.py b/nitrostack/transforms/__init__.py index 667e7d7..a97d8c4 100644 --- a/nitrostack/transforms/__init__.py +++ b/nitrostack/transforms/__init__.py @@ -12,9 +12,10 @@ TransformRegistry, ) from nitrostack.transforms.validation import ToolArgumentError, validate_tool_arguments +from nitrostack.transforms.synthetic import SyntheticTool __all__ = [ "CatalogTransform", "McpTransform", "McpTransformBase", "TransformContext", "TransformError", "TransformPipeline", "TransformRegistry", - "ToolArgumentError", "validate_tool_arguments", "active_bypass", "bypassing", + "ToolArgumentError", "validate_tool_arguments", "active_bypass", "bypassing", "SyntheticTool", ] \ No newline at end of file diff --git a/nitrostack/transforms/search/__init__.py b/nitrostack/transforms/search/__init__.py new file mode 100644 index 0000000..0779c25 --- /dev/null +++ b/nitrostack/transforms/search/__init__.py @@ -0,0 +1,12 @@ +from nitrostack.transforms.search.base import BaseSearchTransform, is_browse_query +from nitrostack.transforms.search.models import ( + BROWSE_MAX_RESULTS, DEFAULT_SEARCH_LIMIT, MAX_SEARCH_RESULTS, + CallToolInput, RankOutcome, SearchToolsInput, +) +from nitrostack.transforms.search.regex import RegexSearchTransform + +__all__ = [ + "BaseSearchTransform", "RegexSearchTransform", "RankOutcome", + "SearchToolsInput", "CallToolInput", "is_browse_query", + "MAX_SEARCH_RESULTS", "DEFAULT_SEARCH_LIMIT", "BROWSE_MAX_RESULTS", +] \ No newline at end of file diff --git a/nitrostack/transforms/search/base.py b/nitrostack/transforms/search/base.py new file mode 100644 index 0000000..050ee28 --- /dev/null +++ b/nitrostack/transforms/search/base.py @@ -0,0 +1,160 @@ +"""Shared behavior for search transforms: two meta-tools, browse mode, limits, dispatch.""" +from __future__ import annotations + +import logging +import re +from abc import abstractmethod +from typing import Any, Dict, Iterable, List, Optional, Sequence + +from nitrostack.transforms.search.models import ( + BROWSE_MAX_RESULTS, MAX_SEARCH_RESULTS, CallToolInput, RankOutcome, SearchToolsInput, +) +from nitrostack.transforms.search.serializer import is_always_visible, serialize_tool +from nitrostack.transforms.synthetic import SyntheticTool +from nitrostack.transforms.transform import ( + CatalogTransform, NextResolver, TransformContext, +) +from nitrostack.transforms.validation import ToolArgumentError + +logger = logging.getLogger(__name__) + +# Words that name no task. A query made only of these (or empty) lists the catalog. +_BROWSE_WORDS = frozenset({ + "the", "all", "show", "list", "me", "tools", "tool", "available", "catalog", + "everything", "please", "what", "do", "you", "have", "browse", +}) +_PLAIN_QUERY = re.compile(r"[\w\s]+") + + +def is_browse_query(query: str) -> bool: + q = (query or "").strip() + if not q: + return True + if not _PLAIN_QUERY.fullmatch(q): + return False # has punctuation or regex syntax: it is a real search + return all(tok in _BROWSE_WORDS for tok in q.casefold().split()) + + +class BaseSearchTransform(CatalogTransform): + """Replaces the catalog with ``search_tools`` and ``call_tool`` (plus always-visible tools).""" + + name = "search" + + def __init__( + self, + *, + name: Optional[str] = None, + search_tool_name: str = "search_tools", + call_tool_name: str = "call_tool", + always_visible: Iterable[str] = (), + ) -> None: + if name: + self.name = name + if not search_tool_name or not call_tool_name or search_tool_name == call_tool_name: + raise ValueError("search_tool_name and call_tool_name must be non-empty and different.") + self.search_tool_name = search_tool_name + self.call_tool_name = call_tool_name + self.always_visible = frozenset(always_visible) + self._registry: Any = None + self._synthetic: Dict[str, SyntheticTool] = { + search_tool_name: SyntheticTool( + name=search_tool_name, + description=( + "Find tools by what they do. Returns matching tool names with their " + "parameters. Use call_tool to run one. An empty query lists the catalog." + ), + input_model=SearchToolsInput, + handler=self._handle_search, + read_only=True, + ), + call_tool_name: SyntheticTool( + name=call_tool_name, + description="Run a tool found with search_tools, by exact name, with its arguments.", + input_model=CallToolInput, + handler=self._handle_call, + ), + } + + # ---- lifecycle ------------------------------------------------------- + + def on_register(self, registry: Any) -> None: + self._registry = registry + + def synthetic_tools(self) -> List[SyntheticTool]: + return list(self._synthetic.values()) + + # ---- catalog hooks --------------------------------------------------- + + def apply_transform(self, tools: Sequence[Any], ctx: TransformContext) -> List[Any]: + visible = [] + for tool in tools: + if tool.name in self._synthetic: + logger.warning("Real tool %r is shadowed by the %s meta-tool.", tool.name, self.name) + continue + if is_always_visible(tool, self.always_visible): + visible.append(tool) + return [s.to_mcp_tool() for s in self._synthetic.values()] + visible + + async def resolve_tool(self, name: str, next: NextResolver, ctx: TransformContext) -> Optional[Any]: + if name in self._synthetic: + return self._synthetic[name] + return await next(name) + + # ---- ranking (subclasses) ------------------------------------------- + + @abstractmethod + async def rank(self, query: str, tools: Sequence[Any]) -> RankOutcome: + """Return matching tools, best first. Must not raise for a bad query.""" + + # ---- handlers -------------------------------------------------------- + + def _catalog(self) -> List[Any]: + if self._registry is None: + return [] + tools = [t for t in self._registry.list_tools() if t.name not in self._synthetic] + return sorted(tools, key=lambda t: t.name) + + async def _handle_search(self, args: SearchToolsInput, ctx: TransformContext) -> Dict[str, Any]: + catalog = self._catalog() + notes: List[str] = [] + + if is_browse_query(args.query): + shown = catalog[:BROWSE_MAX_RESULTS] + if len(catalog) > len(shown): + notes.append(f"Showing the first {len(shown)} of {len(catalog)} tools; search to narrow down.") + return { + "mode": "browse", + "total_tools": len(catalog), + "results": [serialize_tool(t, "brief") for t in shown], + "note": " ".join(notes) or None, + } + + limit = args.limit + if limit > MAX_SEARCH_RESULTS: + notes.append(f"limit was reduced from {limit} to {MAX_SEARCH_RESULTS}.") + limit = MAX_SEARCH_RESULTS + + outcome = await self.rank(args.query, catalog) + if outcome.note: + notes.append(outcome.note) + top = outcome.ranked[:limit] + if not top: + notes.append("No tools matched. Try fewer words, or search with an empty query to browse.") + return { + "mode": "search", + "query": args.query, + "total_tools": len(catalog), + "results": [serialize_tool(tool, args.detail) for tool, _score in top], + "note": " ".join(notes) or None, + } + + async def _handle_call(self, args: CallToolInput, ctx: TransformContext) -> Any: + target = args.name.strip() + if target in self._synthetic: + raise ToolArgumentError( + self.call_tool_name, + [{"loc": ["name"], "msg": f"'{target}' is a discovery tool and cannot be called through {self.call_tool_name}."}], + ) + # Goes back through the pipeline: guards and argument validation run for the real tool, + # and this transform is skipped for the nested call. + return await ctx.call_tool(target, args.arguments, caller=self.name) \ No newline at end of file diff --git a/nitrostack/transforms/search/models.py b/nitrostack/transforms/search/models.py new file mode 100644 index 0000000..da80d44 --- /dev/null +++ b/nitrostack/transforms/search/models.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Literal, Optional, Tuple + +from pydantic import BaseModel, Field + +MAX_SEARCH_RESULTS = 20 +DEFAULT_SEARCH_LIMIT = 5 +BROWSE_MAX_RESULTS = 100 + +DetailLevel = Literal["brief", "detailed", "full"] + + +class SearchToolsInput(BaseModel): + query: str = Field( + default="", + description="What you want to do, or part of a tool name. Leave empty to browse the catalog.", + ) + limit: int = Field( + default=DEFAULT_SEARCH_LIMIT, + ge=1, + description=f"Maximum results. Values above {MAX_SEARCH_RESULTS} are reduced to {MAX_SEARCH_RESULTS}.", + ) + detail: DetailLevel = Field( + default="detailed", + description="'brief' = name and one line, 'detailed' = parameters, 'full' = complete schema.", + ) + + +class CallToolInput(BaseModel): + name: str = Field(min_length=1, description="Exact name of the tool to run, as returned by search_tools.") + arguments: Dict[str, Any] = Field( + default_factory=dict, description="Arguments for that tool, matching its input schema." + ) + + +@dataclass +class RankOutcome: + """Result of ranking: (tool, score) pairs, best first, plus an optional explanation.""" + + ranked: List[Tuple[Any, float]] = field(default_factory=list) + note: Optional[str] = None \ No newline at end of file diff --git a/nitrostack/transforms/search/regex.py b/nitrostack/transforms/search/regex.py new file mode 100644 index 0000000..0b8385b --- /dev/null +++ b/nitrostack/transforms/search/regex.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import Any, List, Optional, Sequence, Tuple + +from nitrostack.transforms.search.base import BaseSearchTransform +from nitrostack.transforms.search.models import RankOutcome +from nitrostack.transforms.search.regex_match import run_regex +from nitrostack.transforms.search.serializer import FIELD_WEIGHTS, tool_fields + +_N_FIELDS = len(FIELD_WEIGHTS) + + +class RegexSearchTransform(BaseSearchTransform): + """Literal, case-insensitive substring search. Optionally treats the query as a regex. + + The regex runs in a child process with a timeout. A timeout, an invalid pattern, + or a failure to start the worker falls back to a literal match with a note. + """ + + name = "regex_search" + + def __init__( + self, + *, + allow_regex: bool = False, + regex_timeout: float = 2.0, + max_pattern_length: int = 200, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if regex_timeout <= 0: + raise ValueError("regex_timeout must be positive.") + self.allow_regex = allow_regex + self.regex_timeout = regex_timeout + self.max_pattern_length = max_pattern_length + + async def rank(self, query: str, tools: Sequence[Any]) -> RankOutcome: + q = query.strip() + texts: List[str] = [] + for tool in tools: + texts.extend(tool_fields(tool)) + + hits: Optional[set] = None + note: Optional[str] = None + + if self.allow_regex: + if len(q) > self.max_pattern_length: + note = f"Pattern longer than {self.max_pattern_length} characters; used a literal match." + else: + outcome = await run_regex(q, texts, self.regex_timeout) + if outcome.hits is not None: + hits = outcome.hits + else: + note = f"Regex not used: {outcome.reason}. Used a literal match." + + if hits is None: + needle = q.casefold() + hits = {i for i, text in enumerate(texts) if needle in text.casefold()} + + scored: List[Tuple[Any, float]] = [] + for index, tool in enumerate(tools): + score = sum( + FIELD_WEIGHTS[f] for f in range(_N_FIELDS) if (index * _N_FIELDS + f) in hits + ) + if score > 0: + scored.append((tool, score)) + scored.sort(key=lambda pair: (-pair[1], pair[0].name)) # equal scores: by name + return RankOutcome(ranked=scored, note=note) \ No newline at end of file diff --git a/nitrostack/transforms/search/regex_match.py b/nitrostack/transforms/search/regex_match.py new file mode 100644 index 0000000..79ffa3e --- /dev/null +++ b/nitrostack/transforms/search/regex_match.py @@ -0,0 +1,63 @@ +"""Run a user-supplied regex with a hard time limit, without blocking the event loop. + +Python's `re` cannot be interrupted, so the match runs in a short-lived child +interpreter that is killed on timeout. The child imports only the standard library. +""" +from __future__ import annotations + +import asyncio +import json +import sys +from dataclasses import dataclass +from typing import Optional, Sequence, Set + +_CHILD = r""" +import json, re, sys +req = json.load(sys.stdin) +try: + rx = re.compile(req["pattern"], re.IGNORECASE) +except re.error as exc: + print(json.dumps({"status": "invalid", "detail": str(exc)})) + sys.exit(0) +hits = [i for i, t in enumerate(req["texts"]) if rx.search(t)] +print(json.dumps({"status": "ok", "hits": hits})) +""" + + +@dataclass +class RegexOutcome: + hits: Optional[Set[int]] # None means "could not use the regex" + reason: Optional[str] = None # why, when hits is None + + +async def run_regex(pattern: str, texts: Sequence[str], timeout: float) -> RegexOutcome: + payload = json.dumps({"pattern": pattern, "texts": list(texts)}).encode("utf-8") + try: + proc = await asyncio.create_subprocess_exec( + sys.executable, "-I", "-c", _CHILD, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + except (NotImplementedError, OSError) as exc: + return RegexOutcome(None, f"regex worker could not start ({type(exc).__name__})") + + try: + out, _ = await asyncio.wait_for(proc.communicate(payload), timeout=timeout) + except asyncio.TimeoutError: + return RegexOutcome(None, f"timed out after {timeout:g}s") + finally: + if proc.returncode is None: + try: + proc.kill() + except ProcessLookupError: + pass + await proc.wait() + + try: + data = json.loads(out.decode("utf-8")) + except (ValueError, UnicodeDecodeError): + return RegexOutcome(None, "regex worker returned no result") + if data.get("status") == "invalid": + return RegexOutcome(None, f"invalid pattern ({data.get('detail', 'syntax error')})") + return RegexOutcome(set(data.get("hits", []))) \ No newline at end of file diff --git a/nitrostack/transforms/search/serializer.py b/nitrostack/transforms/search/serializer.py new file mode 100644 index 0000000..793b5d5 --- /dev/null +++ b/nitrostack/transforms/search/serializer.py @@ -0,0 +1,95 @@ +"""Turns tool definitions into search results at three detail levels.""" +from __future__ import annotations + +from typing import Any, Dict, Iterable, List, Tuple + +from nitrostack.transforms.search.models import DetailLevel + +ALWAYS_VISIBLE_META_KEYS = ("alwaysVisible", "nitrostack/alwaysVisible") + + +def _props(tool: Any) -> Dict[str, Any]: + schema = getattr(tool, "inputSchema", None) or {} + props = schema.get("properties") if isinstance(schema, dict) else None + return props if isinstance(props, dict) else {} + + +def _type_label(prop: Any) -> str: + if not isinstance(prop, dict): + return "any" + t = prop.get("type") + if isinstance(t, list): + return "|".join(str(x) for x in t) + if t: + return str(t) + any_of = prop.get("anyOf") + if isinstance(any_of, list): + return "|".join(str(s.get("type", "any")) for s in any_of if isinstance(s, dict)) or "any" + return "any" + + +def param_text(tool: Any) -> str: + parts: List[str] = [] + for name, prop in _props(tool).items(): + parts.append(str(name)) + if isinstance(prop, dict) and prop.get("description"): + parts.append(str(prop["description"])) + return " ".join(parts) + + +def tool_fields(tool: Any) -> Tuple[str, str, str, str]: + """(name, title, description, parameter text). Order matches FIELD_WEIGHTS.""" + return ( + getattr(tool, "name", "") or "", + getattr(tool, "title", None) or "", + getattr(tool, "description", None) or "", + param_text(tool), + ) + + +# A name match outranks a title match, which outranks description, then parameters. +FIELD_WEIGHTS = (4.0, 3.0, 2.0, 1.0) + + +def first_sentence(text: str, max_len: int = 160) -> str: + text = (text or "").strip() + if not text: + return "" + head = text.split(". ")[0].strip() + return head if len(head) <= max_len else head[: max_len - 1].rstrip() + "…" + + +def is_always_visible(tool: Any, names: Iterable[str]) -> bool: + # UNVERIFIED: how @tool(metadata=...) lands on the mcp Tool. Check `tool.meta` first. + if getattr(tool, "name", None) in set(names): + return True + meta = getattr(tool, "meta", None) + if isinstance(meta, dict): + return any(bool(meta.get(k)) for k in ALWAYS_VISIBLE_META_KEYS) + return False + + +def serialize_tool(tool: Any, detail: DetailLevel) -> Dict[str, Any]: + name = getattr(tool, "name", "") + description = getattr(tool, "description", None) or "" + if detail == "brief": + return {"name": name, "summary": first_sentence(description)} + if detail == "full": + return tool.model_dump(by_alias=True, exclude_none=True, mode="json") + + schema = getattr(tool, "inputSchema", None) or {} + required = set(schema.get("required", [])) if isinstance(schema, dict) else set() + out: Dict[str, Any] = {"name": name, "description": description} + title = getattr(tool, "title", None) + if title: + out["title"] = title + out["parameters"] = [ + { + "name": pname, + "type": _type_label(prop), + "required": pname in required, + "description": prop.get("description", "") if isinstance(prop, dict) else "", + } + for pname, prop in _props(tool).items() + ] + return out \ No newline at end of file diff --git a/nitrostack/transforms/synthetic.py b/nitrostack/transforms/synthetic.py new file mode 100644 index 0000000..3e259f4 --- /dev/null +++ b/nitrostack/transforms/synthetic.py @@ -0,0 +1,35 @@ +"""A tool that exists only in a transform, not in the registry.""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Type + +import mcp.types as types +from pydantic import BaseModel + +from nitrostack.protocol.schema import normalize_input_schema + +if TYPE_CHECKING: + from nitrostack.transforms.transform import TransformContext + +# The handler receives the VALIDATED input model instance and the transform context. +SyntheticHandler = Callable[[Any, "TransformContext"], Awaitable[Any]] + + +@dataclass(frozen=True) +class SyntheticTool: + name: str + description: str + input_model: Type[BaseModel] + handler: SyntheticHandler + read_only: bool = False + + def to_mcp_tool(self) -> types.Tool: + schema = normalize_input_schema(self.input_model.model_json_schema()) + annotations = types.ToolAnnotations(readOnlyHint=True) if self.read_only else None + return types.Tool( + name=self.name, + description=self.description, + inputSchema=schema, + annotations=annotations, + ) \ No newline at end of file diff --git a/tests/test_transforms_search.py b/tests/test_transforms_search.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_transforms_search_app.py b/tests/test_transforms_search_app.py new file mode 100644 index 0000000..e69de29 From 36e9e82c9d654ff8b5c24cc1cfc071c51cdce997 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sun, 25 Oct 2026 16:27:30 +0530 Subject: [PATCH 013/146] feat(transforms): add BaseSearchTransform and RegexSearchTransform (#62) --- nitrostack/transforms/search/serializer.py | 44 ++++++++++++++++++---- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/nitrostack/transforms/search/serializer.py b/nitrostack/transforms/search/serializer.py index 793b5d5..d06059f 100644 --- a/nitrostack/transforms/search/serializer.py +++ b/nitrostack/transforms/search/serializer.py @@ -1,4 +1,6 @@ + """Turns tool definitions into search results at three detail levels.""" + from __future__ import annotations from typing import Any, Dict, Iterable, List, Tuple @@ -8,9 +10,16 @@ ALWAYS_VISIBLE_META_KEYS = ("alwaysVisible", "nitrostack/alwaysVisible") +def _schema(tool: Any) -> Dict[str, Any]: + for attr in ("inputSchema", "input_schema"): + value = getattr(tool, attr, None) + if isinstance(value, dict): + return value + return {} + + def _props(tool: Any) -> Dict[str, Any]: - schema = getattr(tool, "inputSchema", None) or {} - props = schema.get("properties") if isinstance(schema, dict) else None + props = _schema(tool).get("properties") return props if isinstance(props, dict) else {} @@ -24,7 +33,14 @@ def _type_label(prop: Any) -> str: return str(t) any_of = prop.get("anyOf") if isinstance(any_of, list): - return "|".join(str(s.get("type", "any")) for s in any_of if isinstance(s, dict)) or "any" + return ( + "|".join( + str(s.get("type", "any")) + for s in any_of + if isinstance(s, dict) + ) + or "any" + ) return "any" @@ -72,24 +88,36 @@ def is_always_visible(tool: Any, names: Iterable[str]) -> bool: def serialize_tool(tool: Any, detail: DetailLevel) -> Dict[str, Any]: name = getattr(tool, "name", "") description = getattr(tool, "description", None) or "" + if detail == "brief": return {"name": name, "summary": first_sentence(description)} + if detail == "full": - return tool.model_dump(by_alias=True, exclude_none=True, mode="json") + return tool.model_dump( + by_alias=True, + exclude_none=True, + mode="json", + ) + + schema = _schema(tool) + required = set(schema.get("required", [])) - schema = getattr(tool, "inputSchema", None) or {} - required = set(schema.get("required", [])) if isinstance(schema, dict) else set() out: Dict[str, Any] = {"name": name, "description": description} title = getattr(tool, "title", None) if title: out["title"] = title + out["parameters"] = [ { "name": pname, "type": _type_label(prop), "required": pname in required, - "description": prop.get("description", "") if isinstance(prop, dict) else "", + "description": ( + prop.get("description", "") + if isinstance(prop, dict) + else "" + ), } for pname, prop in _props(tool).items() ] - return out \ No newline at end of file + return out From 12d949b38702172b2de9f59b813ee95d384c4409 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sun, 25 Oct 2026 16:27:48 +0530 Subject: [PATCH 014/146] test(transforms): progressive discovery, regex timeout, call_tool dispatch (#62) --- tests/test_transforms_search.py | 227 ++++++++++++++++++++++++++++ tests/test_transforms_search_app.py | 81 ++++++++++ 2 files changed, 308 insertions(+) diff --git a/tests/test_transforms_search.py b/tests/test_transforms_search.py index e69de29..24334b3 100644 --- a/tests/test_transforms_search.py +++ b/tests/test_transforms_search.py @@ -0,0 +1,227 @@ +import asyncio +import time + +import mcp.types as types +import pytest + +from nitrostack.transforms import TransformContext +from nitrostack.transforms.search import ( + CallToolInput, RegexSearchTransform, SearchToolsInput, is_browse_query, +) +from nitrostack.transforms.validation import ToolArgumentError + + +def run(coro): + return asyncio.run(coro) + + +def make_tool(name, description="", props=None, meta=None): + schema = {"type": "object", "properties": props or {}} + return types.Tool(name=name, description=description, inputSchema=schema, _meta=meta) + + +class FakeRegistry: + def __init__(self, tools): + self._tools = tools + + def list_tools(self): + return list(self._tools) + + +class FakeCtx(TransformContext): + def __init__(self): + super().__init__() + self.calls = [] + + async def call_tool(self, name, arguments=None, *, caller=None): + self.calls.append((name, arguments, caller)) + return {"ok": True} + + +def registered(transform, tools): + transform.on_register(FakeRegistry(tools)) + return transform + + +async def search(transform, **kw): + ctx = TransformContext() + tool = await transform.resolve_tool(transform.search_tool_name, _none, ctx) + return await tool.handler(SearchToolsInput(**kw), ctx) + + +async def _none(name): + return None + + +CATALOG = [ + make_tool("get_user", "Look up a user by id. Returns a profile.", {"user_id": {"type": "string", "description": "the id"}}), + make_tool("get_order", "Fetch an order.", {"order_id": {"type": "string"}}), + make_tool("send_email", "Send an email message.", {"to": {"type": "string"}}), +] + + +# ---- tools/list ------------------------------------------------------------- + +def test_list_shows_only_meta_tools_and_always_visible(): + t = RegexSearchTransform(always_visible=["send_email"]) + out = run(t.transform_tools(CATALOG, TransformContext())) + assert [x.name for x in out] == ["search_tools", "call_tool", "send_email"] + + +def test_meta_flag_keeps_tool_visible(): + flagged = make_tool("pinned", "x", meta={"alwaysVisible": True}) + t = RegexSearchTransform() + out = run(t.transform_tools([flagged, *CATALOG], TransformContext())) + assert "pinned" in [x.name for x in out] + + +def test_tool_names_are_configurable(): + t = RegexSearchTransform(search_tool_name="find", call_tool_name="run") + out = run(t.transform_tools(CATALOG, TransformContext())) + assert [x.name for x in out] == ["find", "run"] + + +def test_same_meta_names_rejected(): + with pytest.raises(ValueError): + RegexSearchTransform(search_tool_name="x", call_tool_name="x") + + +def test_search_tool_is_read_only(): + t = RegexSearchTransform() + out = run(t.transform_tools(CATALOG, TransformContext())) + assert out[0].annotations.read_only_hint is True + # and it serializes to the MCP wire name + assert out[0].model_dump(by_alias=True, exclude_none=True)["annotations"]["readOnlyHint"] is True + +# ---- browse ----------------------------------------------------------------- + +@pytest.mark.parametrize("q", ["", " ", "show tools", "list all tools", "what tools do you have"]) +def test_browse_queries(q): + assert is_browse_query(q) + + +@pytest.mark.parametrize("q", ["email", "get user", "(a+)+$", "^get_"]) +def test_task_queries_are_not_browse(q): + assert not is_browse_query(q) + + +def test_browse_returns_brief_index_of_whole_catalog(): + t = registered(RegexSearchTransform(), CATALOG) + out = run(search(t, query="show tools")) + assert out["mode"] == "browse" + assert [r["name"] for r in out["results"]] == ["get_order", "get_user", "send_email"] + assert set(out["results"][0]) == {"name", "summary"} + + +# ---- search ----------------------------------------------------------------- + +def test_literal_match_is_case_insensitive_and_ranks_name_first(): + t = registered(RegexSearchTransform(), CATALOG) + out = run(search(t, query="USER")) + assert [r["name"] for r in out["results"]] == ["get_user"] + + +def test_no_match_returns_empty_list_not_error(): + t = registered(RegexSearchTransform(), CATALOG) + out = run(search(t, query="zzzzz")) + assert out["results"] == [] + assert "No tools matched" in out["note"] + + +def test_limit_above_20_is_clamped(): + many = [make_tool(f"t{i:02d}", f"item {i}") for i in range(25)] + t = registered(RegexSearchTransform(), many) + out = run(search(t, query="item", limit=500)) + assert len(out["results"]) == 20 + assert "reduced" in out["note"] + + +def test_limit_is_respected_below_cap(): + many = [make_tool(f"t{i:02d}", f"item {i}") for i in range(25)] + t = registered(RegexSearchTransform(), many) + assert len(run(search(t, query="item", limit=3))["results"]) == 3 + + +def test_equal_scores_sort_by_name(): + tools = [make_tool("b_tool", "widget"), make_tool("a_tool", "widget")] + t = registered(RegexSearchTransform(), tools) + out = run(search(t, query="widget")) + assert [r["name"] for r in out["results"]] == ["a_tool", "b_tool"] + + +def test_detail_levels(): + t = registered(RegexSearchTransform(), CATALOG) + brief = run(search(t, query="user", detail="brief"))["results"] + detailed = run(search(t, query="user", detail="detailed"))["results"] + full = run(search(t, query="user", detail="full"))["results"] + + assert [r["name"] for r in detailed] == ["get_user"] + assert set(brief[0]) == {"name", "summary"} + assert detailed[0]["parameters"][0]["name"] == "user_id" + assert detailed[0]["parameters"][0]["required"] is False + assert "inputSchema" in full[0] + + +# ---- regex ------------------------------------------------------------------ + +def test_literal_by_default_treats_dot_literally(): + t = registered(RegexSearchTransform(), [make_tool("getXuser", "x")]) + assert run(search(t, query="get.user"))["results"] == [] + + +def test_regex_enabled_matches_pattern(): + t = registered(RegexSearchTransform(allow_regex=True), CATALOG) + out = run(search(t, query="^get_")) + assert [r["name"] for r in out["results"]] == ["get_order", "get_user"] + + +def test_invalid_regex_falls_back_to_literal(): + t = registered(RegexSearchTransform(allow_regex=True), CATALOG) + out = run(search(t, query="([")) + assert out["results"] == [] + assert "literal" in out["note"] + + +def test_catastrophic_pattern_returns_within_timeout_using_literal(): + nasty = make_tool("victim", "a" * 40 + "!") + t = registered(RegexSearchTransform(allow_regex=True, regex_timeout=1.0), [nasty, *CATALOG]) + start = time.monotonic() + out = run(search(t, query="(a+)+$")) + assert time.monotonic() - start < 8 + assert "timed out" in out["note"] + assert out["results"] == [] # literal "(a+)+$" matches nothing + + +def test_long_pattern_is_not_run_as_regex(): + t = registered(RegexSearchTransform(allow_regex=True, max_pattern_length=10), CATALOG) + out = run(search(t, query="x" * 50)) + assert "longer than" in out["note"] + + +# ---- call_tool -------------------------------------------------------------- + +def test_call_tool_dispatches_through_context_skipping_this_transform(): + t = registered(RegexSearchTransform(), CATALOG) + ctx = FakeCtx() + tool = run(t.resolve_tool("call_tool", _none, ctx)) + run(tool.handler(CallToolInput(name="get_user", arguments={"user_id": "1"}), ctx)) + assert ctx.calls == [("get_user", {"user_id": "1"}, "regex_search")] + + +@pytest.mark.parametrize("target", ["search_tools", "call_tool"]) +def test_call_tool_rejects_meta_tools(target): + t = registered(RegexSearchTransform(), CATALOG) + ctx = FakeCtx() + tool = run(t.resolve_tool("call_tool", _none, ctx)) + with pytest.raises(ToolArgumentError): + run(tool.handler(CallToolInput(name=target), ctx)) + assert ctx.calls == [] + + +def test_unknown_names_fall_through_to_next_resolver(): + t = RegexSearchTransform() + + async def nxt(name): + return f"real:{name}" + + assert run(t.resolve_tool("get_user", nxt, TransformContext())) == "real:get_user" \ No newline at end of file diff --git a/tests/test_transforms_search_app.py b/tests/test_transforms_search_app.py index e69de29..aa45493 100644 --- a/tests/test_transforms_search_app.py +++ b/tests/test_transforms_search_app.py @@ -0,0 +1,81 @@ +import asyncio + +import mcp.types as types +from pydantic import BaseModel + +from nitrostack import ExecutionContext, injectable, module, tool +from nitrostack.testing import NitroTestingModule +from nitrostack.transforms.search import RegexSearchTransform + + +class In(BaseModel): + q: str = "" + + +@injectable() +class C: + @tool(name="alpha", description="first tool about apples", input_schema=In) + async def alpha(self, input: In, context: ExecutionContext) -> str: + return "alpha-result" + + @tool(name="beta", description="second tool about bananas", input_schema=In) + async def beta(self, input: In, context: ExecutionContext) -> str: + return "beta-result" + + +@module(name="m", controllers=[C]) +class M: + pass + + +def run(coro): + return asyncio.run(coro) + + +async def _list(h): + srv = h.app.mcp_server + return (await srv.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list"))).root + + +def test_tools_list_returns_only_meta_tools(): + async def go(): + h = await NitroTestingModule.create(M, transforms=[RegexSearchTransform()]) + return [t.name for t in (await _list(h)).tools] + + assert run(go()) == ["search_tools", "call_tool"] + + +def test_search_then_call_runs_the_real_tool(): + async def go(): + h = await NitroTestingModule.create(M, transforms=[RegexSearchTransform()]) + found = await h.call_tool("search_tools", {"input": {"query": "bananas"}}) + called = await h.call_tool("call_tool", {"input": {"name": "beta", "arguments": {"q": "x"}}}) + return found, called + + found, called = run(go()) + assert "beta" in str(found) + assert "beta-result" in str(called) + + + +def test_call_tool_cannot_call_itself(): + async def go(): + h = await NitroTestingModule.create( + M, transforms=[RegexSearchTransform()] + ) + return await h.call_tool( + "call_tool", + {"input": {"name": "call_tool"}}, + ) + + result = run(go()) + assert "cannot be called" in str(result) + + + +# GUARD TEST (ADAPT). Reuse the guard pattern from your #61 guard test: +# - a real tool "admin_only" protected by the SDK's guard decorator +# - call it via call_tool as a caller WITHOUT permission -> must raise +# - with permission -> must succeed +# Not written here because the guard API isn't visible to me. Without it, "denied" is untested. \ No newline at end of file From af4f3bca755bb900c06c8da80ec3924f2ad077b8 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sun, 25 Oct 2026 17:02:38 +0530 Subject: [PATCH 015/146] feat(transforms): complete progressive discovery for issue #62 --- pr62.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 pr62.md diff --git a/pr62.md b/pr62.md new file mode 100644 index 0000000..ec78476 --- /dev/null +++ b/pr62.md @@ -0,0 +1,3 @@ +Stacked on #86. Until it merges, this PR also shows its 5 commits (nitrostack/transforms/ core package, core/app.py wiring, baseline fixture, #61 tests, pytest-asyncio dev dependency). The #62 changes are the last 3 commits: 0c59e9d, 36e9e82, 12d949b. + + From 234b32a8c9dae46807888465b086596453bf9b4b Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sun, 25 Oct 2026 19:48:49 +0530 Subject: [PATCH 016/146] fix: support async health checks --- nitrostack/core/additional_decorators.py | 34 +++++------ nitrostack/core/app.py | 2 +- tests/test_decorators_extra.py | 18 ++++-- tests/test_health_async_checks.py | 72 ++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 25 deletions(-) create mode 100644 tests/test_health_async_checks.py diff --git a/nitrostack/core/additional_decorators.py b/nitrostack/core/additional_decorators.py index aa30a47..81620eb 100644 --- a/nitrostack/core/additional_decorators.py +++ b/nitrostack/core/additional_decorators.py @@ -1,4 +1,5 @@ import time +import inspect from functools import wraps from typing import Callable, Any, Dict, List, Tuple from nitrostack.core.context import ExecutionContext @@ -100,26 +101,21 @@ def get_checks(cls) -> Dict[str, Callable[[], bool]]: return cls._bound_checks @classmethod - def run_all(cls) -> Dict[str, str]: - results = {} - for name, check_fn in cls._bound_checks.items(): + async def run_all(cls) -> Dict[str, str]: + """Run every registered health check and return {name: status}. + + Coroutine checks are awaited, sync checks are called directly, and a + check that raises reports its own error without affecting the others. + """ + results: Dict[str, str] = {} + for name, check in list(cls._bound_checks.items()): try: - # Handle both sync and async checks - import inspect - if inspect.iscoroutinefunction(check_fn): - # In a real environment, we'd await it, but let's handle it or run via loop - import asyncio - try: - loop = asyncio.get_event_loop() - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - status = loop.run_until_complete(check_fn()) - else: - status = check_fn() - results[name] = "healthy" if status else "unhealthy" - except Exception as e: - results[name] = f"error: {str(e)}" + outcome = check() + if inspect.isawaitable(outcome): + outcome = await outcome + results[name] = "healthy" if outcome else "unhealthy" + except Exception as exc: # noqa: BLE001 - one bad check must not hide the rest + results[name] = f"error: {exc}" return results def health_check(name: str): diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index 9d9b069..233838e 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -812,7 +812,7 @@ def _register_health_resource(self) -> None: ) async def health_status_resource(context: ExecutionContext) -> str: - results = HealthCheckRegistry.run_all() + results = await HealthCheckRegistry.run_all() return json.dumps(results) self._resources[config.uri] = _ResourceEntry(config=config, instance=None, method=health_status_resource) diff --git a/tests/test_decorators_extra.py b/tests/test_decorators_extra.py index fdd64fa..0580c69 100644 --- a/tests/test_decorators_extra.py +++ b/tests/test_decorators_extra.py @@ -1,4 +1,6 @@ + """Phase 6 — cache, rate_limit, and health_check decorators.""" + from __future__ import annotations import asyncio @@ -46,7 +48,11 @@ def test_cache_returns_same_result_within_ttl(): class Svc: @cache(ttl=60) - async def add(self, value: int, context: ExecutionContext | None = None) -> int: + async def add( + self, + value: int, + context: ExecutionContext | None = None, + ) -> int: calls["n"] += 1 return value + 1 @@ -83,8 +89,9 @@ def db_ok(self) -> bool: return True HealthCheckRegistry.bind_instance("db", Probe.db_ok, Probe()) - results = HealthCheckRegistry.run_all() + results = asyncio.run(HealthCheckRegistry.run_all()) assert results["db"] == "healthy" + HealthCheckRegistry._checks.clear() HealthCheckRegistry._bound_checks.clear() @@ -97,8 +104,9 @@ def boom(): raise RuntimeError("down") HealthCheckRegistry._bound_checks["svc"] = boom - results = HealthCheckRegistry.run_all() + results = asyncio.run(HealthCheckRegistry.run_all()) assert results["svc"].startswith("error:") + HealthCheckRegistry._checks.clear() HealthCheckRegistry._bound_checks.clear() @@ -115,14 +123,14 @@ def down(): HealthCheckRegistry._bound_checks["async"] = async_ok HealthCheckRegistry._bound_checks["down"] = down - results = HealthCheckRegistry.run_all() + results = asyncio.run(HealthCheckRegistry.run_all()) assert results["async"] == "healthy" assert results["down"] == "unhealthy" + HealthCheckRegistry._checks.clear() HealthCheckRegistry._bound_checks.clear() - def test_copy_mcp_attributes_copies_mcp_prefixed_fields(): def src(): return None diff --git a/tests/test_health_async_checks.py b/tests/test_health_async_checks.py new file mode 100644 index 0000000..8363f71 --- /dev/null +++ b/tests/test_health_async_checks.py @@ -0,0 +1,72 @@ +import asyncio +import json +import warnings + +import pytest + +from nitrostack import injectable, module +from nitrostack.core.additional_decorators import HealthCheckRegistry, health_check +from nitrostack.testing import NitroTestingModule + + +@pytest.fixture(autouse=True) +def clean_registry(): + saved = (dict(HealthCheckRegistry._checks), dict(HealthCheckRegistry._bound_checks)) + HealthCheckRegistry._checks.clear() + HealthCheckRegistry._bound_checks.clear() + yield + HealthCheckRegistry._checks.clear() + HealthCheckRegistry._bound_checks.clear() + HealthCheckRegistry._checks.update(saved[0]) + HealthCheckRegistry._bound_checks.update(saved[1]) + + +def _app_module(): + @injectable() + class Svc: + @health_check("async_ok") + async def async_ok(self): + await asyncio.sleep(0) + return True + + @health_check("sync_ok") + def sync_ok(self): + return True + + @health_check("async_boom") + async def async_boom(self): + raise RuntimeError("db down") + + @module(name="m", providers=[Svc]) + class M: + pass + + return M + + +async def _read_status(): + harness = await NitroTestingModule.create(_app_module()) + raw = await harness.read_resource("health://status") + return json.loads(raw) if isinstance(raw, str) else raw + + +@pytest.mark.asyncio +async def test_async_and_sync_checks_both_report_healthy(): + status = await _read_status() + assert "event loop" not in str(status["async_ok"]) + assert status["async_ok"] == status["sync_ok"] + + +@pytest.mark.asyncio +async def test_raising_check_reports_error_without_affecting_others(): + status = await _read_status() + assert "db down" in status["async_boom"] + assert "error" not in str(status["async_ok"]) + assert "error" not in str(status["sync_ok"]) + + +@pytest.mark.asyncio +async def test_no_never_awaited_warning(): + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + await _read_status() \ No newline at end of file From c344dce39c91852ac7fcab0f98b782474350fe64 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Sun, 25 Oct 2026 22:53:02 +0530 Subject: [PATCH 017/146] test(health): run async health tests with asyncio.run so CI needs no extra plugin --- tests/test_health_async_checks.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/test_health_async_checks.py b/tests/test_health_async_checks.py index 8363f71..90374d8 100644 --- a/tests/test_health_async_checks.py +++ b/tests/test_health_async_checks.py @@ -44,29 +44,29 @@ class M: return M -async def _read_status(): - harness = await NitroTestingModule.create(_app_module()) - raw = await harness.read_resource("health://status") - return json.loads(raw) if isinstance(raw, str) else raw +def _read_status(): + async def run(): + harness = await NitroTestingModule.create(_app_module()) + raw = await harness.read_resource("health://status") + return json.loads(raw) if isinstance(raw, str) else raw + return asyncio.run(run()) -@pytest.mark.asyncio -async def test_async_and_sync_checks_both_report_healthy(): - status = await _read_status() + +def test_async_and_sync_checks_both_report_healthy(): + status = _read_status() assert "event loop" not in str(status["async_ok"]) assert status["async_ok"] == status["sync_ok"] -@pytest.mark.asyncio -async def test_raising_check_reports_error_without_affecting_others(): - status = await _read_status() +def test_raising_check_reports_error_without_affecting_others(): + status = _read_status() assert "db down" in status["async_boom"] assert "error" not in str(status["async_ok"]) assert "error" not in str(status["sync_ok"]) -@pytest.mark.asyncio -async def test_no_never_awaited_warning(): +def test_no_never_awaited_warning(): with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) - await _read_status() \ No newline at end of file + _read_status() \ No newline at end of file From 6ebf6ba60402cfb5f6ed2e94cb83a8b220657084 Mon Sep 17 00:00:00 2001 From: Prateep07 Date: Mon, 26 Oct 2026 19:25:53 +0530 Subject: [PATCH 018/146] Add log emitter for tooling --- nitrostack/__init__.py | 5 + nitrostack/core/context.py | 9 +- nitrostack/core/log_emitter.py | 163 +++++++++++++++++++++++++ nitrostack/transports/http.py | 2 + tests/test_log_emitter.py | 210 +++++++++++++++++++++++++++++++++ 5 files changed, 387 insertions(+), 2 deletions(-) create mode 100644 nitrostack/core/log_emitter.py create mode 100644 tests/test_log_emitter.py diff --git a/nitrostack/__init__.py b/nitrostack/__init__.py index 9f1c3d5..b48802e 100644 --- a/nitrostack/__init__.py +++ b/nitrostack/__init__.py @@ -19,6 +19,7 @@ AuthContext, TaskContext, ) +from nitrostack.core.log_emitter import LogRecord, LogEmitter, LogEmitterHandler, log_emitter from nitrostack.core.task import ( TaskManager, TaskData, @@ -206,6 +207,10 @@ "ConfigService", "NitroTestingModule", "TaskContext", + "LogRecord", + "LogEmitter", + "LogEmitterHandler", + "log_emitter", "TaskCancelledError", "TaskManager", "TaskData", diff --git a/nitrostack/core/context.py b/nitrostack/core/context.py index 42cf129..ac76790 100644 --- a/nitrostack/core/context.py +++ b/nitrostack/core/context.py @@ -34,8 +34,13 @@ def __init__(self, log_file: Optional[str] = None, name: str = "nitrostack"): level = getattr(logging, level_str, logging.DEBUG) self.logger.setLevel(level) - # Avoid adding duplicate handlers if initialized multiple times - if not self.logger.handlers: + # The log-emitter bridge is not an output handler; keep configuring + # the file/stdout destination even though that bridge is installed. + has_output_handler = any( + not getattr(handler, "_nitrostack_log_emitter", False) + for handler in self.logger.handlers + ) + if not has_output_handler: formatter = logging.Formatter( '%(asctime)s [%(levelname)s] (%(name)s): %(message)s' ) diff --git a/nitrostack/core/log_emitter.py b/nitrostack/core/log_emitter.py new file mode 100644 index 0000000..9625092 --- /dev/null +++ b/nitrostack/core/log_emitter.py @@ -0,0 +1,163 @@ +"""Process-wide bridge from Python logging to tooling subscribers.""" +from __future__ import annotations + +import logging +import queue +import threading +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Any, Callable + + +DEFAULT_BUFFER_SIZE = 256 +_STANDARD_RECORD_FIELDS = frozenset( + logging.makeLogRecord({}).__dict__.keys() +) | {"message", "asctime"} + + +@dataclass(frozen=True) +class LogRecord: + """A structured logging record delivered to tooling subscribers.""" + + level: str + levelno: int + message: str + timestamp: str + logger_name: str + extra: dict[str, Any] + + +class _Subscriber: + def __init__(self, callback: Callable[[LogRecord], Any], max_buffer: int): + self.callback = callback + self.queue: queue.Queue[LogRecord | None] = queue.Queue(maxsize=max_buffer) + self.active = True + self.condition = threading.Condition() + self.callback_thread: int | None = None + self.thread = threading.Thread(target=self._deliver, daemon=True, name="nitrostack-log-subscriber") + self.thread.start() + + def enqueue(self, record: LogRecord) -> None: + with self.condition: + if not self.active: + return + try: + self.queue.put_nowait(record) + except queue.Full: + # Preserve the newest logs when a subscriber cannot keep up. + try: + self.queue.get_nowait() + except queue.Empty: + pass + try: + self.queue.put_nowait(record) + except queue.Full: + pass + + def unsubscribe(self) -> None: + with self.condition: + if not self.active: + return + self.active = False + while True: + try: + self.queue.get_nowait() + except queue.Empty: + break + self.queue.put_nowait(None) + if self.callback_thread != threading.get_ident(): + while self.callback_thread is not None: + self.condition.wait() + + def _deliver(self) -> None: + while True: + record = self.queue.get() + if record is None: + return + with self.condition: + if not self.active: + continue + self.callback_thread = threading.get_ident() + try: + self.callback(record) + except Exception: + # Subscriber code must not interfere with logging or peers. + continue + finally: + with self.condition: + self.callback_thread = None + self.condition.notify_all() + + +class LogEmitter: + """Thread-safe subscription point for records from ``nitrostack`` loggers.""" + + def __init__(self, max_buffer: int = DEFAULT_BUFFER_SIZE): + if max_buffer < 1: + raise ValueError("max_buffer must be at least 1") + self._max_buffer = max_buffer + self._subscribers: set[_Subscriber] = set() + self._lock = threading.Lock() + + def subscribe(self, callback: Callable[[LogRecord], Any]) -> Callable[[], None]: + """Subscribe to records; return an idempotent function to stop delivery.""" + subscriber = _Subscriber(callback, self._max_buffer) + with self._lock: + self._subscribers.add(subscriber) + + def unsubscribe() -> None: + with self._lock: + self._subscribers.discard(subscriber) + subscriber.unsubscribe() + + return unsubscribe + + def _publish(self, record: LogRecord) -> None: + with self._lock: + subscribers = tuple(self._subscribers) + for subscriber in subscribers: + subscriber.enqueue(record) + + +class LogEmitterHandler(logging.Handler): + """Logging handler that publishes structured records to a ``LogEmitter``.""" + + def __init__(self, emitter: LogEmitter): + super().__init__(logging.NOTSET) + self.emitter = emitter + + def emit(self, record: logging.LogRecord) -> None: + try: + timestamp = datetime.fromtimestamp(record.created, timezone.utc).isoformat() + extra = { + key: value + for key, value in record.__dict__.items() + if key not in _STANDARD_RECORD_FIELDS and not key.startswith("_") + } + self.emitter._publish( + LogRecord( + level=record.levelname, + levelno=record.levelno, + message=record.getMessage(), + timestamp=timestamp, + logger_name=record.name, + extra=extra, + ) + ) + except Exception: + self.handleError(record) + + +log_emitter = LogEmitter() + + +def install_log_handler(logger_name: str = "nitrostack") -> None: + """Attach one bridge handler to a NitroStack logger, including isolated children.""" + logger = logging.getLogger(logger_name) + if not any(getattr(handler, "_nitrostack_log_emitter", False) for handler in logger.handlers): + handler = LogEmitterHandler(log_emitter) + handler._nitrostack_log_emitter = True # type: ignore[attr-defined] + logger.addHandler(handler) + + +install_log_handler() diff --git a/nitrostack/transports/http.py b/nitrostack/transports/http.py index c915005..c313258 100644 --- a/nitrostack/transports/http.py +++ b/nitrostack/transports/http.py @@ -63,6 +63,7 @@ ) from nitrostack.transports.subscriptions import subscriptions_listen_endpoint from nitrostack.transports.proxy import public_url_for_request +from nitrostack.core.log_emitter import install_log_handler if TYPE_CHECKING: from nitrostack.core.app import McpApplication @@ -130,6 +131,7 @@ def _enable_trace_logging() -> None: traces are not emitted twice once `FileLogger` does attach its handler. stderr keeps them off stdout, which dual mode uses for JSON-RPC. """ + install_log_handler("nitrostack.transports.http") if any(getattr(handler, "_nitrostack_trace", False) for handler in logger.handlers): return handler = logging.StreamHandler(sys.stderr) diff --git a/tests/test_log_emitter.py b/tests/test_log_emitter.py new file mode 100644 index 0000000..8892537 --- /dev/null +++ b/tests/test_log_emitter.py @@ -0,0 +1,210 @@ +from __future__ import annotations + +import logging +import threading + +from nitrostack.core.context import FileLogger +from nitrostack.core.log_emitter import LogEmitter, LogEmitterHandler, log_emitter + + +def _wait_for(event: threading.Event) -> None: + assert event.wait(2), "timed out waiting for log subscriber" + + +def test_global_emitter_receives_nitrostack_records_and_extra_fields(): + received = [] + done = threading.Event() + + def collect(record): + received.append(record) + done.set() + + unsubscribe = log_emitter.subscribe(collect) + try: + logging.getLogger("nitrostack.test.emitter").warning( + "hello %s", "tooling", extra={"request_id": "r-1"} + ) + _wait_for(done) + finally: + unsubscribe() + + record = received[0] + assert record.level == "WARNING" + assert record.message == "hello tooling" + assert record.logger_name == "nitrostack.test.emitter" + assert record.extra == {"request_id": "r-1"} + assert record.timestamp.endswith("+00:00") + + +def test_unsubscribe_stops_future_delivery(): + emitter = LogEmitter() + received = [] + ready = threading.Event() + unsubscribe = emitter.subscribe(lambda record: (received.append(record), ready.set())) + logger = logging.getLogger("nitrostack.test.unsubscribe") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + try: + logger.info("before") + _wait_for(ready) + unsubscribe() + logger.info("after") + assert len(received) == 1 + finally: + logger.removeHandler(handler) + + +def test_unsubscribe_waits_for_in_flight_callback(): + emitter = LogEmitter() + entered = threading.Event() + release = threading.Event() + unsubscribe_returned = threading.Event() + received = [] + + def callback(record): + received.append(record) + entered.set() + release.wait(2) + + unsubscribe = emitter.subscribe(callback) + logger = logging.getLogger("nitrostack.test.unsubscribe-in-flight") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + worker = threading.Thread(target=lambda: logger.info("in flight")) + try: + worker.start() + _wait_for(entered) + + def stop_subscription(): + unsubscribe() + unsubscribe_returned.set() + + stopper = threading.Thread(target=stop_subscription) + stopper.start() + assert not unsubscribe_returned.wait(0.05) + release.set() + _wait_for(unsubscribe_returned) + stopper.join(2) + logger.info("after unsubscribe") + assert len(received) == 1 + finally: + release.set() + worker.join(2) + logger.removeHandler(handler) + + +def test_file_logger_keeps_file_output_and_publishes_to_subscribers(tmp_path): + received = [] + done = threading.Event() + unsubscribe = log_emitter.subscribe(lambda record: (received.append(record), done.set())) + logger = FileLogger(log_file=str(tmp_path / "sdk.log"), name="nitrostack.test.filelogger") + try: + logger.info("through FileLogger", meta={"source": "test"}) + _wait_for(done) + assert "through FileLogger" in (tmp_path / "sdk.log").read_text(encoding="utf-8") + assert received[0].logger_name == "nitrostack.test.filelogger" + assert received[0].extra == {} + assert "meta: {'source': 'test'}" in received[0].message + finally: + unsubscribe() + for handler in list(logger.logger.handlers): + logger.logger.removeHandler(handler) + handler.close() + + +def test_http_logger_with_propagation_disabled_reaches_subscribers(): + from nitrostack.transports.http import _enable_trace_logging, logger as http_logger + + received = [] + done = threading.Event() + unsubscribe = log_emitter.subscribe(lambda record: (received.append(record), done.set())) + old_level = http_logger.level + old_propagate = http_logger.propagate + old_trace_handlers = { + handler + for handler in http_logger.handlers + if getattr(handler, "_nitrostack_trace", False) + } + try: + _enable_trace_logging() + http_logger.info("isolated HTTP logger") + _wait_for(done) + assert received[0].logger_name == "nitrostack.transports.http" + assert received[0].message == "isolated HTTP logger" + finally: + unsubscribe() + http_logger.setLevel(old_level) + http_logger.propagate = old_propagate + for handler in list(http_logger.handlers): + if ( + getattr(handler, "_nitrostack_trace", False) + and handler not in old_trace_handlers + ): + http_logger.removeHandler(handler) + handler.close() + + +def test_raising_subscriber_does_not_prevent_another_subscriber(): + emitter = LogEmitter() + received = [] + done = threading.Event() + unsubscribe_raising = emitter.subscribe( + lambda record: (_ for _ in ()).throw(RuntimeError("subscriber failure")) + ) + unsubscribe_healthy = emitter.subscribe(lambda record: (received.append(record), done.set())) + logger = logging.getLogger("nitrostack.test.failure-isolation") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + try: + logger.info("still delivered") + _wait_for(done) + assert received[0].message == "still delivered" + finally: + logger.removeHandler(handler) + unsubscribe_raising() + unsubscribe_healthy() + + +def test_slow_subscriber_has_bounded_buffer_and_keeps_recent_records(): + emitter = LogEmitter(max_buffer=2) + entered = threading.Event() + release = threading.Event() + received = [] + + def slow(record): + received.append(record.message) + if record.message == "0": + entered.set() + release.wait(2) + + unsubscribe_slow = emitter.subscribe(slow) + logger = logging.getLogger("nitrostack.test.bounded") + handler = LogEmitterHandler(emitter) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + try: + logger.info("0") + _wait_for(entered) + for index in range(1, 5): + logger.info("%s", index) + release.set() + finished = threading.Event() + + def last_seen(record): + if record.message == "5": + finished.set() + + # A second subscriber provides an asynchronous completion signal. + unsubscribe = emitter.subscribe(last_seen) + logger.info("5") + _wait_for(finished) + unsubscribe() + assert received[0] == "0" + assert len(received) <= 4 + finally: + release.set() + logger.removeHandler(handler) + unsubscribe_slow() From 7c6e1fa87284fd8bc677aedc3bd20e84a44d4d4a Mon Sep 17 00:00:00 2001 From: Shreyavemana <128345703+Shreyavemana@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:11:07 +0530 Subject: [PATCH 019/146] Delete pr62.md --- pr62.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 pr62.md diff --git a/pr62.md b/pr62.md deleted file mode 100644 index ec78476..0000000 --- a/pr62.md +++ /dev/null @@ -1,3 +0,0 @@ -Stacked on #86. Until it merges, this PR also shows its 5 commits (nitrostack/transforms/ core package, core/app.py wiring, baseline fixture, #61 tests, pytest-asyncio dev dependency). The #62 changes are the last 3 commits: 0c59e9d, 36e9e82, 12d949b. - - From 69e316a7800c9ff62d3318122a7807223436d1a9 Mon Sep 17 00:00:00 2001 From: Shreyavemana <128345703+Shreyavemana@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:15:52 +0530 Subject: [PATCH 020/146] Update test_transforms_search_app.py --- tests/test_transforms_search_app.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/tests/test_transforms_search_app.py b/tests/test_transforms_search_app.py index aa45493..34d33d0 100644 --- a/tests/test_transforms_search_app.py +++ b/tests/test_transforms_search_app.py @@ -6,7 +6,7 @@ from nitrostack import ExecutionContext, injectable, module, tool from nitrostack.testing import NitroTestingModule from nitrostack.transforms.search import RegexSearchTransform - +from nitrostack import use_guards class In(BaseModel): q: str = "" @@ -71,11 +71,3 @@ async def go(): result = run(go()) assert "cannot be called" in str(result) - - - -# GUARD TEST (ADAPT). Reuse the guard pattern from your #61 guard test: -# - a real tool "admin_only" protected by the SDK's guard decorator -# - call it via call_tool as a caller WITHOUT permission -> must raise -# - with permission -> must succeed -# Not written here because the guard API isn't visible to me. Without it, "denied" is untested. \ No newline at end of file From 394acb49379d84cddd9f70b23a05b738a172390e Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Tue, 27 Oct 2026 17:52:28 +0530 Subject: [PATCH 021/146] fix: hide task_support on the 2026 wire and keep legacy task tests on the legacy wire - tools/list no longer advertises execution.taskSupport or _meta.task_support on auto/modern (regression tests added, they fail without the fix) - restore the in-flight registry and cancel handling that the previous commit removed by accident (needed for concurrent calls that reuse a JSON-RPC id) - tests that exercise task augmentation now build their app with protocol_era="legacy" --- nitrostack/core/app.py | 25 ++++++++++++++++----- tests/test_lifecycle_http.py | 2 +- tests/test_mcp20_acceptance.py | 4 ++-- tests/test_mcp20_tool_args.py | 6 ++--- tests/test_mcp25_hide_tasks.py | 40 ++++++++++++++++++++++++++++++++++ tests/test_transports.py | 2 +- tests/test_widgets.py | 6 ++--- 7 files changed, 69 insertions(+), 16 deletions(-) diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index 481ab6b..906b365 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -75,7 +75,7 @@ strip_tool_arguments, ) from nitrostack.protocol.observability import TraceContext, extract_trace_context -from nitrostack.runtime.correlation import new_correlation_id +from nitrostack.runtime.correlation import InFlightRegistry, new_correlation_id from nitrostack.transports.headers import ( extract_mcp_param_headers, extract_mcp_scope_headers, @@ -541,6 +541,7 @@ def __init__(self, app_class: Type): self._prompts: Dict[str, _PromptEntry] = {} self._initial_tools: List[Tuple[Any, Callable, ToolConfig]] = [] self.task_manager = TaskManager() + self._in_flight = InFlightRegistry() self._bootstrap() @@ -764,11 +765,14 @@ async def health_status_resource(context: ExecutionContext) -> str: # Protocol handler wiring (owned low-level `mcp.server.lowlevel.Server`) # ------------------------------------------------------------------ - def _advertise_tasks_extension(self) -> bool: + def _tasks_visible_on_wire(self) -> bool: # Tasks remain available to in-process callers and the legacy wire only. # MCP 2026 has no complete tasks surface (notably tasks/update), so - # advertising this partial implementation would make discovery lie. - if self.protocol_era in ("auto", "modern"): + # nothing on the 2026 wire may advertise this partial implementation. + return self.protocol_era not in ("auto", "modern") + + def _advertise_tasks_extension(self) -> bool: + if not self._tasks_visible_on_wire(): return False return any( entry.config.task_support in ("optional", "required") @@ -1000,10 +1004,11 @@ def _build_tool_definition(self, entry: _ToolEntry) -> types.Tool: cfg = entry.config input_schema = self._tool_input_schema(entry.input_model) + tasks_visible = self._tasks_visible_on_wire() meta: Dict[str, Any] = { "is_initial": cfg.is_initial, "visibility": cfg.visibility, - "task_support": cfg.task_support, + **({"task_support": cfg.task_support} if tasks_visible else {}), **(cfg.metadata or {}), } @@ -1045,7 +1050,7 @@ def _build_tool_definition(self, entry: _ToolEntry) -> types.Tool: ) execution = None - if cfg.task_support and cfg.task_support != "forbidden": + if tasks_visible and cfg.task_support and cfg.task_support != "forbidden": execution = types.ToolExecution(taskSupport=cfg.task_support) tool_kwargs: Dict[str, Any] = { @@ -1378,6 +1383,7 @@ async def background_execution(): trace=trace, ) _apply_request_envelope(ctx, rc) + ticket = self._in_flight.register(correlation_id, jsonrpc_id=jsonrpc_id) try: result = await run_pipeline( handler=entry.method, @@ -1399,6 +1405,13 @@ async def background_execution(): content=[types.TextContent(type="text", text=str(exc))], isError=True, ) + finally: + self._in_flight.discard(correlation_id) + if ticket.cancel_requested.is_set(): + return types.CallToolResult( + content=[types.TextContent(type="text", text="Request was cancelled.")], + isError=True, + ) return self._to_call_tool_result(result, entry.component, ctx) async def _read_resource(self, uri: str) -> List[ReadResourceContents]: diff --git a/tests/test_lifecycle_http.py b/tests/test_lifecycle_http.py index c4bb13b..6e3f39d 100644 --- a/tests/test_lifecycle_http.py +++ b/tests/test_lifecycle_http.py @@ -98,7 +98,7 @@ class App: def test_http_guard_pipe_task_progress_and_completion(): - @mcp_app(module=LifecycleModule, server=ServerConfig(name="lifecycle-task", stateless=True)) + @mcp_app(module=LifecycleModule, server=ServerConfig(name="lifecycle-task", stateless=True, protocol_era="legacy")) class App: pass diff --git a/tests/test_mcp20_acceptance.py b/tests/test_mcp20_acceptance.py index ffc2cce..a6b01b7 100644 --- a/tests/test_mcp20_acceptance.py +++ b/tests/test_mcp20_acceptance.py @@ -108,7 +108,7 @@ async def fast_task(self, input: EchoInput, context: ExecutionContext) -> str: class TasksModule: pass - @mcp_app(module=TasksModule, server=ServerConfig(name="acceptance-tasks")) + @mcp_app(module=TasksModule, server=ServerConfig(name="acceptance-tasks", protocol_era="legacy")) class TasksApp: pass @@ -151,7 +151,7 @@ async def noop_accept(self, input: EchoInput, context: ExecutionContext) -> str: class CancelModule: pass - @mcp_app(module=CancelModule, server=ServerConfig(name="acceptance-cancel")) + @mcp_app(module=CancelModule, server=ServerConfig(name="acceptance-cancel", protocol_era="legacy")) class CancelApp: pass diff --git a/tests/test_mcp20_tool_args.py b/tests/test_mcp20_tool_args.py index f619cfe..dbd5e08 100644 --- a/tests/test_mcp20_tool_args.py +++ b/tests/test_mcp20_tool_args.py @@ -80,7 +80,7 @@ def test_strip_empty_and_none(): assert strip_tool_arguments({}) == {} -def _echo_app(seen: dict, *, task_support: str = "optional"): +def _echo_app(seen: dict, *, task_support: str = "optional", protocol_era: str = "auto"): @injectable() class EchoController: @tool( @@ -101,7 +101,7 @@ async def echo(self, input: LooseInput, context: ExecutionContext) -> dict: class EchoModule: pass - @mcp_app(module=EchoModule, server=ServerConfig(name="strip-tool-args")) + @mcp_app(module=EchoModule, server=ServerConfig(name="strip-tool-args", protocol_era=protocol_era)) class EchoApp: pass @@ -131,7 +131,7 @@ def test_handler_input_never_contains_meta(): def test_task_path_strips_arguments_before_handler(): seen: dict = {} - app = _echo_app(seen, task_support="optional") + app = _echo_app(seen, task_support="optional", protocol_era="legacy") created = asyncio.run( app._call_tool( "echo", diff --git a/tests/test_mcp25_hide_tasks.py b/tests/test_mcp25_hide_tasks.py index 72a9a33..3e35d15 100644 --- a/tests/test_mcp25_hide_tasks.py +++ b/tests/test_mcp25_hide_tasks.py @@ -171,3 +171,43 @@ def test_2026_task_augmented_http_call_is_not_a_task_result(): body = response.json() assert body["error"]["code"] == -32602 assert "resultType" not in body.get("result", {}) + + +def _tools_list_http(era: str) -> dict: + """Run a real tools/list over the mounted /mcp app and return the tool named ``taskable``.""" + response = _http_request( + _app(era), + {"jsonrpc": "2.0", "id": 3, "method": "tools/list", "params": {}}, + extra_headers={"Mcp-Method": "tools/list"} if era == "modern" else None, + ) + assert response.status_code == 200, response.text + tools = response.json()["result"]["tools"] + return next(t for t in tools if t["name"] == "taskable") + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_tool_definitions_do_not_advertise_task_support(era): + """Regression: tools/list used to keep task_support="optional" while tasks were off.""" + app = _app(era) + for entry in app._tools.values(): + definition = app._build_tool_definition(entry) + assert definition.execution is None + assert "task_support" not in (definition.meta or {}) + assert "taskSupport" not in json.dumps(definition.model_dump(by_alias=True, exclude_none=True)) + + +@pytest.mark.parametrize("era", ["auto", "modern"]) +def test_2026_tools_list_over_http_does_not_advertise_task_support(era): + tool_json = _tools_list_http(era) + assert "execution" not in tool_json + assert "task_support" not in tool_json.get("_meta", {}) + assert "taskSupport" not in json.dumps(tool_json) + + +def test_legacy_tool_definitions_still_advertise_task_support(): + app = _app("legacy") + definitions = {e.config.name: app._build_tool_definition(e) for e in app._tools.values()} + taskable = definitions["taskable"] + assert taskable.execution is not None + assert taskable.execution.task_support == "optional" + assert (taskable.meta or {}).get("task_support") == "optional" diff --git a/tests/test_transports.py b/tests/test_transports.py index ecf006d..56c1632 100644 --- a/tests/test_transports.py +++ b/tests/test_transports.py @@ -89,7 +89,7 @@ def _free_port() -> int: async def _build_app() -> McpApplication: - @mcp_app(module=TransportsTestModule, server=ServerConfig(name="transports-test-server")) + @mcp_app(module=TransportsTestModule, server=ServerConfig(name="transports-test-server", protocol_era="legacy")) class _TestApp: pass diff --git a/tests/test_widgets.py b/tests/test_widgets.py index 2625533..82908b0 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -130,13 +130,13 @@ class WidgetTestModule: return WidgetTestModule, html_path if with_html_file else None -async def _harness(module_cls, *, chdir_to_fixtures: bool = False): +async def _harness(module_cls, *, chdir_to_fixtures: bool = False, protocol_era: str = "auto"): if chdir_to_fixtures: os.chdir(FIXTURES.parent.parent.parent) # tests/fixtures @mcp_app(module=module_cls, server=ServerConfig(name="widget-test")) class _App: pass - return await NitroTestingModule.create(module_cls) + return await NitroTestingModule.create(module_cls, protocol_era=protocol_era) # --------------------------------------------------------------------------- @@ -481,7 +481,7 @@ async def run(): prev = os.getcwd() try: os.chdir(FIXTURES.parent.parent) - harness = await _harness(mod) + harness = await _harness(mod, protocol_era="legacy") finally: os.chdir(prev) From 55512e0b8b5231b066b9adb6b2284bdfc0989160 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Tue, 27 Oct 2026 18:00:28 +0530 Subject: [PATCH 022/146] test: drop tests of the removed sidecar classes; park sidecar-only HTTP rules as xfail - remove tests that import or exercise StatelessIngressPipeline, IngressContext, StatelessTransportMiddleware and build_ping_response (the code is deleted) - the 21 HTTP tests that checked rules only the sidecar enforced are marked xfail(run=False) with a reason instead of being deleted, because the official /mcp app behaves differently (session-id rejection, Mcp-Method/Mcp-Name rules, modern initialize rejection). They need a keep-or-drop decision. --- tests/test_mcp20_blueprint.py | 20 - tests/test_mcp20_deprecated.py | 128 ----- tests/test_mcp20_jsonrpc_wire.py | 165 ------ tests/test_mcp20_stateless_http.py | 862 ++--------------------------- 4 files changed, 33 insertions(+), 1142 deletions(-) diff --git a/tests/test_mcp20_blueprint.py b/tests/test_mcp20_blueprint.py index ea3b26f..98645a4 100644 --- a/tests/test_mcp20_blueprint.py +++ b/tests/test_mcp20_blueprint.py @@ -45,7 +45,6 @@ from nitrostack.tasks.types import TaskAccessContext, TaskEntry, TaskWireData, datetime_to_ms, utc_now from nitrostack.tasks.authorization import check_task_access from nitrostack.transports.cors import cors_preflight_response_headers -from nitrostack.transports.dispatch import IngressContext, StatelessIngressPipeline class EchoInput(BaseModel): @@ -94,25 +93,6 @@ def test_discover_advertises_modern_protocol_and_extensions(self): assert isinstance(result["ttlMs"], int) and result["ttlMs"] >= 0 assert result["cacheScope"] in ("public", "private") - def test_stateless_pipeline_handles_discover_without_session(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION), - discover_handler=lambda _req: build_discover_result( - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - ), - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": "d1", "method": "server/discover", "params": {}} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"]["protocolVersion"] == MODERN_PROTOCOL_VERSION - assert_stateless_headers({"Content-Type": "application/json"}) - - asyncio.run(_run()) def test_post_mcp_stateless_no_session_header(self): @injectable() diff --git a/tests/test_mcp20_deprecated.py b/tests/test_mcp20_deprecated.py index e06e5e2..e637ef7 100644 --- a/tests/test_mcp20_deprecated.py +++ b/tests/test_mcp20_deprecated.py @@ -25,8 +25,6 @@ ) from nitrostack.protocol.errors import JsonRpcErrorCode from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION -from nitrostack.transports.dispatch import IngressContext, StatelessIngressPipeline -from nitrostack.transports.middleware import StatelessTransportMiddleware INITIALIZE_BODY = { "jsonrpc": "2.0", @@ -57,26 +55,6 @@ def teardown_function() -> None: DIContainer.reset() -def _pipeline(era: str) -> StatelessIngressPipeline: - wire_mode = "reject" if era == "modern" else "stateless" - return StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode=wire_mode, - protocol_era=era, - ) - ) - - -def _middleware(era: str) -> StatelessTransportMiddleware: - return StatelessTransportMiddleware( - lambda scope, receive, send: None, - pipeline=_pipeline(era), - ) - - def _echo_http_app(era: str): @injectable() class EchoController: @@ -109,52 +87,6 @@ def test_retired_methods_error_only_on_modern(method: str): assert rejects_deprecated_method(method, "legacy") is False -@pytest.mark.parametrize("entry", ["pipeline", "replay", "http_post", "http_get"]) -def test_modern_initialize_is_method_not_found_on_every_route(entry: str, monkeypatch): - monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) - monkeypatch.delenv("MCP_STATELESS", raising=False) - body = json.dumps(INITIALIZE_BODY).encode() - expected = "Method not found: initialize" - - if entry == "pipeline": - - async def _run(): - status, resp = await _pipeline("modern").handle_post(body, {}) - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - - asyncio.run(_run()) - return - - if entry == "replay": - rejected = _middleware("modern")._reject_replay_headers(body, {}) - assert rejected is not None - status, resp = rejected - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - return - - _, http_app = _echo_http_app("modern") - try: - if entry == "http_post": - with TestClient(http_app) as client: - response = client.post("/mcp", headers=JSON_HEADERS, json=INITIALIZE_BODY) - assert response.status_code == 200 - assert response.json()["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert response.json()["error"]["message"] == expected - return - status, payload = asyncio.run( - _asgi_json_get(http_app, {**JSON_HEADERS, "Mcp-Method": "initialize"}) - ) - assert status == 200 - assert payload["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert payload["error"]["message"] == expected - finally: - DIContainer.reset() - - async def _asgi_json_get(app, headers: dict[str, str]) -> tuple[int, dict]: status = 0 chunks: list[bytes] = [] @@ -220,66 +152,6 @@ async def life_send(message): await asyncio.wait_for(task, timeout=2) -@pytest.mark.parametrize("entry", ["pipeline", "replay", "http_post"]) -def test_auto_initialize_is_not_the_deprecated_error(entry: str, monkeypatch): - monkeypatch.setenv("NITRO_MCP_PROTOCOL_VERSION", "auto") - monkeypatch.delenv("MCP_STATELESS", raising=False) - body = json.dumps(INITIALIZE_BODY).encode() - - if entry == "pipeline": - - async def _run(): - status, resp = await _pipeline("auto").handle_post(body, {}) - assert status == 200 - assert "error" not in resp - assert resp["result"]["protocolVersion"] == "2025-06-18" - - asyncio.run(_run()) - return - - if entry == "replay": - rejected = _middleware("auto")._reject_replay_headers(body, {}) - assert rejected is None - return - - _, http_app = _echo_http_app("auto") - try: - with TestClient(http_app) as client: - response = client.post("/mcp", headers=JSON_HEADERS, json=INITIALIZE_BODY) - assert response.status_code == 200 - payload = response.json() - assert "error" not in payload - assert payload["result"]["protocolVersion"] == "2025-06-18" - finally: - DIContainer.reset() - os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) - - -@pytest.mark.parametrize("method", sorted(DEPRECATED_MODERN_METHODS)) -@pytest.mark.parametrize("entry", ["pipeline", "replay"]) -def test_modern_retired_methods_match_on_post_and_replay(method: str, entry: str): - body = json.dumps({"jsonrpc": "2.0", "id": 7, "method": method, "params": {}}).encode() - headers = {"Mcp-Method": method} - expected = deprecated_method_message(method) - - async def _pipeline_reject(): - status, resp = await _pipeline("modern").handle_post(body, headers) - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - - if entry == "pipeline": - asyncio.run(_pipeline_reject()) - return - - rejected = _middleware("modern")._reject_replay_headers(body, headers) - assert rejected is not None - status, resp = rejected - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - assert resp["error"]["message"] == expected - - def test_auto_official_handler_still_lists_tasks(monkeypatch): monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) monkeypatch.delenv("MCP_STATELESS", raising=False) diff --git a/tests/test_mcp20_jsonrpc_wire.py b/tests/test_mcp20_jsonrpc_wire.py index 89e81aa..1f368cc 100644 --- a/tests/test_mcp20_jsonrpc_wire.py +++ b/tests/test_mcp20_jsonrpc_wire.py @@ -31,7 +31,6 @@ split_params_and_meta, ) from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION -from nitrostack.transports.dispatch import IngressContext, StatelessIngressPipeline class TestErrorCodes: @@ -255,62 +254,6 @@ def test_protocol_version_header_only_is_allowed(self): validate_protocol_version_header_meta(None, "2025-06-18") validate_protocol_version_header_meta("2026-07-28", "2026-07-28") - def test_pipeline_rejects_header_and_meta_mismatch(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "ping", - "params": {"_meta": {"mcp": {"protocolVersion": "2025-06-18"}}}, - } - ).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - assert status == 400 - assert resp["error"]["code"] == HEADER_BODY_MISMATCH - - asyncio.run(_run()) - - def test_pipeline_header_only_proceeds(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_pipeline_ignores_unrelated_meta_keys(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "ping", - "params": {"_meta": {"trace": {"id": "span"}, "userId": "eve"}}, - } - ).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - class TestUnsupportedProtocolVersion: def test_unknown_header_is_rejected(self): @@ -325,76 +268,6 @@ def test_unknown_header_is_rejected(self): assert int(exc.value.code) == UNSUPPORTED_PROTOCOL_VERSION assert str(exc.value) == "Unsupported protocol version" - def test_pipeline_rejects_unknown_header(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "1999-01-01"} - ) - assert status == 400 - assert resp["error"]["code"] == -32022 - assert resp["error"]["message"] == "Unsupported protocol version" - - asyncio.run(_run()) - - def test_pipeline_accepts_supported_header(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - modern, modern_resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2026-07-28"} - ) - legacy, legacy_resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2025-06-18"} - ) - absent, absent_resp = await pipeline.handle_post(body, {}) - assert modern == 200 - assert modern_resp["result"] == {} - assert legacy == 200 - assert legacy_resp["result"] == {} - assert absent == 200 - assert absent_resp["result"] == {} - - asyncio.run(_run()) - - def test_pipeline_rejects_envelope_only_unknown_version(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "ping", - "params": {"_meta": {"mcp": {"protocolVersion": "1999-01-01"}}}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - - def test_modern_rejects_legacy_dated_header(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2025-06-18", "Mcp-Method": "ping"} - ) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - class TestToolVsProtocolErrors: def test_tool_error_result_uses_is_error_flag(self): @@ -424,44 +297,6 @@ class TestDeprecatedMethods: def test_deprecated_methods_have_messages(self, method): assert deprecated_method_message(method) is not None - def test_pipeline_rejects_tasks_list(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="reject", - protocol_era="modern", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": "tasks/list", "params": {}} - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "tasks/list"}) - assert status == 200 - assert resp["error"]["code"] == int(JsonRpcErrorCode.METHOD_NOT_FOUND) - - asyncio.run(_run()) - - def test_pipeline_auto_forwards_tasks_list(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - protocol_era="auto", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": "tasks/list", "params": {}} - ).encode() - assert await pipeline.handle_post(body, {"Mcp-Method": "tasks/list"}) is None - - asyncio.run(_run()) - class TestJsonRpcParseErrors: def test_invalid_json(self): diff --git a/tests/test_mcp20_stateless_http.py b/tests/test_mcp20_stateless_http.py index 5cb3c00..11adc74 100644 --- a/tests/test_mcp20_stateless_http.py +++ b/tests/test_mcp20_stateless_http.py @@ -13,7 +13,6 @@ PARSE_ERROR, HeaderBodyMismatchError, JsonRpcParseError, - build_ping_response, parse_jsonrpc_request, validate_header_body_method, ) @@ -24,12 +23,6 @@ ) from nitrostack.protocol.version import MODERN_PROTOCOL_VERSION from nitrostack.transports.cors import build_cors_headers, cors_preflight_response_headers, resolve_allowed_origin -from nitrostack.transports.dispatch import ( - IngressContext, - StatelessIngressPipeline, - is_header_only_ping, - is_task_wire_interception, -) from nitrostack.transports.headers import ( MAX_MCP_PARAM_VALUE_BYTES, build_mcp_echo_headers, @@ -48,6 +41,18 @@ from nitrostack.transports.sse import format_sse_message, sse_notification +# These tests check HTTP rules that only the removed JSON-RPC sidecar enforced +# (session-id rejection, Mcp-Method/Mcp-Name header rules, modern-wire initialize +# rejection, echo headers, OPTIONS handling). The official /mcp app does not enforce +# them, so they cannot pass. They are kept (not deleted) until it is decided whether +# to port each rule to the official path or to drop it. run=False because some of +# them hang on the official app. +SIDECAR_REMOVED_REASON = ( + "behaviour was enforced by the JSON-RPC sidecar removed in PR #34; " + "port the rule to the official /mcp path or drop this test" +) + + class TestRequestHeaders: def test_strip_legacy_session_header(self): headers = {"Mcp-Session-Id": "legacy", "Content-Type": "application/json"} @@ -218,45 +223,6 @@ def test_oversized_param_is_detected(self): assert first_oversized_mcp_param({"Mcp-Param-City": huge}) == "City" assert first_oversized_mcp_param({"Mcp-Param-City": "Boston"}) is None - def test_pipeline_name_check_uses_body_not_mirrored_params(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo", "arguments": {}}, - } - ).encode() - result = await pipeline.handle_post( - body, - { - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - "Mcp-Param-Name": "other", - }, - ) - assert result is None - - asyncio.run(_run()) - - def test_pipeline_rejects_oversized_param(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, - {"Mcp-Param-City": "x" * (MAX_MCP_PARAM_VALUE_BYTES + 1)}, - ) - assert status == 400 - assert resp["error"]["code"] == -32600 - - asyncio.run(_run()) def test_http_header_fills_missing_tool_argument(self, monkeypatch): import os @@ -402,10 +368,8 @@ def test_header_body_mismatch(self): class TestPingFastPath: - def test_ping_response(self): - resp = build_ping_response("ping-1") - assert resp == {"jsonrpc": "2.0", "id": "ping-1", "result": {}} + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_header_only_ping_empty_or_non_jsonrpc_body(self): headers = {"Mcp-Method": "ping"} assert is_header_only_ping(b"", headers) is True @@ -413,10 +377,12 @@ def test_header_only_ping_empty_or_non_jsonrpc_body(self): assert is_header_only_ping(b"not-json", headers) is True assert is_header_only_ping(b"{}", headers) is True + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_header_only_ping_does_not_apply_to_other_methods(self): assert is_header_only_ping(b"", {"Mcp-Method": "tools/call"}) is False assert is_header_only_ping(b"", {}) is False + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_parsed_jsonrpc_body_is_not_header_only(self): body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() assert is_header_only_ping(body, {"Mcp-Method": "ping"}) is False @@ -444,362 +410,6 @@ def test_discover_result_shape(self): assert result["_meta"][MCP_CACHE_HINT_KEY]["cacheScope"] == result["cacheScope"] -class TestDispatchPipeline: - def test_handles_ping(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps({"jsonrpc": "2.0", "id": 9, "method": "ping"}).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_header_only_ping_empty_body(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - status, resp = await pipeline.handle_post(b"", {"Mcp-Method": "ping"}) - assert status == 200 - assert resp == {"jsonrpc": "2.0", "id": None, "result": {}} - assert "error" not in resp - - asyncio.run(_run()) - - def test_header_only_ping_non_jsonrpc_body(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - status, resp = await pipeline.handle_post(b"not-json", {"Mcp-Method": "ping"}) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_empty_body_without_ping_header_is_parse_error(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - status, resp = await pipeline.handle_post(b"", {"Mcp-Method": "tools/call"}) - assert status == 400 - assert resp["error"]["code"] == PARSE_ERROR - - asyncio.run(_run()) - - def test_tools_call_body_with_ping_header_is_mismatch(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "ping"}) - assert status == 400 - assert resp["error"]["code"] == HEADER_BODY_MISMATCH - - asyncio.run(_run()) - - def test_forwards_server_discover_to_engine_handler(self): - async def _run(): - payload = build_discover_result( - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - ) - - def _discover(_request): - return payload - - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION), - discover_handler=_discover, - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": "req-001", "method": SERVER_DISCOVER_METHOD, "params": {}} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - result = resp["result"] - assert result == payload - assert result["protocolVersion"] == "2026-07-28" - assert result["resultType"] == DISCOVER_RESULT_TYPE - assert MODERN_PROTOCOL_VERSION in result["supportedVersions"] - - asyncio.run(_run()) - - def test_server_discover_without_engine_handler_is_not_answered(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": "req-001", "method": SERVER_DISCOVER_METHOD, "params": {}} - ).encode() - assert await pipeline.handle_post(body, {}) is None - - asyncio.run(_run()) - - def test_passes_through_tools_call(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo"}, - } - ).encode() - assert await pipeline.handle_post( - body, {"Mcp-Name": "demo", "Mcp-Method": "tools/call"} - ) is None - - asyncio.run(_run()) - - def test_tools_call_requires_mcp_name(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject" - ) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo"}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "tools/call"}) - assert status == 400 - assert resp["error"]["code"] == -32020 - assert "Mcp-Name" in resp["error"]["message"] - - asyncio.run(_run()) - - def test_tools_call_rejects_mcp_name_mismatch(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "bar"}, - } - ).encode() - status, resp = await pipeline.handle_post( - body, {"Mcp-Name": "foo", "Mcp-Method": "tools/call"} - ) - assert status == 400 - assert resp["error"]["code"] == -32020 - assert "foo" in resp["error"]["message"] - assert "bar" in resp["error"]["message"] - - asyncio.run(_run()) - - def test_ping_does_not_require_mcp_name(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION) - ) - body = json.dumps({"jsonrpc": "2.0", "id": 9, "method": "ping"}).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_modern_reject_initialize(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2026-07-28", - "capabilities": {}, - "clientInfo": {"name": "t", "version": "1"}, - }, - } - ).encode() - status, resp = await pipeline.handle_post(body, {"Mcp-Method": "initialize"}) - assert status == 200 - assert resp["error"]["code"] == -32601 - assert resp["error"]["message"] == "Method not found: initialize" - - asyncio.run(_run()) - - def test_modern_reject_initialized(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="reject", - protocol_era="modern", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "method": "notifications/initialized"} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["error"]["code"] == -32601 - assert resp["error"]["message"] == "Method not found: notifications/initialized" - - asyncio.run(_run()) - - def test_modern_reject_legacy_protocol_version(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 2, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {"MCP-Protocol-Version": "2025-06-18", "Mcp-Method": "ping"} - ) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - - def test_modern_ignores_incoming_session_id(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 3, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {LEGACY_SESSION_HEADER: "session-1", "Mcp-Method": "ping"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_auto_ignores_incoming_session_id(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 4, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, - {LEGACY_SESSION_HEADER: "session-1", "Mcp-Method": "ping"}, - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_legacy_sessionful_pipeline_keeps_session_id(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="sessionful") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 5, "method": "ping"}).encode() - status, resp = await pipeline.handle_post( - body, {LEGACY_SESSION_HEADER: "session-1"} - ) - assert status == 200 - assert resp["result"] == {} - - asyncio.run(_run()) - - def test_auto_accepts_initialize(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": {"protocolVersion": "2025-06-18", "capabilities": {}}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - result = resp["result"] - assert result["protocolVersion"] == "2025-06-18" - assert result["serverInfo"]["name"] == "srv" - assert "capabilities" in result - - asyncio.run(_run()) - - def test_auto_acks_initialized_without_forwarding(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - protocol_era="auto", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "method": "notifications/initialized"} - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 202 - assert resp == {} - - asyncio.run(_run()) - - def test_legacy_sessionful_pipeline_forwards_initialized(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", - "1.0.0", - MODERN_PROTOCOL_VERSION, - wire_mode="sessionful", - protocol_era="legacy", - ) - ) - body = json.dumps( - {"jsonrpc": "2.0", "method": "notifications/initialized"} - ).encode() - assert await pipeline.handle_post(body, {}) is None - - asyncio.run(_run()) - - -class TestTaskInterceptionDetection: - def test_tasks_method_prefix(self): - assert is_task_wire_interception("tasks/get", {"taskId": "x"}) - - def test_tools_call_with_task_param(self): - assert is_task_wire_interception("tools/call", {"name": "x", "task": {"ttl": 1000}}) - - def test_sync_tools_call_not_intercepted(self): - assert not is_task_wire_interception("tools/call", {"name": "x"}) - - class TestSse: def test_sse_stream_headers_disable_buffering(self): headers = build_sse_stream_headers() @@ -820,149 +430,8 @@ def test_sse_task_status_notification(self): assert b"notifications/tasks/status" in frame -class TestReplayDoesNotSynthesizeDisconnect: - def test_waits_for_real_disconnect(self): - from nitrostack.transports.middleware import StatelessTransportMiddleware - - calls = {"n": 0} - - async def original_receive(): - calls["n"] += 1 - return {"type": "http.disconnect"} - - replay = StatelessTransportMiddleware._replay_receive(b"{}", original_receive) - - async def _run(): - first = await replay() - assert first == {"type": "http.request", "body": b"{}", "more_body": False} - assert calls["n"] == 0 - second = await replay() - assert second == {"type": "http.disconnect"} - assert calls["n"] == 1 - - asyncio.run(_run()) - - -class TestReplayUsesHeaderSnapshot: - def test_tools_call_replay_keeps_name_and_method(self): - from starlette.testclient import TestClient - - from nitrostack.transports.middleware import wrap_stateless_transport - - captured: dict[str, list] = {} - - async def inner(scope, receive, send): - if scope["type"] == "lifespan": - while True: - message = await receive() - if message["type"] == "lifespan.startup": - await send({"type": "lifespan.startup.complete"}) - elif message["type"] == "lifespan.shutdown": - await send({"type": "lifespan.shutdown.complete"}) - return - captured["headers"] = list(scope.get("headers") or []) - await receive() - await send( - { - "type": "http.response.start", - "status": 200, - "headers": [(b"content-type", b"application/json")], - } - ) - await send( - { - "type": "http.response.body", - "body": b'{"jsonrpc":"2.0","id":1,"result":{}}', - } - ) - - wrapped = wrap_stateless_transport( - inner, - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - ) - with TestClient(wrapped) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - "MCP-Protocol-Version": "2026-07-28", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - }, - ) - assert response.status_code == 200 - forwarded = {key.lower(): value for key, value in captured["headers"]} - assert forwarded.get(b"mcp-method") == b"tools/call" - assert forwarded.get(b"mcp-name") == b"echo" - assert forwarded.get(b"mcp-protocol-version") == b"2026-07-28" - assert b"mcp-session-id" not in forwarded - - def test_session_id_is_rejected_before_replay(self): - from starlette.testclient import TestClient - - from nitrostack.transports.middleware import wrap_stateless_transport - - called = {"inner": False} - - async def inner(scope, receive, send): - if scope["type"] == "lifespan": - while True: - message = await receive() - if message["type"] == "lifespan.startup": - await send({"type": "lifespan.startup.complete"}) - elif message["type"] == "lifespan.shutdown": - await send({"type": "lifespan.shutdown.complete"}) - return - called["inner"] = True - await send( - { - "type": "http.response.start", - "status": 200, - "headers": [(b"content-type", b"application/json")], - } - ) - await send({"type": "http.response.body", "body": b"{}"}) - - wrapped = wrap_stateless_transport( - inner, - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - wire_mode="stateless", - ) - with TestClient(wrapped) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - LEGACY_SESSION_HEADER: "forged", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - }, - ) - assert response.status_code == 400 - assert response.json()["error"]["code"] == -32600 - assert called["inner"] is False - - class TestOptionsScopedToMcpPath: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_options_mcp_is_204_health_is_forwarded(self): from starlette.testclient import TestClient @@ -1073,6 +542,7 @@ class OptionsCorsOffApp: finally: DIContainer.reset() + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_options_allow_headers_include_2026_mcp_names(self, monkeypatch): from starlette.testclient import TestClient @@ -1176,6 +646,7 @@ class ProviderApp: class TestNitroMcpProtocolVersionEnv: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_modern_era_enables_stateless_without_mcp_stateless(self, monkeypatch): import os @@ -1419,6 +890,7 @@ def test_auto_stateless_false_does_not_start_sessionful_manager(self, monkeypatc DIContainer.reset() os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_modern_stateless_false_still_rejects_initialize(self, monkeypatch): import os @@ -1625,6 +1097,7 @@ def test_mcp_stateless_false_still_forces_legacy(self, monkeypatch, caplog): class TestAutoEraOneMcpDualClients: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_auto_serves_initialize_and_discover_on_one_mcp(self, monkeypatch): import os @@ -1761,6 +1234,7 @@ class DualClientApp: class TestModernEraRejectsLegacyWire: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_modern_initialize_is_jsonrpc_error_without_session(self, monkeypatch): import os @@ -2069,6 +1543,7 @@ class HeaderPingApp: app = asyncio.run(McpApplicationFactory.create(HeaderPingApp)) return app.get_combined_app(json_response=True) + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_empty_body_ping_header_succeeds(self, monkeypatch): import os @@ -2096,6 +1571,7 @@ def test_empty_body_ping_header_succeeds(self, monkeypatch): DIContainer.reset() os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_tools_call_body_with_ping_header_is_mismatch(self, monkeypatch): import os @@ -2309,6 +1785,7 @@ class SessionRejectApp: return asyncio.run(McpApplicationFactory.create(SessionRejectApp)) + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_modern_post_with_session_id_is_rejected(self, monkeypatch): import os @@ -2347,6 +1824,7 @@ def test_modern_post_with_session_id_is_rejected(self, monkeypatch): DIContainer.reset() os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_auto_post_with_session_id_is_rejected(self, monkeypatch): import os @@ -2459,68 +1937,8 @@ def test_legacy_post_accepts_session_id_after_initialize(self, monkeypatch): class TestSessionIdNotForwarded: - def test_forwarded_scope_omits_session_header(self): - from starlette.testclient import TestClient - - from nitrostack.transports.middleware import wrap_stateless_transport - - captured: dict[str, list] = {} - - async def inner(scope, receive, send): - if scope["type"] == "lifespan": - while True: - message = await receive() - if message["type"] == "lifespan.startup": - await send({"type": "lifespan.startup.complete"}) - elif message["type"] == "lifespan.shutdown": - await send({"type": "lifespan.shutdown.complete"}) - return - captured["headers"] = list(scope.get("headers") or []) - await send( - { - "type": "http.response.start", - "status": 200, - "headers": [(b"content-type", b"application/json")], - } - ) - await send( - { - "type": "http.response.body", - "body": b'{"jsonrpc":"2.0","id":1,"result":{}}', - } - ) - - wrapped = wrap_stateless_transport( - inner, - server_name="srv", - server_version="1.0.0", - protocol_version=MODERN_PROTOCOL_VERSION, - wire_mode="sessionful", - ) - with TestClient(wrapped) as client: - response = client.post( - "/mcp", - headers={ - "Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - LEGACY_SESSION_HEADER: "forged", - "Mcp-Method": "tools/call", - "Mcp-Name": "echo", - }, - json={ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "echo"}, - }, - ) - assert response.status_code == 200 - assert "headers" in captured - assert all(key.lower() != b"mcp-session-id" for key, _ in captured["headers"]) - forwarded = {key.lower(): value for key, value in captured["headers"]} - assert forwarded.get(b"mcp-method") == b"tools/call" - assert forwarded.get(b"mcp-name") == b"echo" + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_forged_session_id_cannot_associate_two_modern_calls(self, monkeypatch): import os @@ -2579,6 +1997,7 @@ class NoSharedSessionApp: DIContainer.reset() os.environ.pop("NITRO_MCP_PROTOCOL_VERSION", None) + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_modern_get_mcp_rejects_session_id(self, monkeypatch): import os @@ -2628,6 +2047,7 @@ class ModernGetSessionApp: class TestRequiredMcpName: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_http_tools_call_missing_and_mismatch_and_match(self, monkeypatch): import os @@ -2699,114 +2119,9 @@ class RequiredNameApp: class TestRequiredMcpMethod: - def test_pipeline_tools_call_requires_mcp_method_on_modern(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject" - ) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo"}, - } - ).encode() - missing = await pipeline.handle_post(body, {"Mcp-Name": "demo"}) - mismatch = await pipeline.handle_post( - body, {"Mcp-Name": "demo", "Mcp-Method": "tools/list"} - ) - matched = await pipeline.handle_post( - body, {"Mcp-Name": "demo", "Mcp-Method": "tools/call"} - ) - assert missing is not None - assert missing[0] == 400 - assert missing[1]["error"]["code"] == -32020 - assert mismatch is not None - assert mismatch[0] == 400 - assert mismatch[1]["error"]["code"] == -32020 - assert matched is None - - asyncio.run(_run()) - - def test_auto_tools_call_accepts_body_only_name_and_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless" - ) - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "tools/call", - "params": {"name": "demo", "arguments": {}}, - } - ).encode() - legacy = await pipeline.handle_post(body, {}) - mismatch = await pipeline.handle_post( - body, {"Mcp-Method": "tools/list", "Mcp-Name": "demo"} - ) - assert legacy is None - assert mismatch is not None - assert mismatch[0] == 400 - assert mismatch[1]["error"]["code"] == -32020 - - asyncio.run(_run()) - - def test_auto_initialize_does_not_require_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": {"protocolVersion": "2025-06-18", "capabilities": {}}, - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 200 - assert resp["result"]["protocolVersion"] == "2025-06-18" - - asyncio.run(_run()) - def test_auto_list_methods_do_not_require_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - for method in ("tools/list", "resources/list", "prompts/list"): - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": method, "params": {}} - ).encode() - result = await pipeline.handle_post(body, {}) - assert result is None, method - - asyncio.run(_run()) - - def test_modern_ping_requires_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping"}).encode() - missing = await pipeline.handle_post(body, {}) - matched = await pipeline.handle_post(body, {"Mcp-Method": "ping"}) - assert missing is not None - assert missing[0] == 400 - assert missing[1]["error"]["code"] == -32020 - assert matched is not None - assert matched[0] == 200 - assert matched[1]["result"] == {} - - asyncio.run(_run()) + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_http_tools_call_missing_and_mismatch_and_match(self, monkeypatch): import os @@ -2898,123 +2213,9 @@ def test_table_covers_modern_surface(self): assert "tasks/get" in methods assert "tools/call" in methods - @pytest.mark.parametrize( - "contract", - [ - row - for row in MODERN_METHOD_CONTRACTS - if row.method not in {"initialize", "notifications/initialized"} - ], - ids=lambda row: row.method, - ) - def test_modern_missing_mcp_method_is_header_mismatch(self, contract): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": contract.method, - "params": _contract_params(contract.method), - } - ).encode() - status, resp = await pipeline.handle_post(body, {}) - assert status == 400 - assert resp["error"]["code"] == HEADER_BODY_MISMATCH - - asyncio.run(_run()) - - @pytest.mark.parametrize( - "contract", - [ - row - for row in MODERN_METHOD_CONTRACTS - if row.method not in {"initialize", "notifications/initialized"} - ], - ids=lambda row: row.method, - ) - def test_modern_unsupported_protocol_version(self, contract): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject") - ) - params = _contract_params(contract.method) - body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": contract.method, - "params": params, - } - ).encode() - headers = { - "Mcp-Method": contract.method, - "MCP-Protocol-Version": "1999-01-01", - } - if mcp_name_is_required(contract.method): - field = mcp_name_field(contract.method) - headers["Mcp-Name"] = params[field] - status, resp = await pipeline.handle_post(body, headers) - assert status == 400 - assert resp["error"]["code"] == -32022 - - asyncio.run(_run()) - - def test_resources_read_and_prompts_get_require_mcp_name(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext( - "srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="reject" - ) - ) - read_body = json.dumps( - { - "jsonrpc": "2.0", - "id": 1, - "method": "resources/read", - "params": {"uri": "mcp://demo/item"}, - } - ).encode() - prompt_body = json.dumps( - { - "jsonrpc": "2.0", - "id": 2, - "method": "prompts/get", - "params": {"name": "demo"}, - } - ).encode() - read_missing = await pipeline.handle_post( - read_body, {"Mcp-Method": "resources/read"} - ) - prompt_missing = await pipeline.handle_post( - prompt_body, {"Mcp-Method": "prompts/get"} - ) - assert read_missing is not None - assert read_missing[0] == 400 - assert read_missing[1]["error"]["code"] == HEADER_BODY_MISMATCH - assert prompt_missing is not None - assert prompt_missing[0] == 400 - assert prompt_missing[1]["error"]["code"] == HEADER_BODY_MISMATCH - assert read_missing[1]["error"]["code"] == prompt_missing[1]["error"]["code"] - - asyncio.run(_run()) - - def test_auto_discover_still_allows_missing_mcp_method(self): - async def _run(): - pipeline = StatelessIngressPipeline( - IngressContext("srv", "1.0.0", MODERN_PROTOCOL_VERSION, wire_mode="stateless") - ) - body = json.dumps( - {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {}} - ).encode() - assert await pipeline.handle_post(body, {}) is None - - asyncio.run(_run()) - class TestProtocolVersionCrossCheck: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_http_mismatch_is_rejected_and_header_only_succeeds(self, monkeypatch): import os @@ -3089,6 +2290,7 @@ class VersionCrossCheckApp: class TestUnsupportedProtocolVersionHttp: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_http_unknown_version_is_rejected_and_supported_proceeds(self, monkeypatch): import os @@ -3170,6 +2372,7 @@ def test_echo_uses_supported_request_version(self): supported={"2026-07-28", "2025-06-18"}, ) == MODERN_PROTOCOL_VERSION + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_http_success_and_error_echo_headers(self, monkeypatch): import os @@ -3257,6 +2460,7 @@ class EchoHeadersApp: class TestCorsExposeHeaders: + @pytest.mark.xfail(run=False, reason=SIDECAR_REMOVED_REASON) def test_http_mcp_response_exposes_echo_headers_not_session_id(self, monkeypatch): from pydantic import BaseModel, Field from starlette.testclient import TestClient From acb37fb24f8f51f14cae8f741465ff02cf4891e6 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Tue, 27 Oct 2026 18:02:44 +0530 Subject: [PATCH 023/146] test: align tests that were hidden by collection errors with the hidden-tasks 2026 wire - task conformance tests (blueprint) build their app with protocol_era=legacy - tasks/* handlers are absent on auto/modern, so the tests now assert that instead of calling a handler that no longer exists - tasks/result and tasks/list are no longer listed as deprecated modern methods - the SEP-2243 method table has no tasks/* rows on the 2026 wire - tools_list_baseline.json: auto and modern no longer carry _meta.task_support --- tests/fixtures/tools_list_baseline.json | 4 ++-- tests/test_mcp20_blueprint.py | 19 +++++++------------ tests/test_mcp20_deprecated.py | 15 +++++---------- tests/test_mcp20_jsonrpc_wire.py | 2 +- tests/test_mcp20_stateless_http.py | 3 ++- 5 files changed, 17 insertions(+), 26 deletions(-) diff --git a/tests/fixtures/tools_list_baseline.json b/tests/fixtures/tools_list_baseline.json index 6edb97d..e0e9a20 100644 --- a/tests/fixtures/tools_list_baseline.json +++ b/tests/fixtures/tools_list_baseline.json @@ -1,5 +1,5 @@ { "legacy": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}", - "auto": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}", - "modern": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"task_support\":\"forbidden\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}" + "auto": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}", + "modern": "{\"_meta\":{\"io.modelcontextprotocol/cacheHint\":{\"ttlMs\":60000,\"cacheScope\":\"private\"}},\"ttlMs\":0,\"cacheScope\":\"private\",\"tools\":[{\"name\":\"alpha\",\"description\":\"first\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"alpha\",\"description\":\"first\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}},{\"name\":\"beta\",\"description\":\"second\",\"inputSchema\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"},\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":false,\"openWorldHint\":true},\"_meta\":{\"is_initial\":false,\"visibility\":\"visible\",\"openai/type\":\"function\",\"openai/function\":{\"name\":\"beta\",\"description\":\"second\",\"parameters\":{\"properties\":{\"q\":{\"default\":\"\",\"title\":\"Q\",\"type\":\"string\"}},\"title\":\"In\",\"type\":\"object\",\"$schema\":\"https://json-schema.org/draft/2020-12/schema\"}}}}],\"resultType\":\"complete\"}" } \ No newline at end of file diff --git a/tests/test_mcp20_blueprint.py b/tests/test_mcp20_blueprint.py index 98645a4..7170ba3 100644 --- a/tests/test_mcp20_blueprint.py +++ b/tests/test_mcp20_blueprint.py @@ -172,15 +172,10 @@ class JsonRpcApp: async def _run(): app = await McpApplicationFactory.create(JsonRpcApp) - handler = app.mcp_server.request_handlers[types.GetTaskPayloadRequest] - with pytest.raises(McpError) as exc: - await handler( - types.GetTaskPayloadRequest( - method="tasks/result", - params=types.GetTaskPayloadRequestParams(taskId="missing"), - ) - ) - assert exc.value.error.code == types.METHOD_NOT_FOUND + # The 2026 wire has no Tasks surface, so tasks/result has no handler at all + # and the official server answers it as method-not-found. + assert types.GetTaskPayloadRequest not in app.mcp_server.request_handlers + assert app.mcp_server.has_task_support is False asyncio.run(_run()) @@ -197,7 +192,7 @@ async def slow(self, input: EchoInput, context: ExecutionContext) -> str: class TasksModule: pass - @mcp_app(module=TasksModule, server=ServerConfig(name="tasks")) + @mcp_app(module=TasksModule, server=ServerConfig(name="tasks", protocol_era="legacy")) class TasksApp: pass @@ -246,7 +241,7 @@ async def noop_bp(self, input: EchoInput, context: ExecutionContext) -> str: class GetModule: pass - @mcp_app(module=GetModule, server=ServerConfig(name="get")) + @mcp_app(module=GetModule, server=ServerConfig(name="get", protocol_era="legacy")) class GetApp: pass @@ -324,7 +319,7 @@ async def noop_iso(self, input: EchoInput, context: ExecutionContext) -> str: class IsoModule: pass - @mcp_app(module=IsoModule, server=ServerConfig(name="iso")) + @mcp_app(module=IsoModule, server=ServerConfig(name="iso", protocol_era="legacy")) class IsoApp: pass diff --git a/tests/test_mcp20_deprecated.py b/tests/test_mcp20_deprecated.py index e637ef7..27944b0 100644 --- a/tests/test_mcp20_deprecated.py +++ b/tests/test_mcp20_deprecated.py @@ -152,27 +152,22 @@ async def life_send(message): await asyncio.wait_for(task, timeout=2) -def test_auto_official_handler_still_lists_tasks(monkeypatch): +def test_auto_official_handler_hides_tasks_list(monkeypatch): + # Tasks are hidden on the 2026 wire (auto included), so there is no handler. monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) monkeypatch.delenv("MCP_STATELESS", raising=False) app, _ = _echo_http_app("auto") try: - handler = app.mcp_server.request_handlers[types.ListTasksRequest] - result = asyncio.run(handler(types.ListTasksRequest(method="tasks/list", params={}))) - assert result.tasks == [] + assert types.ListTasksRequest not in app.mcp_server.request_handlers finally: DIContainer.reset() -def test_modern_official_handler_rejects_tasks_list(monkeypatch): +def test_modern_official_handler_hides_tasks_list(monkeypatch): monkeypatch.delenv("NITRO_MCP_PROTOCOL_VERSION", raising=False) monkeypatch.delenv("MCP_STATELESS", raising=False) app, _ = _echo_http_app("modern") try: - handler = app.mcp_server.request_handlers[types.ListTasksRequest] - with pytest.raises(McpError) as exc: - asyncio.run(handler(types.ListTasksRequest(method="tasks/list", params={}))) - assert exc.value.error.code == types.METHOD_NOT_FOUND - assert exc.value.error.message == deprecated_method_message("tasks/list") + assert types.ListTasksRequest not in app.mcp_server.request_handlers finally: DIContainer.reset() diff --git a/tests/test_mcp20_jsonrpc_wire.py b/tests/test_mcp20_jsonrpc_wire.py index 1f368cc..d7c442e 100644 --- a/tests/test_mcp20_jsonrpc_wire.py +++ b/tests/test_mcp20_jsonrpc_wire.py @@ -292,7 +292,7 @@ def test_tool_execution_error_maps_to_result_not_rpc_error(self): class TestDeprecatedMethods: @pytest.mark.parametrize( "method", - ["tasks/result", "tasks/list", "resources/subscribe", "logging/setLevel"], + ["resources/subscribe", "logging/setLevel"], ) def test_deprecated_methods_have_messages(self, method): assert deprecated_method_message(method) is not None diff --git a/tests/test_mcp20_stateless_http.py b/tests/test_mcp20_stateless_http.py index 11adc74..8767a47 100644 --- a/tests/test_mcp20_stateless_http.py +++ b/tests/test_mcp20_stateless_http.py @@ -2210,7 +2210,8 @@ def test_table_covers_modern_surface(self): assert "resources/read" in methods assert "prompts/get" in methods assert "completion/complete" in methods - assert "tasks/get" in methods + # Tasks are hidden on the 2026 wire until tasks/update exists. + assert not any(m.startswith("tasks/") for m in methods) assert "tools/call" in methods From 43594438b006baa0117e8d298025ef719a7867d5 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Tue, 27 Oct 2026 18:27:53 +0530 Subject: [PATCH 024/146] feat(auth): add SecretValue wrapper for secrets (#69) SecretValue keeps a secret out of logs, repr, str, f-strings, tracebacks, pickles and Pydantic/JSON output. The raw value is only available through unwrap(). - port of the SecretValue from closed PR #4 with the snake_case API only - pickling redacts: a pickled secret loads back with no value and unwrap() raises - Pydantic v2 fields validate a SecretValue or str and serialize as the redacted marker - equality uses hmac.compare_digest - add is_secret_value() and unwrap_secret() - JWTModule(secret=...), ApiKeyModule(keys=[...]), OAuthService client secrets and ConfigService defaults/get_secret() accept a SecretValue; plain str still works --- README.md | 26 ++ nitrostack/__init__.py | 8 + nitrostack/auth/api_key.py | 13 +- nitrostack/auth/config.py | 22 ++ nitrostack/auth/jwt.py | 12 +- nitrostack/auth/oauth.py | 14 +- nitrostack/auth/oauth_module.py | 5 +- nitrostack/auth/secret.py | 221 ++++++++++++++++ tests/test_secret_value.py | 432 ++++++++++++++++++++++++++++++++ 9 files changed, 741 insertions(+), 12 deletions(-) create mode 100644 nitrostack/auth/secret.py create mode 100644 tests/test_secret_value.py diff --git a/README.md b/README.md index 01dcd2a..bf299b1 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,32 @@ The SDK reads standard settings from the environment or `.env` files: | `NITROSTACK_LOG_TO_STDOUT` | Set to `true` to allow logging to stdout under stdio transport (Caution: may corrupt protocol stream). | | `NITROSTACK_HTTP_DEBUG` | Set to `1` to log every HTTP request (method, path, headers, body) and response status to stderr. Use when diagnosing a client that fails to connect: uvicorn's access log shows neither headers nor timestamps. | +### Keeping secrets out of logs (`SecretValue`) + +Wrap a secret in `SecretValue` so it cannot end up in logs, `repr`, tracebacks, pickles or +serialized output. Everything prints `[SecretValue: REDACTED]`. The raw value is only available +through `unwrap()`. + +```python +from nitrostack import SecretValue, JWTModule, ApiKeyModule + +jwt_secret = SecretValue.from_env("JWT_SECRET") # raises if the variable is not set +optional = SecretValue.from_env_optional("MAYBE_SECRET") # None if it is not set + +print(f"{jwt_secret}") # [SecretValue: REDACTED] +JWTModule.for_root(secret=jwt_secret) +ApiKeyModule.for_root(keys=[SecretValue.from_env("SERVICE_API_KEY")]) +``` + +- `SecretValue.from_value("...", allow_hardcoded=True, reason="test")` is for values written in code + (tests). It must be allowed explicitly and it warns. +- Pickling and Pydantic/JSON output are redacted too. A pickled secret loads back with no value, and + `unwrap()` raises instead of returning a fake one. +- `==` compares with `hmac.compare_digest`. +- `JWTModule`, `ApiKeyModule`, `OAuthModule` (the two client secrets) and `ConfigService` + (`defaults`, `get_secret()`) accept a `SecretValue` or a plain `str`. +- `is_secret_value(x)` and `unwrap_secret(x)` help code that takes either. + --- ## Transport Options diff --git a/nitrostack/__init__.py b/nitrostack/__init__.py index 9f1c3d5..4e80cf4 100644 --- a/nitrostack/__init__.py +++ b/nitrostack/__init__.py @@ -113,6 +113,11 @@ ConfigModule, ConfigService, ) +from nitrostack.auth.secret import ( + SecretValue, + is_secret_value, + unwrap_secret, +) from nitrostack.widgets import ( Component, WidgetCsp, @@ -204,6 +209,9 @@ "AudienceMismatchError", "ConfigModule", "ConfigService", + "SecretValue", + "is_secret_value", + "unwrap_secret", "NitroTestingModule", "TaskContext", "TaskCancelledError", diff --git a/nitrostack/auth/api_key.py b/nitrostack/auth/api_key.py index fd0eaf2..6cb98b9 100644 --- a/nitrostack/auth/api_key.py +++ b/nitrostack/auth/api_key.py @@ -1,9 +1,10 @@ import secrets import hashlib import os -from typing import List, Optional +from typing import List, Optional, Sequence, Union from nitrostack.core.module import module from nitrostack.core.di import DIContainer +from nitrostack.auth.secret import SecretValue, unwrap_secret class ApiKeyService: def __init__( @@ -11,10 +12,13 @@ def __init__( keys_env_prefix: str = "API_KEY", header_name: str = "x-api-key", hashed: bool = False, + keys: Optional[Sequence[Union[SecretValue, str]]] = None, ): self.keys_env_prefix = keys_env_prefix self.header_name = header_name self.hashed = hashed + # Keys passed in code are used in addition to the ones found in the environment. + self._explicit_keys: List[Union[SecretValue, str]] = list(keys or []) self._keys: List[str] = [] self._load_keys() @@ -29,7 +33,8 @@ def _load_keys(self) -> None: for k, v in os.environ.items(): if k.startswith(f"{self.keys_env_prefix}_"): keys.append(v) - + + keys.extend(unwrap_secret(k) for k in self._explicit_keys) self._keys = keys def get_keys(self) -> List[str]: @@ -65,11 +70,13 @@ def for_root( keys_env_prefix: str = "API_KEY", header_name: str = "x-api-key", hashed: bool = False, + keys: Optional[Sequence[Union[SecretValue, str]]] = None, ): service = ApiKeyService( keys_env_prefix=keys_env_prefix, header_name=header_name, - hashed=hashed + hashed=hashed, + keys=keys, ) DIContainer.get_instance().register_value(ApiKeyService, service) return cls diff --git a/nitrostack/auth/config.py b/nitrostack/auth/config.py index f97c56d..a521972 100644 --- a/nitrostack/auth/config.py +++ b/nitrostack/auth/config.py @@ -2,6 +2,7 @@ from typing import Dict, Any, Callable, Optional from nitrostack.core.module import module from nitrostack.core.di import DIContainer, injectable +from nitrostack.auth.secret import SecretValue @injectable() class ConfigService: @@ -12,6 +13,8 @@ def __init__( defaults: Optional[Dict[str, Any]] = None, validate_fn: Optional[Callable[[Dict[str, Any]], bool]] = None, ): + # ``defaults`` values may be SecretValue instances. They are kept as they are, so + # printing the config or calling ``get()`` never shows the raw secret. self._config: Dict[str, Any] = {} if defaults: self._config.update(defaults) @@ -52,6 +55,25 @@ def get_or_throw(self, key: str) -> Any: raise KeyError(f"Configuration key '{key}' is required but not found.") return self._config[key] + def get_secret(self, key: str, default: Optional[SecretValue] = None) -> Optional[SecretValue]: + """Return a configuration value as a ``SecretValue`` (or ``default`` when missing). + + A value that is already a ``SecretValue`` is returned as it is. A plain string is + wrapped, so callers can pass it on without it being printed by accident. + """ + value = self._config.get(key) + if value is None or value == "": + return default + if isinstance(value, SecretValue): + return value + return SecretValue(str(value), source="config") + + def get_secret_or_throw(self, key: str) -> SecretValue: + secret = self.get_secret(key) + if secret is None: + raise KeyError(f"Configuration key '{key}' is required but not found.") + return secret + @module(name="ConfigModule") class ConfigModule: @classmethod diff --git a/nitrostack/auth/jwt.py b/nitrostack/auth/jwt.py index 19bd0c7..84c9c5b 100644 --- a/nitrostack/auth/jwt.py +++ b/nitrostack/auth/jwt.py @@ -4,9 +4,10 @@ import hashlib import base64 import os -from typing import Any, Dict, Optional +from typing import Any, Dict, Optional, Union from nitrostack.core.module import module from nitrostack.core.di import DIContainer +from nitrostack.auth.secret import SecretValue, unwrap_secret class JWTService: def __init__( @@ -15,13 +16,18 @@ def __init__( expires_in: str = "24h", audience: Optional[str] = None, issuer: Optional[str] = None, + secret: Union[SecretValue, str, None] = None, ): self.secret_env_var = secret_env_var + # An explicit secret wins over the environment variable. Prefer a SecretValue. + self._secret = secret self.expires_in = expires_in self.audience = audience self.issuer = issuer def get_secret(self) -> str: + if self._secret is not None: + return unwrap_secret(self._secret) secret = os.environ.get(self.secret_env_var) if not secret: # Fallback for dev mode/testing so it doesn't fail hard if not set @@ -116,12 +122,14 @@ def for_root( expires_in: str = "24h", audience: Optional[str] = None, issuer: Optional[str] = None, + secret: Union[SecretValue, str, None] = None, ): service = JWTService( secret_env_var=secret_env_var, expires_in=expires_in, audience=audience, - issuer=issuer + issuer=issuer, + secret=secret, ) DIContainer.get_instance().register_value(JWTService, service) return cls diff --git a/nitrostack/auth/oauth.py b/nitrostack/auth/oauth.py index b6b3358..c5b3095 100644 --- a/nitrostack/auth/oauth.py +++ b/nitrostack/auth/oauth.py @@ -4,11 +4,12 @@ import json import urllib.request import urllib.parse -from typing import List, Optional, Dict, Any, Tuple +from typing import List, Optional, Dict, Any, Tuple, Union from http.server import HTTPServer, BaseHTTPRequestHandler import threading from nitrostack.core.module import module from nitrostack.core.di import DIContainer +from nitrostack.auth.secret import SecretValue, unwrap_secret from nitrostack.auth.oauth_module import ( apply_cimd_to_registration_body, build_authorization_server_metadata, @@ -72,7 +73,7 @@ def __init__( scopes_supported: List[str], token_introspection_endpoint: Optional[str] = None, token_introspection_client_id: Optional[str] = None, - token_introspection_client_secret: Optional[str] = None, + token_introspection_client_secret: Union[SecretValue, str, None] = None, discovery_port: int = 3005, jwks_uri: Optional[str] = None, audience: Optional[str] = None, @@ -80,7 +81,7 @@ def __init__( token_cache_seconds: Optional[int] = None, enable_client_registration: Optional[bool] = None, static_client_id: Optional[str] = None, - static_client_secret: Optional[str] = None, + static_client_secret: Union[SecretValue, str, None] = None, ): self.resource_uri = resource_uri self.authorization_servers = authorization_servers @@ -375,7 +376,8 @@ async def _introspect_via_endpoint(self, token: str) -> Dict[str, Any]: # Add basic auth if client credentials provided if self.token_introspection_client_id and self.token_introspection_client_secret: import base64 - auth_str = f"{self.token_introspection_client_id}:{self.token_introspection_client_secret}" + client_secret = unwrap_secret(self.token_introspection_client_secret) + auth_str = f"{self.token_introspection_client_id}:{client_secret}" encoded_auth = base64.b64encode(auth_str.encode("utf-8")).decode("utf-8") req.add_header("Authorization", f"Basic {encoded_auth}") @@ -460,7 +462,7 @@ def for_root( scopes_supported: List[str], token_introspection_endpoint: Optional[str] = None, token_introspection_client_id: Optional[str] = None, - token_introspection_client_secret: Optional[str] = None, + token_introspection_client_secret: Union[SecretValue, str, None] = None, discovery_port: int = 3005, jwks_uri: Optional[str] = None, audience: Optional[str] = None, @@ -468,7 +470,7 @@ def for_root( token_cache_seconds: Optional[int] = None, enable_client_registration: Optional[bool] = None, static_client_id: Optional[str] = None, - static_client_secret: Optional[str] = None, + static_client_secret: Union[SecretValue, str, None] = None, ): if not resource_uri or not str(resource_uri).strip(): raise ConfigurationError("OAuthModule.for_root requires resource_uri") diff --git a/nitrostack/auth/oauth_module.py b/nitrostack/auth/oauth_module.py index bfc59d1..d0d6176 100644 --- a/nitrostack/auth/oauth_module.py +++ b/nitrostack/auth/oauth_module.py @@ -20,6 +20,8 @@ import time from typing import Any, Dict, Optional, TYPE_CHECKING +from nitrostack.auth.secret import unwrap_secret + from nitrostack.auth.cimd import ( looks_like_cimd_url, resolve_cimd_sync, @@ -153,7 +155,8 @@ def build_registration_response(service: "OAuthService", body: Optional[Dict[str """ body = body or {} client_id = service.static_client_id - client_secret = service.static_client_secret or "" + # The registration response must hand the real secret to the client, so unwrap it here. + client_secret = unwrap_secret(service.static_client_secret) if service.static_client_secret else "" return { "client_id": client_id, "client_secret": client_secret, diff --git a/nitrostack/auth/secret.py b/nitrostack/auth/secret.py new file mode 100644 index 0000000..452afac --- /dev/null +++ b/nitrostack/auth/secret.py @@ -0,0 +1,221 @@ +"""``SecretValue``: a wrapper that keeps a secret out of logs, ``repr``, tracebacks, +pickles and serialized output. + +The raw value is only reachable through :meth:`SecretValue.unwrap`. Everything else +that could print or serialize the object shows ``[SecretValue: REDACTED]`` instead. + +>>> s = SecretValue.from_value("a-long-test-secret-value", allow_hardcoded=True) +>>> f"{s}", repr(s) +('[SecretValue: REDACTED]', '[SecretValue: REDACTED]') +""" + +from __future__ import annotations + +import hmac +import os +import secrets as _secrets +import warnings +from typing import Any, Optional, Union + +REDACTED = "[SecretValue: REDACTED]" + +# Secrets shorter than this still work, but trigger a warning. +MIN_RECOMMENDED_LENGTH = 16 + +# Per-process key so hash() never exposes anything derived from the value alone. +_HASH_KEY = _secrets.token_bytes(32) + + +def _redacted_after_pickle(source: str) -> "SecretValue": + """Rebuild a ``SecretValue`` that carries no value (used when unpickling).""" + return SecretValue._empty(source) + + +class SecretValue: + """Holds a secret string and refuses to reveal it by accident.""" + + __slots__ = ("_value", "source") + + def __init__(self, value: str, source: str = "env") -> None: + if not isinstance(value, str): + raise TypeError("SecretValue needs a str value") + if not value: + raise ValueError("Secret value cannot be empty") + if len(value) < MIN_RECOMMENDED_LENGTH: + warnings.warn( + f"[SecretValue] Secret is shorter than {MIN_RECOMMENDED_LENGTH} characters. " + "Consider using a longer secret.", + UserWarning, + stacklevel=2, + ) + self._value: Optional[str] = value + self.source = source + + # ------------------------------------------------------------------ + # Construction + # ------------------------------------------------------------------ + + @classmethod + def _empty(cls, source: str) -> "SecretValue": + """A secret that was redacted on its way through pickle. It has no value.""" + obj = cls.__new__(cls) + obj._value = None + obj.source = source + return obj + + @classmethod + def from_env(cls, env_var_name: str) -> "SecretValue": + """Read a required secret from an environment variable.""" + value = os.environ.get(env_var_name) + if not value: + raise ValueError( + f"Environment variable {env_var_name} is not set. " + "Set it in your environment or .env file." + ) + return cls(value, "env") + + @classmethod + def from_env_optional(cls, env_var_name: str) -> Optional["SecretValue"]: + """Read a secret from an environment variable, or ``None`` when it is not set.""" + value = os.environ.get(env_var_name) + if not value: + return None + return cls(value, "env") + + @classmethod + def from_value( + cls, + value: str, + allow_hardcoded: bool = False, + reason: Optional[str] = None, + ) -> "SecretValue": + """Wrap a value that is written in code. This must be allowed explicitly.""" + if not allow_hardcoded: + raise ValueError( + "Hardcoded secrets are not allowed. Use SecretValue.from_env() to load " + "secrets from environment variables. If you must use a hardcoded value " + "(for example in a test), pass allow_hardcoded=True." + ) + warnings.warn( + "[SecretValue] Using a hardcoded secret value. " + f"Reason: {reason or 'not specified'}. Do not do this in production.", + UserWarning, + stacklevel=2, + ) + return cls(value, "explicit") + + # ------------------------------------------------------------------ + # Access + # ------------------------------------------------------------------ + + def unwrap(self) -> str: + """Return the raw secret. Call this only where the value is really needed.""" + if self._value is None: + raise ValueError( + "This SecretValue was redacted during serialization and has no value." + ) + return self._value + + def is_from_environment(self) -> bool: + return self.source == "env" + + # ------------------------------------------------------------------ + # Redaction: str, repr, format, f-strings, logging, tracebacks + # ------------------------------------------------------------------ + + def __str__(self) -> str: + return REDACTED + + def __repr__(self) -> str: + return REDACTED + + def __format__(self, format_spec: str) -> str: + return format(REDACTED, format_spec) + + # ------------------------------------------------------------------ + # Comparison + # ------------------------------------------------------------------ + + def __eq__(self, other: object) -> bool: + if isinstance(other, SecretValue): + other_value = other._value + elif isinstance(other, str): + other_value = other + else: + return NotImplemented + if self._value is None or other_value is None: + return False + return hmac.compare_digest(self._value.encode("utf-8"), other_value.encode("utf-8")) + + def __ne__(self, other: object) -> bool: + result = self.__eq__(other) + return result if result is NotImplemented else not result + + def __hash__(self) -> int: + if self._value is None: + return hash(("SecretValue", "redacted")) + return hash(hmac.digest(_HASH_KEY, self._value.encode("utf-8"), "sha256")) + + def __bool__(self) -> bool: + return self._value is not None + + # ------------------------------------------------------------------ + # Pickle and copy + # ------------------------------------------------------------------ + + def __reduce__(self): + # The pickle holds only the source. Loading it gives a SecretValue with no + # value, so a secret can neither leak through a pickle nor be silently + # replaced by a placeholder string. + return (_redacted_after_pickle, (self.source,)) + + def __copy__(self) -> "SecretValue": + return self # immutable, so sharing is safe + + def __deepcopy__(self, memo: Any) -> "SecretValue": + return self + + # ------------------------------------------------------------------ + # Pydantic v2: validation and JSON/dict serialization + # ------------------------------------------------------------------ + + @classmethod + def __get_pydantic_core_schema__(cls, source_type: Any, handler: Any): + from pydantic_core import core_schema + + def validate(value: Any) -> "SecretValue": + if isinstance(value, SecretValue): + return value + if isinstance(value, str): + return cls(value, "explicit") + raise ValueError("expected a SecretValue or a string") + + return core_schema.no_info_plain_validator_function( + validate, + serialization=core_schema.plain_serializer_function_ser_schema( + lambda _value: REDACTED, + return_schema=core_schema.str_schema(), + when_used="always", + ), + ) + + @classmethod + def __get_pydantic_json_schema__(cls, core_schema_: Any, handler: Any): + return {"type": "string", "format": "password", "writeOnly": True} + + +def is_secret_value(value: Any) -> bool: + """True when ``value`` is a ``SecretValue``.""" + return isinstance(value, SecretValue) + + +def unwrap_secret(secret: Union[SecretValue, str]) -> str: + """Return the raw string for a ``SecretValue`` or a plain ``str``. + + Plain strings are accepted so existing code keeps working. + """ + if isinstance(secret, SecretValue): + return secret.unwrap() + if isinstance(secret, str): + return secret + raise TypeError(f"Expected a SecretValue or str, got {type(secret).__name__}") diff --git a/tests/test_secret_value.py b/tests/test_secret_value.py new file mode 100644 index 0000000..53803ec --- /dev/null +++ b/tests/test_secret_value.py @@ -0,0 +1,432 @@ +"""Issue #69: ``SecretValue`` keeps secrets out of logs, repr, pickles and serialized output.""" + +from __future__ import annotations + +import base64 +import copy +import io +import json +import logging +import pickle +import traceback +import warnings + +import pytest +from pydantic import BaseModel + +from nitrostack import ConfigService, DIContainer, SecretValue, is_secret_value, unwrap_secret +from nitrostack.auth.api_key import ApiKeyModule, ApiKeyService +from nitrostack.auth.jwt import JWTModule, JWTService +from nitrostack.auth.oauth import OAuthModule, OAuthService +from nitrostack.auth.oauth_module import build_registration_response +from nitrostack.auth.secret import REDACTED + +RAW = "s3cr3t-value-that-must-not-leak-0123456789" + + +def _secret(value: str = RAW) -> SecretValue: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return SecretValue.from_value(value, allow_hardcoded=True, reason="test") + + +def setup_function() -> None: + DIContainer.reset() + + +def teardown_function() -> None: + DIContainer.reset() + + +# --------------------------------------------------------------------------- +# Construction +# --------------------------------------------------------------------------- + + +def test_from_env_reads_the_variable_and_marks_the_source(monkeypatch): + monkeypatch.setenv("MY_SECRET", RAW) + secret = SecretValue.from_env("MY_SECRET") + assert secret.unwrap() == RAW + assert secret.is_from_environment() is True + + +def test_from_env_raises_when_missing_and_optional_returns_none(monkeypatch): + monkeypatch.delenv("MISSING_SECRET", raising=False) + with pytest.raises(ValueError, match="MISSING_SECRET"): + SecretValue.from_env("MISSING_SECRET") + assert SecretValue.from_env_optional("MISSING_SECRET") is None + monkeypatch.setenv("MISSING_SECRET", "") + assert SecretValue.from_env_optional("MISSING_SECRET") is None + + +def test_the_missing_variable_error_never_contains_a_value(monkeypatch): + monkeypatch.delenv("MISSING_SECRET", raising=False) + with pytest.raises(ValueError) as exc: + SecretValue.from_env("MISSING_SECRET") + assert RAW not in str(exc.value) + + +def test_hardcoded_values_need_explicit_permission(): + with pytest.raises(ValueError, match="allow_hardcoded"): + SecretValue.from_value(RAW) + with pytest.warns(UserWarning, match="hardcoded"): + secret = SecretValue.from_value(RAW, allow_hardcoded=True, reason="unit test") + assert secret.unwrap() == RAW + assert secret.is_from_environment() is False + + +def test_empty_and_non_string_values_are_rejected(): + with pytest.raises(ValueError): + SecretValue("") + with pytest.raises(TypeError): + SecretValue(12345) # type: ignore[arg-type] + + +def test_short_secrets_warn_but_still_work(): + with pytest.warns(UserWarning, match="shorter than 16"): + secret = SecretValue("short") + assert secret.unwrap() == "short" + + +# --------------------------------------------------------------------------- +# Acceptance criteria: the raw value never appears +# --------------------------------------------------------------------------- + + +def test_str_repr_and_fstring_are_redacted(): + secret = _secret() + assert str(secret) == REDACTED + assert repr(secret) == REDACTED + assert f"{secret}" == REDACTED + assert f"{secret!r}" == REDACTED + assert "%s %r" % (secret, secret) == f"{REDACTED} {REDACTED}" + assert "{}".format(secret) == REDACTED + assert RAW not in f"{secret:>40}" + + +def test_containers_holding_a_secret_do_not_leak_in_repr(): + secret = _secret() + assert RAW not in repr({"key": secret}) + assert RAW not in repr([secret]) + assert RAW not in repr((secret,)) + + +def test_there_is_no_instance_dict_to_dump(): + with pytest.raises(TypeError): + vars(_secret()) + + +def test_logging_never_contains_the_raw_value(caplog): + secret = _secret() + logger = logging.getLogger("secret-test") + stream = io.StringIO() + handler = logging.StreamHandler(stream) + handler.setFormatter(logging.Formatter("%(levelname)s %(message)s %(args)s")) + logger.addHandler(handler) + logger.setLevel(logging.DEBUG) + try: + with caplog.at_level(logging.DEBUG, logger="secret-test"): + logger.info("token is %s", secret) + logger.info("token is %r", secret) + logger.info(f"token is {secret}") + logger.info("token is %(s)s", {"s": secret}) + try: + raise RuntimeError(f"failed with {secret}") + except RuntimeError: + logger.exception("boom with %s", secret) + finally: + logger.removeHandler(handler) + assert RAW not in stream.getvalue() + assert RAW not in caplog.text + assert all(RAW not in record.getMessage() for record in caplog.records) + assert REDACTED in caplog.text + + +def test_tracebacks_do_not_contain_the_raw_value(): + secret = _secret() + + def fail(): + local_secret = secret # noqa: F841 - shows up in captured locals + raise RuntimeError(f"bad secret {secret!r}") + + try: + fail() + except RuntimeError as exc: + text = "".join(traceback.format_exception(exc, capture_locals=True)) + assert RAW not in text + assert REDACTED in text + + +def test_pickle_never_contains_the_raw_value(): + secret = _secret() + for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1): + blob = pickle.dumps(secret, protocol=protocol) + assert RAW.encode() not in blob + assert RAW.encode() not in base64.b64encode(blob) + + +def test_an_unpickled_secret_has_no_value_instead_of_a_fake_one(): + restored = pickle.loads(pickle.dumps(_secret())) + assert is_secret_value(restored) + with pytest.raises(ValueError, match="redacted during serialization"): + restored.unwrap() + assert bool(restored) is False + assert restored != _secret() + + +class Settings(BaseModel): + name: str + api_secret: SecretValue + + +def test_pydantic_serialization_is_redacted(): + model = Settings(name="svc", api_secret=_secret()) + assert RAW not in model.model_dump_json() + assert REDACTED in model.model_dump_json() + assert model.model_dump()["api_secret"] == REDACTED + assert RAW not in json.dumps(model.model_dump()) + assert RAW not in repr(model) + assert RAW not in str(model) + assert RAW not in json.dumps(model.model_json_schema()) + + +def test_pydantic_accepts_a_secret_or_a_string_and_keeps_the_value(): + from_secret = Settings(name="a", api_secret=_secret()) + from_text = Settings(name="b", api_secret=RAW) + assert from_secret.api_secret.unwrap() == RAW + assert from_text.api_secret.unwrap() == RAW + assert isinstance(from_text.api_secret, SecretValue) + with pytest.raises(ValueError): + Settings(name="c", api_secret=123) # type: ignore[arg-type] + + +def test_a_bare_secret_is_not_json_serializable_rather_than_leaking(): + with pytest.raises(TypeError): + json.dumps({"secret": _secret()}) + + +def test_json_default_hook_that_uses_str_still_redacts(): + assert RAW not in json.dumps({"secret": _secret()}, default=str) + + +# --------------------------------------------------------------------------- +# Equality, hashing, copying +# --------------------------------------------------------------------------- + + +def test_equality_compares_values_in_constant_time(monkeypatch): + calls: list[tuple[bytes, bytes]] = [] + real = __import__("hmac").compare_digest + + def spy(a, b): + calls.append((a, b)) + return real(a, b) + + monkeypatch.setattr("nitrostack.auth.secret.hmac.compare_digest", spy) + assert _secret() == _secret() + assert _secret() == RAW + assert _secret() != _secret("another-long-secret-value-xyz") + assert _secret() != "different" + assert len(calls) == 4 + + +def test_equality_with_other_types_is_false(): + assert (_secret() == 123) is False + assert (_secret() != 123) is True + + +def test_equal_secrets_hash_equal_and_the_hash_is_not_the_plain_hash(): + assert hash(_secret()) == hash(_secret()) + assert hash(_secret()) != hash(RAW) + assert len({_secret(), _secret()}) == 1 + + +def test_copy_and_deepcopy_keep_the_value(): + secret = _secret() + assert copy.copy(secret).unwrap() == RAW + nested = copy.deepcopy({"k": [secret]}) + assert nested["k"][0].unwrap() == RAW + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def test_is_secret_value_and_unwrap_secret(): + secret = _secret() + assert is_secret_value(secret) is True + assert is_secret_value(RAW) is False + assert unwrap_secret(secret) == RAW + assert unwrap_secret(RAW) == RAW # plain strings are still accepted + with pytest.raises(TypeError): + unwrap_secret(None) # type: ignore[arg-type] + with pytest.raises(TypeError): + unwrap_secret(123) # type: ignore[arg-type] + + +# --------------------------------------------------------------------------- +# Modules accept a SecretValue and still accept a plain str +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_jwt_module_accepts_secret_and_str(wrap, monkeypatch): + monkeypatch.delenv("JWT_SECRET", raising=False) + JWTModule.for_root(secret=_secret() if wrap else RAW, audience="mcp") + service = DIContainer.get_instance().resolve(JWTService) + assert service.get_secret() == RAW + token = service.create_token({"sub": "u1"}) + assert service.verify_token(token)["sub"] == "u1" + assert RAW not in token # the secret signs the token, it is not inside it + + +def test_jwt_explicit_secret_wins_over_the_environment(monkeypatch): + monkeypatch.setenv("JWT_SECRET", "from-environment-secret-value") + service = JWTService(secret=_secret()) + assert service.get_secret() == RAW + + +def test_jwt_still_uses_the_environment_when_no_secret_is_given(monkeypatch): + monkeypatch.setenv("JWT_SECRET", "from-environment-secret-value") + assert JWTService().get_secret() == "from-environment-secret-value" + + +def test_jwt_service_repr_does_not_contain_the_secret(): + assert RAW not in repr(JWTService(secret=_secret())) + assert RAW not in str(JWTService(secret=_secret())) + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_api_key_module_accepts_secret_and_str(wrap, monkeypatch): + for name in ("API_KEY", "API_KEY_1"): + monkeypatch.delenv(name, raising=False) + ApiKeyModule.for_root(keys=[_secret() if wrap else RAW]) + service = DIContainer.get_instance().resolve(ApiKeyService) + assert service.validate(RAW) is True + assert service.validate("wrong") is False + + +def test_api_key_explicit_keys_add_to_environment_keys(monkeypatch): + monkeypatch.setenv("API_KEY", "env-key-value") + service = ApiKeyService(keys=[_secret()]) + assert service.validate("env-key-value") is True + assert service.validate(RAW) is True + + +def test_api_key_hashed_mode_works_with_a_secret_key(): + service = ApiKeyService(hashed=True, keys=[SecretValue("x" * 16)]) + assert service.validate("anything") is False + hashed = service.hash_key("plain") + assert ApiKeyService(hashed=True, keys=[_secret(hashed)]).validate("plain") is True + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_oauth_registration_response_returns_the_real_client_secret(wrap): + service = OAuthService( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + enable_client_registration=True, + static_client_id="client-1", + static_client_secret=_secret() if wrap else RAW, + ) + body = build_registration_response(service) + assert body["client_secret"] == RAW + assert body["token_endpoint_auth_method"] == "client_secret_post" + if wrap: + assert RAW not in repr(service.static_client_secret) + + +def test_oauth_without_a_client_secret_is_a_public_client(): + service = OAuthService( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + enable_client_registration=True, + static_client_id="client-1", + ) + body = build_registration_response(service) + assert body["client_secret"] == "" + assert body["token_endpoint_auth_method"] == "none" + + +@pytest.mark.parametrize("wrap", [True, False], ids=["SecretValue", "str"]) +def test_oauth_introspection_sends_the_real_secret_in_basic_auth(wrap, monkeypatch): + monkeypatch.delenv("INTROSPECTION_CLIENT_SECRET", raising=False) + service = OAuthService( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + token_introspection_endpoint="http://auth.example.test/introspect", + token_introspection_client_id="svc", + token_introspection_client_secret=_secret() if wrap else RAW, + ) + seen = {} + + class FakeResponse: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return b'{"active": true}' + + def fake_urlopen(request, timeout=0): + seen["auth"] = request.get_header("Authorization") + return FakeResponse() + + monkeypatch.setattr("nitrostack.auth.oauth.urllib.request.urlopen", fake_urlopen) + import asyncio + + result = asyncio.run(service._introspect_via_endpoint("tok")) + assert result == {"active": True} + sent = base64.b64decode(seen["auth"].split(" ", 1)[1]).decode() + assert sent == f"svc:{RAW}" + + +def test_oauth_module_for_root_accepts_secret_values(): + OAuthModule.for_root( + resource_uri="http://localhost:3000", + authorization_servers=["http://auth.example.test"], + scopes_supported=["read"], + token_introspection_client_secret=_secret(), + static_client_secret=_secret(), + ) + service = DIContainer.get_instance().resolve(OAuthService) + assert is_secret_value(service.static_client_secret) + assert RAW not in repr(service.static_client_secret) + + +def test_config_service_keeps_secret_defaults_redacted(tmp_path): + config = ConfigService( + env_file_path=str(tmp_path / "missing.env"), + defaults={"DB_PASSWORD": _secret(), "PLAIN": "x"}, + ) + assert is_secret_value(config.get("DB_PASSWORD")) + assert RAW not in str(config.get("DB_PASSWORD")) + assert config.get_secret("DB_PASSWORD").unwrap() == RAW + + +def test_config_service_get_secret_wraps_plain_strings(tmp_path): + config = ConfigService(env_file_path=str(tmp_path / "missing.env"), defaults={"TOKEN": RAW}) + secret = config.get_secret("TOKEN") + assert is_secret_value(secret) + assert RAW not in f"{secret}" + assert secret.unwrap() == RAW + + +def test_config_service_get_secret_missing_empty_and_required(tmp_path): + config = ConfigService( + env_file_path=str(tmp_path / "missing.env"), + defaults={"EMPTY": ""}, + ignore_env_file=True, + ) + assert config.get_secret("NOPE_NOT_SET_ANYWHERE") is None + assert config.get_secret("EMPTY") is None + fallback = _secret() + assert config.get_secret("NOPE_NOT_SET_ANYWHERE", fallback) is fallback + with pytest.raises(KeyError): + config.get_secret_or_throw("NOPE_NOT_SET_ANYWHERE") From bf54a4b4c87219c8125a309e16438d8523c03338 Mon Sep 17 00:00:00 2001 From: Prateep07 Date: Tue, 27 Oct 2026 18:59:15 +0530 Subject: [PATCH 025/146] Fix lazy log emitter handler installation --- nitrostack/core/log_emitter.py | 36 ++++++++++++++++++++++++++++------ tests/test_log_emitter.py | 22 +++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/nitrostack/core/log_emitter.py b/nitrostack/core/log_emitter.py index 9625092..cb88a27 100644 --- a/nitrostack/core/log_emitter.py +++ b/nitrostack/core/log_emitter.py @@ -98,16 +98,20 @@ def __init__(self, max_buffer: int = DEFAULT_BUFFER_SIZE): self._max_buffer = max_buffer self._subscribers: set[_Subscriber] = set() self._lock = threading.Lock() + self._installed_handlers: dict[str, logging.Handler] = {} def subscribe(self, callback: Callable[[LogRecord], Any]) -> Callable[[], None]: """Subscribe to records; return an idempotent function to stop delivery.""" subscriber = _Subscriber(callback, self._max_buffer) with self._lock: self._subscribers.add(subscriber) + self._install_handlers_locked() def unsubscribe() -> None: with self._lock: self._subscribers.discard(subscriber) + if not self._subscribers: + self._remove_handlers_locked() subscriber.unsubscribe() return unsubscribe @@ -118,6 +122,24 @@ def _publish(self, record: LogRecord) -> None: for subscriber in subscribers: subscriber.enqueue(record) + def _install_handlers_locked(self) -> None: + # Installing on both loggers ensures records are captured even when + # the HTTP logger disables propagation for its own stderr trace output. + for name in ("nitrostack", "nitrostack.transports.http"): + logger = logging.getLogger(name) + if name in self._installed_handlers: + continue + handler = LogEmitterHandler(self) + handler._nitrostack_log_emitter = True # type: ignore[attr-defined] + logger.addHandler(handler) + self._installed_handlers[name] = handler + + def _remove_handlers_locked(self) -> None: + for name, handler in self._installed_handlers.items(): + logging.getLogger(name).removeHandler(handler) + handler.close() + self._installed_handlers.clear() + class LogEmitterHandler(logging.Handler): """Logging handler that publishes structured records to a ``LogEmitter``.""" @@ -152,12 +174,14 @@ def emit(self, record: logging.LogRecord) -> None: def install_log_handler(logger_name: str = "nitrostack") -> None: - """Attach one bridge handler to a NitroStack logger, including isolated children.""" - logger = logging.getLogger(logger_name) - if not any(getattr(handler, "_nitrostack_log_emitter", False) for handler in logger.handlers): + """Attach the bridge to a logger while global emitter subscriptions exist.""" + with log_emitter._lock: + if not log_emitter._subscribers: + return + logger = logging.getLogger(logger_name) + if logger_name in log_emitter._installed_handlers: + return handler = LogEmitterHandler(log_emitter) handler._nitrostack_log_emitter = True # type: ignore[attr-defined] logger.addHandler(handler) - - -install_log_handler() + log_emitter._installed_handlers[logger_name] = handler diff --git a/tests/test_log_emitter.py b/tests/test_log_emitter.py index 8892537..a994bfd 100644 --- a/tests/test_log_emitter.py +++ b/tests/test_log_emitter.py @@ -2,6 +2,7 @@ import logging import threading +import sys from nitrostack.core.context import FileLogger from nitrostack.core.log_emitter import LogEmitter, LogEmitterHandler, log_emitter @@ -11,6 +12,27 @@ def _wait_for(event: threading.Event) -> None: assert event.wait(2), "timed out waiting for log subscriber" +def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(capsys): + logger = logging.getLogger("nitrostack.test.last-resort") + old_level = logger.level + old_propagate = logger.propagate + old_handlers = list(logger.handlers) + try: + for handler in old_handlers: + logger.removeHandler(handler) + logger.setLevel(logging.WARNING) + logger.propagate = True + logger.warning("warning before subscription") + assert "warning before subscription" in capsys.readouterr().err + finally: + for handler in list(logger.handlers): + logger.removeHandler(handler) + for handler in old_handlers: + logger.addHandler(handler) + logger.setLevel(old_level) + logger.propagate = old_propagate + + def test_global_emitter_receives_nitrostack_records_and_extra_fields(): received = [] done = threading.Event() From 4b11a6b43f3d1423484064e6018dee9317b0e19f Mon Sep 17 00:00:00 2001 From: Prateep07 Date: Tue, 27 Oct 2026 19:12:09 +0530 Subject: [PATCH 026/146] Make lastResort logging regression test deterministic --- tests/test_log_emitter.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/test_log_emitter.py b/tests/test_log_emitter.py index a994bfd..8ee1f8f 100644 --- a/tests/test_log_emitter.py +++ b/tests/test_log_emitter.py @@ -2,7 +2,6 @@ import logging import threading -import sys from nitrostack.core.context import FileLogger from nitrostack.core.log_emitter import LogEmitter, LogEmitterHandler, log_emitter @@ -17,14 +16,22 @@ def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(capsy old_level = logger.level old_propagate = logger.propagate old_handlers = list(logger.handlers) + old_last_resort = logging.lastResort + fallback = logging.StreamHandler() try: for handler in old_handlers: logger.removeHandler(handler) + fallback.setLevel(logging.WARNING) + fallback.stream = capsys._capture.err + logging.lastResort = fallback logger.setLevel(logging.WARNING) logger.propagate = True logger.warning("warning before subscription") + assert not any(getattr(handler, "_nitrostack_log_emitter", False) for handler in logger.handlers) assert "warning before subscription" in capsys.readouterr().err finally: + logging.lastResort = old_last_resort + fallback.close() for handler in list(logger.handlers): logger.removeHandler(handler) for handler in old_handlers: From e69fd553aaa914da7de7c5becff37c51fa919dcb Mon Sep 17 00:00:00 2001 From: Prateep07 Date: Tue, 27 Oct 2026 19:19:44 +0530 Subject: [PATCH 027/146] Fix duplicate log emission and stabilize tests --- nitrostack/core/log_emitter.py | 28 +++++++++++----------------- tests/test_log_emitter.py | 20 +++++++++++++++----- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/nitrostack/core/log_emitter.py b/nitrostack/core/log_emitter.py index cb88a27..55118aa 100644 --- a/nitrostack/core/log_emitter.py +++ b/nitrostack/core/log_emitter.py @@ -123,16 +123,16 @@ def _publish(self, record: LogRecord) -> None: subscriber.enqueue(record) def _install_handlers_locked(self) -> None: - # Installing on both loggers ensures records are captured even when - # the HTTP logger disables propagation for its own stderr trace output. - for name in ("nitrostack", "nitrostack.transports.http"): - logger = logging.getLogger(name) - if name in self._installed_handlers: - continue - handler = LogEmitterHandler(self) - handler._nitrostack_log_emitter = True # type: ignore[attr-defined] - logger.addHandler(handler) - self._installed_handlers[name] = handler + self._install_handler_locked("nitrostack") + + def _install_handler_locked(self, logger_name: str) -> None: + if logger_name in self._installed_handlers: + return + logger = logging.getLogger(logger_name) + handler = LogEmitterHandler(self) + handler._nitrostack_log_emitter = True # type: ignore[attr-defined] + logger.addHandler(handler) + self._installed_handlers[logger_name] = handler def _remove_handlers_locked(self) -> None: for name, handler in self._installed_handlers.items(): @@ -178,10 +178,4 @@ def install_log_handler(logger_name: str = "nitrostack") -> None: with log_emitter._lock: if not log_emitter._subscribers: return - logger = logging.getLogger(logger_name) - if logger_name in log_emitter._installed_handlers: - return - handler = LogEmitterHandler(log_emitter) - handler._nitrostack_log_emitter = True # type: ignore[attr-defined] - logger.addHandler(handler) - log_emitter._installed_handlers[logger_name] = handler + log_emitter._install_handler_locked(logger_name) diff --git a/tests/test_log_emitter.py b/tests/test_log_emitter.py index 8ee1f8f..725a7c6 100644 --- a/tests/test_log_emitter.py +++ b/tests/test_log_emitter.py @@ -1,6 +1,7 @@ from __future__ import annotations import logging +import io import threading from nitrostack.core.context import FileLogger @@ -17,18 +18,18 @@ def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(capsy old_propagate = logger.propagate old_handlers = list(logger.handlers) old_last_resort = logging.lastResort - fallback = logging.StreamHandler() + fallback_stream = io.StringIO() + fallback = logging.StreamHandler(fallback_stream) try: for handler in old_handlers: logger.removeHandler(handler) fallback.setLevel(logging.WARNING) - fallback.stream = capsys._capture.err logging.lastResort = fallback logger.setLevel(logging.WARNING) logger.propagate = True logger.warning("warning before subscription") assert not any(getattr(handler, "_nitrostack_log_emitter", False) for handler in logger.handlers) - assert "warning before subscription" in capsys.readouterr().err + assert "warning before subscription" in fallback_stream.getvalue() finally: logging.lastResort = old_last_resort fallback.close() @@ -219,7 +220,6 @@ def slow(record): _wait_for(entered) for index in range(1, 5): logger.info("%s", index) - release.set() finished = threading.Event() def last_seen(record): @@ -230,9 +230,19 @@ def last_seen(record): unsubscribe = emitter.subscribe(last_seen) logger.info("5") _wait_for(finished) + release.set() + drained = threading.Event() + # Wait for the slow subscriber's queue to drain before checking its + # bounded-buffer policy. The retained messages are the newest ones. + for _ in range(100): + if received[-2:] == ["4", "5"]: + drained.set() + break + threading.Event().wait(0.01) + _wait_for(drained) unsubscribe() assert received[0] == "0" - assert len(received) <= 4 + assert received[-2:] == ["4", "5"] finally: release.set() logger.removeHandler(handler) From 3a3cc9b9d032cb96588850ad9c40e08b3487eb0c Mon Sep 17 00:00:00 2001 From: Prateep07 Date: Tue, 27 Oct 2026 19:24:13 +0530 Subject: [PATCH 028/146] Stabilize log emitter regression tests --- tests/test_log_emitter.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/tests/test_log_emitter.py b/tests/test_log_emitter.py index 725a7c6..8020b90 100644 --- a/tests/test_log_emitter.py +++ b/tests/test_log_emitter.py @@ -12,17 +12,23 @@ def _wait_for(event: threading.Event) -> None: assert event.wait(2), "timed out waiting for log subscriber" -def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(capsys): +def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(): logger = logging.getLogger("nitrostack.test.last-resort") + root_logger = logging.getLogger() old_level = logger.level old_propagate = logger.propagate old_handlers = list(logger.handlers) + old_root_handlers = list(root_logger.handlers) old_last_resort = logging.lastResort fallback_stream = io.StringIO() fallback = logging.StreamHandler(fallback_stream) try: for handler in old_handlers: logger.removeHandler(handler) + # Pytest's root capture handler would count as a logging destination + # and prevent logging from invoking lastResort. + for handler in old_root_handlers: + root_logger.removeHandler(handler) fallback.setLevel(logging.WARNING) logging.lastResort = fallback logger.setLevel(logging.WARNING) @@ -33,6 +39,10 @@ def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(capsy finally: logging.lastResort = old_last_resort fallback.close() + for handler in list(root_logger.handlers): + root_logger.removeHandler(handler) + for handler in old_root_handlers: + root_logger.addHandler(handler) for handler in list(logger.handlers): logger.removeHandler(handler) for handler in old_handlers: @@ -89,6 +99,7 @@ def test_unsubscribe_waits_for_in_flight_callback(): emitter = LogEmitter() entered = threading.Event() release = threading.Event() + drained = threading.Event() unsubscribe_returned = threading.Event() received = [] @@ -209,6 +220,8 @@ def slow(record): if record.message == "0": entered.set() release.wait(2) + if record.message == "5": + drained.set() unsubscribe_slow = emitter.subscribe(slow) logger = logging.getLogger("nitrostack.test.bounded") @@ -231,14 +244,6 @@ def last_seen(record): logger.info("5") _wait_for(finished) release.set() - drained = threading.Event() - # Wait for the slow subscriber's queue to drain before checking its - # bounded-buffer policy. The retained messages are the newest ones. - for _ in range(100): - if received[-2:] == ["4", "5"]: - drained.set() - break - threading.Event().wait(0.01) _wait_for(drained) unsubscribe() assert received[0] == "0" From e3a6c5c20e6ffbd6debe73b281d709b53f04faa8 Mon Sep 17 00:00:00 2001 From: Prateep07 Date: Tue, 27 Oct 2026 19:29:43 +0530 Subject: [PATCH 029/146] Restrict automatic log handler to global emitter --- nitrostack/core/log_emitter.py | 7 ++++++- tests/test_log_emitter.py | 28 ++++++---------------------- 2 files changed, 12 insertions(+), 23 deletions(-) diff --git a/nitrostack/core/log_emitter.py b/nitrostack/core/log_emitter.py index 55118aa..670433a 100644 --- a/nitrostack/core/log_emitter.py +++ b/nitrostack/core/log_emitter.py @@ -105,7 +105,12 @@ def subscribe(self, callback: Callable[[LogRecord], Any]) -> Callable[[], None]: subscriber = _Subscriber(callback, self._max_buffer) with self._lock: self._subscribers.add(subscriber) - self._install_handlers_locked() + # Only the process-wide emitter owns NitroStack logger wiring. + # Standalone emitters are connected explicitly with + # LogEmitterHandler, avoiding duplicate delivery from the shared + # ``nitrostack`` logger hierarchy. + if self is log_emitter: + self._install_handlers_locked() def unsubscribe() -> None: with self._lock: diff --git a/tests/test_log_emitter.py b/tests/test_log_emitter.py index 8020b90..d99c10b 100644 --- a/tests/test_log_emitter.py +++ b/tests/test_log_emitter.py @@ -13,22 +13,15 @@ def _wait_for(event: threading.Event) -> None: def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(): - logger = logging.getLogger("nitrostack.test.last-resort") - root_logger = logging.getLogger() - old_level = logger.level - old_propagate = logger.propagate - old_handlers = list(logger.handlers) - old_root_handlers = list(root_logger.handlers) + logger = logging.Logger("nitrostack.test.last-resort") + # Detach from pytest's logging capture handlers so Python's fallback is + # the only possible destination, as it is before any NitroStack handlers + # or subscriptions have been installed. + logger.parent = None old_last_resort = logging.lastResort fallback_stream = io.StringIO() fallback = logging.StreamHandler(fallback_stream) try: - for handler in old_handlers: - logger.removeHandler(handler) - # Pytest's root capture handler would count as a logging destination - # and prevent logging from invoking lastResort. - for handler in old_root_handlers: - root_logger.removeHandler(handler) fallback.setLevel(logging.WARNING) logging.lastResort = fallback logger.setLevel(logging.WARNING) @@ -39,16 +32,6 @@ def test_nitrostack_warning_reaches_last_resort_stderr_without_subscribers(): finally: logging.lastResort = old_last_resort fallback.close() - for handler in list(root_logger.handlers): - root_logger.removeHandler(handler) - for handler in old_root_handlers: - root_logger.addHandler(handler) - for handler in list(logger.handlers): - logger.removeHandler(handler) - for handler in old_handlers: - logger.addHandler(handler) - logger.setLevel(old_level) - logger.propagate = old_propagate def test_global_emitter_receives_nitrostack_records_and_extra_fields(): @@ -213,6 +196,7 @@ def test_slow_subscriber_has_bounded_buffer_and_keeps_recent_records(): emitter = LogEmitter(max_buffer=2) entered = threading.Event() release = threading.Event() + drained = threading.Event() received = [] def slow(record): From 5bcb5ba2a9f823b7fb83c19b5f1fb994f41fedfa Mon Sep 17 00:00:00 2001 From: Prateep07 Date: Tue, 27 Oct 2026 19:47:09 +0530 Subject: [PATCH 030/146] feat: add per-session tool visibility --- README.md | 9 ++ nitrostack/core/app.py | 83 +++++++++++++-- nitrostack/core/context.py | 20 ++++ nitrostack/core/decorators.py | 3 + nitrostack/core/visibility.py | 111 +++++++++++++++++++ tests/test_tool_visibility.py | 194 ++++++++++++++++++++++++++++++++++ 6 files changed, 414 insertions(+), 6 deletions(-) create mode 100644 nitrostack/core/visibility.py create mode 100644 tests/test_tool_visibility.py diff --git a/README.md b/README.md index 01dcd2a..e4112c2 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,15 @@ server = ServerConfig(name="my-server", transport_type="http", max_sessions=100, `ServerConfig.protocol_era` is used only when `MCP_STATELESS` and `NITRO_MCP_PROTOCOL_VERSION` are both unset. Unknown tokens become `auto`, same as an unknown env value. +### Per-session tool visibility + +Tools can declare `visibility="hidden"` and `default_visible=False`, then handlers can +call `context.enable_tools(["admin_tool"])` or `context.disable_tools([...])`. Overrides +are scoped by transport session ID and verified token subject, with a bounded TTL/LRU +store. Dynamic visibility requires a sessionful transport. The default `auto` era is +sessionless, so changes warn and do nothing there; the SDK does not fall back to +subject-only state because it would share overrides across that subject's sessions. + --- ## Developing & Testing diff --git a/nitrostack/core/app.py b/nitrostack/core/app.py index 53777ae..1ea6184 100644 --- a/nitrostack/core/app.py +++ b/nitrostack/core/app.py @@ -35,6 +35,7 @@ ) from nitrostack.core.context import ExecutionContext, TaskContext +from nitrostack.core.visibility import VisibilityTransform from nitrostack.core.decorators import ToolConfig, ResourceConfig, PromptConfig, widget_resource_uri from nitrostack.core.app_mode import get_app_mode, get_widget_mime_type, is_mcp_app_mode, is_openai_mode from nitrostack.core.di import DIContainer @@ -609,6 +610,7 @@ def __init__(self, app_class: Type): self._initial_tools: List[Tuple[Any, Callable, ToolConfig]] = [] self.task_manager = TaskManager() self._in_flight = InFlightRegistry() + self.visibility_transform = VisibilityTransform() # Pipeline first: handlers consult it lazily when requests arrive. self._transforms = TransformPipeline( @@ -906,9 +908,11 @@ async def _list_tools( _ctx: ServerRequestContext, _params: Optional[PaginatedRequestParams], ): + session_key = self._visibility_session_key(_ctx) tools = [ self._build_tool_definition(entry) for entry in self._tools.values() + if self.visibility_transform.is_visible(entry, session_key) ] if self._transforms.enabled: @@ -932,6 +936,8 @@ async def _list_tools( async def _call_tool(ctx: ServerRequestContext, params: CallToolRequestParams): token = request_ctx.set(ctx) try: + if not self._tool_visible(params.name, ctx): + return self._unknown_tool_result(params.name) result = await self._call_tool( params.name, params.arguments or {}, task=params.task ) @@ -1015,14 +1021,22 @@ async def _discover(ctx: ServerRequestContext, _params: Optional[RequestParams]) server.add_request_handler("prompts/get", GetPromptRequestParams, _get_prompt) async def handle_list_tools(req=None): - return ServerResult(await _list_tools(None, None)) + ctx = req if req is not None and hasattr(req, "session") else request_ctx.get(None) + return ServerResult(await _list_tools(ctx, None)) async def handle_call_tool(req=None): params = getattr(req, "params", None) if req is not None else None name = getattr(params, "name", "") if params is not None else "" arguments = (getattr(params, "arguments", None) or {}) if params is not None else {} task = getattr(params, "task", None) if params is not None else None - return ServerResult(await self._call_tool(name, arguments, task=task)) + ctx = req if req is not None and hasattr(req, "session") else request_ctx.get(None) + if not self._tool_visible(name, ctx): + return ServerResult(self._unknown_tool_result(name)) + token = request_ctx.set(ctx) + try: + return ServerResult(await self._call_tool(name, arguments, task=task)) + finally: + request_ctx.reset(token) async def handle_list_resources(req=None): return ServerResult(await _list_resources(None, None)) @@ -1216,6 +1230,62 @@ async def _invoke_for_transform(self, name: str, arguments: dict, tctx: Transfor # Re-enter the normal call path so guards and validation run for the real tool. return await self._call_tool(name, arguments, _tctx=tctx) + @staticmethod + def _visibility_session_key(request_context: Any) -> tuple[str, str] | None: + session = getattr(request_context, "session", None) + session_id = getattr(session, "id", None) or getattr(session, "session_id", None) + if session_id is None: + return None + auth = auth_context_from_request(request_context) + return VisibilityTransform.session_key( + str(session_id), auth.subject if auth is not None else None + ) + + def _tool_visible(self, name: str, request_context: Any) -> bool: + entry = self._tools.get(name) + if entry is None: + # Transform-defined synthetic tools are not in the app registry. + # Let the transform resolver decide whether such names exist. + return True + return self.visibility_transform.is_visible( + entry, self._visibility_session_key(request_context) + ) + + def _configure_visibility_context( + self, context: ExecutionContext, request_context: Any + ) -> None: + key = self._visibility_session_key(request_context) + context._tool_visibility_controller = self.visibility_transform + context._visibility_session_key = key + context._visibility_app = self + context._visibility_supported = key is not None + context._visibility_change_callback = self._publish_tools_changed + + @staticmethod + def _unknown_tool_result(name: str) -> types.CallToolResult: + return types.CallToolResult( + content=[types.TextContent(type="text", text=f"Tool '{name}' not found")], + isError=True, + ) + + def _publish_tools_changed(self, context: ExecutionContext) -> None: + session = getattr(request_ctx.get(None), "session", None) + sender = getattr(session, "send_notification", None) if session is not None else None + if sender is None: + logger.debug("Transport does not support tools/list_changed notification") + return + + async def send_notification() -> None: + try: + await sender(types.ToolListChangedNotification()) + except Exception: + logger.debug("Unable to send session tools/list_changed notification", exc_info=True) + + try: + asyncio.create_task(send_notification()) + except RuntimeError: + logger.debug("No running event loop for tools/list_changed notification") + def _to_call_tool_result( self, result: Any, @@ -1379,10 +1449,9 @@ def _widget_result_content(self, structured: Dict[str, Any], component: Optional async def _call_real_tool(self, name: str, arguments: Dict[str, Any], task: Any = None): entry = self._tools.get(name) if entry is None: - return types.CallToolResult( - content=[types.TextContent(type="text", text=f"Tool '{name}' not found")], - isError=True, - ) + return self._unknown_tool_result(name) + if not self._tool_visible(name, request_ctx.get(None)): + return self._unknown_tool_result(name) cfg = entry.config tool_arguments, input_responses, request_state = split_mrtr_from_arguments( @@ -1466,6 +1535,7 @@ async def background_execution(): trace=trace, ) _apply_request_envelope(task_ctx, rc) + self._configure_visibility_context(task_ctx, rc) task_ctx.task = TaskContext( task_id, self.task_manager, @@ -1520,6 +1590,7 @@ async def background_execution(): trace=trace, ) _apply_request_envelope(ctx, rc) + self._configure_visibility_context(ctx, rc) ticket = self._in_flight.register(correlation_id, jsonrpc_id=jsonrpc_id) try: result = await run_pipeline( diff --git a/nitrostack/core/context.py b/nitrostack/core/context.py index 42cf129..5d0040c 100644 --- a/nitrostack/core/context.py +++ b/nitrostack/core/context.py @@ -197,6 +197,10 @@ class ExecutionContext: rpc_meta: Optional["RequestMeta"] = None mcp_headers: Dict[str, str] = field(default_factory=dict) mcp_param_headers: Dict[str, str] = field(default_factory=dict) + _tool_visibility_controller: Any = field(default=None, repr=False, compare=False) + _visibility_session_key: Any = field(default=None, repr=False, compare=False) + _visibility_change_callback: Any = field(default=None, repr=False, compare=False) + _visibility_supported: bool = field(default=False, repr=False, compare=False) def __post_init__(self) -> None: if not self.correlation_id: @@ -208,3 +212,19 @@ def user(self) -> Optional[str]: if self.auth is None: return None return self.auth.subject + + def enable_tools(self, names: List[str]) -> None: + """Enable registered tools for this verified transport session.""" + self._change_tool_visibility(names, visible=True) + + def disable_tools(self, names: List[str]) -> None: + """Disable registered tools for this verified transport session.""" + self._change_tool_visibility(names, visible=False) + + def _change_tool_visibility(self, names: List[str], *, visible: bool) -> None: + if not self._visibility_supported or self._tool_visibility_controller is None: + self.logger.warn("Tool visibility changes require a sessionful transport session") + return + changed = self._tool_visibility_controller.change(self, names, visible=visible) + if changed and self._visibility_change_callback is not None: + self._visibility_change_callback(self) diff --git a/nitrostack/core/decorators.py b/nitrostack/core/decorators.py index 60f4323..ef5a700 100644 --- a/nitrostack/core/decorators.py +++ b/nitrostack/core/decorators.py @@ -49,6 +49,7 @@ class ToolConfig: annotations: ToolAnnotations = field(default_factory=ToolAnnotations) task_support: Literal["forbidden", "optional", "required"] = "forbidden" visibility: Literal["visible", "hidden"] = "visible" + default_visible: Optional[bool] = None examples: Optional[ToolExamples] = None invocation: Optional[ToolInvocation] = None metadata: Dict[str, Any] = field(default_factory=dict) @@ -98,6 +99,7 @@ def tool( annotations: Optional[ToolAnnotations] = None, task_support: Literal["forbidden", "optional", "required"] = "forbidden", visibility: Literal["visible", "hidden"] = "visible", + default_visible: Optional[bool] = None, examples: Optional[ToolExamples] = None, invocation: Optional[ToolInvocation] = None, metadata: Optional[Dict[str, Any]] = None, @@ -121,6 +123,7 @@ def decorator(func: Callable): annotations=annotations, task_support=task_support, visibility=visibility, + default_visible=(visibility == "visible") if default_visible is None else default_visible, examples=examples, invocation=invocation, metadata=metadata, diff --git a/nitrostack/core/visibility.py b/nitrostack/core/visibility.py new file mode 100644 index 0000000..529dfbe --- /dev/null +++ b/nitrostack/core/visibility.py @@ -0,0 +1,111 @@ +"""Per-session tool visibility with bounded TTL/LRU state.""" + +from __future__ import annotations + +import time +from collections import OrderedDict +from dataclasses import dataclass, field +from threading import RLock +from typing import Callable, Iterable + + +@dataclass +class _SessionVisibility: + expires_at: float + overrides: dict[str, bool] = field(default_factory=dict) + + +class SessionVisibilityStore: + """Thread-safe TTL/LRU storage for tool visibility overrides.""" + + def __init__( + self, + *, + ttl_seconds: float = 3600, + max_entries: int = 10_000, + clock: Callable[[], float] = time.monotonic, + ) -> None: + if ttl_seconds <= 0 or max_entries <= 0: + raise ValueError("ttl_seconds and max_entries must be positive") + self.ttl_seconds = ttl_seconds + self.max_entries = max_entries + self._clock = clock + self._entries: OrderedDict[tuple[str, str], _SessionVisibility] = OrderedDict() + self._lock = RLock() + + def _expire(self, now: float) -> None: + for key, entry in list(self._entries.items()): + if entry.expires_at <= now: + del self._entries[key] + + def _get(self, key: tuple[str, str], now: float) -> _SessionVisibility: + self._expire(now) + entry = self._entries.get(key) + if entry is None: + entry = _SessionVisibility(now + self.ttl_seconds) + self._entries[key] = entry + else: + self._entries.move_to_end(key) + entry.expires_at = now + self.ttl_seconds + while len(self._entries) > self.max_entries: + self._entries.popitem(last=False) + return entry + + def is_visible(self, key: tuple[str, str], name: str, default: bool) -> bool: + with self._lock: + return self._get(key, self._clock()).overrides.get(name, default) + + def update(self, key: tuple[str, str], names: Iterable[str], visible: bool) -> bool: + changed = False + with self._lock: + entry = self._get(key, self._clock()) + for name in names: + if entry.overrides.get(name) != visible: + entry.overrides[name] = visible + changed = True + return changed + + +class VisibilityTransform: + """Apply decorator defaults and per-session tool visibility overrides.""" + + def __init__(self, store: SessionVisibilityStore | None = None) -> None: + self.store = store or SessionVisibilityStore() + + @staticmethod + def session_key( + transport_session_id: str | None, + verified_subject: str | None, + ) -> tuple[str, str] | None: + if not transport_session_id: + return None + return transport_session_id, verified_subject or "" + + def is_visible(self, entry: object, key: tuple[str, str] | None) -> bool: + config = getattr(entry, "config") + default = config.default_visible + if default is None: + default = config.visibility == "visible" + if key is None: + return default + return self.store.is_visible(key, config.name, default) + + def update(self, key: tuple[str, str], names: Iterable[str], visible: bool) -> bool: + """Update known tool names for a specific visibility key.""" + return self.store.update(key, names, visible) + + def change(self, context: object, names: Iterable[str], *, visible: bool) -> bool: + key = getattr(context, "_visibility_session_key", None) + if key is None: + getattr(context, "logger").warn( + "Tool visibility changes require a sessionful transport session" + ) + return False + app = getattr(context, "_visibility_app") + valid: list[str] = [] + for name in names: + if name not in app._tools: + getattr(context, "logger").warn(f"Unknown tool name in visibility change: {name}") + continue + valid.append(name) + return self.store.update(key, valid, visible) if valid else False diff --git a/tests/test_tool_visibility.py b/tests/test_tool_visibility.py new file mode 100644 index 0000000..005986b --- /dev/null +++ b/tests/test_tool_visibility.py @@ -0,0 +1,194 @@ +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +from pydantic import BaseModel + +from nitrostack import ExecutionContext, injectable, module, tool +from nitrostack.core.app import McpApplication +from nitrostack.core.context import AuthContext +from nitrostack.core.visibility import SessionVisibilityStore, VisibilityTransform +from nitrostack.runtime.request_ctx import RequestContext, request_ctx + + +class EmptyInput(BaseModel): + pass + + +@injectable() +class VisibilityTools: + @tool("public_tool", "public", EmptyInput) + async def public(self, input: EmptyInput, context: ExecutionContext): + return "public" + + @tool("admin_tool", "admin", EmptyInput, visibility="hidden", default_visible=False) + async def admin(self, input: EmptyInput, context: ExecutionContext): + return "admin" + + @tool("unlock", "unlock", EmptyInput) + async def unlock(self, input: EmptyInput, context: ExecutionContext): + context.enable_tools(["admin_tool", "not_registered"]) + return "ok" + + @tool("lock", "lock", EmptyInput) + async def lock(self, input: EmptyInput, context: ExecutionContext): + context.disable_tools(["admin_tool"]) + return "ok" + + +@module(name="visibility", providers=[VisibilityTools]) +class VisibilityModule: + pass + + +def _app(): + return McpApplication(VisibilityModule) + + +def _request(session_id="session-a"): + return RequestContext(session=SimpleNamespace(id=session_id), request_id="1") + + +def test_session_store_lru_eviction(): + now = [0.0] + store = SessionVisibilityStore(ttl_seconds=10, max_entries=2, clock=lambda: now[0]) + store.update(("a", "u"), ["tool"], True) + store.update(("b", "u"), ["tool"], True) + assert store.is_visible(("a", "u"), "tool", False) + store.update(("c", "u"), ["tool"], True) + assert not store.is_visible(("b", "u"), "tool", False) + + +def test_session_store_ttl_expiry_uses_fake_clock(): + now = [0.0] + store = SessionVisibilityStore(ttl_seconds=10, max_entries=2, clock=lambda: now[0]) + store.update(("session", "subject"), ["tool"], True) + now[0] = 11 + assert not store.is_visible(("session", "subject"), "tool", False) + + +def test_session_key_requires_session_and_includes_verified_subject(): + assert VisibilityTransform.session_key(None, "user-a") is None + assert VisibilityTransform.session_key("client-session", "user-a") != ( + VisibilityTransform.session_key("client-session", "user-b") + ) + + +def test_tools_list_and_call_enforce_visibility_and_isolate_sessions(): + async def run(): + app = _app() + list_handler = app.mcp_server.request_handlers[ + __import__("mcp.types", fromlist=["ListToolsRequest"]).ListToolsRequest + ] + request = _request() + token = request_ctx.set(request) + try: + listed = await list_handler(SimpleNamespace(params=None)) + assert "admin_tool" not in [item.name for item in listed.root.tools] + denied = await app._call_tool("admin_tool", {}) + assert denied.is_error + + enabled = await app._call_tool("unlock", {}) + assert not enabled.is_error + listed = await list_handler(SimpleNamespace(params=None)) + assert "admin_tool" in [item.name for item in listed.root.tools] + + entry = app._tools["admin_tool"] + other_session = app._visibility_session_key(_request("session-b")) + assert not app.visibility_transform.is_visible(entry, other_session) + other_subject = ("session-a", "verified-user-b") + assert not app.visibility_transform.is_visible(entry, other_subject) + + disabled = await app._call_tool("lock", {}) + assert not disabled.is_error + listed = await list_handler(SimpleNamespace(params=None)) + assert "admin_tool" not in [item.name for item in listed.root.tools] + finally: + request_ctx.reset(token) + + asyncio.run(run()) + + +def test_sessionless_mutation_is_noop_but_static_default_applies(): + app = _app() + context = ExecutionContext(request_id="r") + app._configure_visibility_context(context, None) + context.enable_tools(["admin_tool"]) + assert not app.visibility_transform.is_visible(app._tools["admin_tool"], None) + assert app.visibility_transform.is_visible(app._tools["public_tool"], None) + + +def test_http_session_id_is_transport_owned_and_keyed_with_verified_subject(monkeypatch): + """An arbitrary client session header cannot choose another session's state.""" + from starlette.testclient import TestClient + + from nitrostack import DIContainer + from nitrostack.auth.jwt import JWTModule, JWTService + from nitrostack.core.app import ServerConfig + from nitrostack.transports.http import build_http_app + + async def build(): + from nitrostack.core.app import McpApplicationFactory, mcp_app + + @mcp_app(module=VisibilityModule, server=ServerConfig(name="visibility-http", protocol_era="legacy")) + class HttpVisibilityApp: + pass + + return await McpApplicationFactory.create(HttpVisibilityApp) + + monkeypatch.setenv("JWT_SECRET", "visibility-test-secret") + DIContainer.reset() + JWTModule.for_root(secret_env_var="JWT_SECRET") + app = asyncio.run(build()) + http_app = build_http_app( + app, protocol_era="legacy", wire_mode="sessionful", enable_cors=True + ) + token = DIContainer.get_instance().resolve(JWTService).create_token({"sub": "owner"}) + auth_headers = { + "Authorization": f"Bearer {token}", + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + } + init_body = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "visibility-test", "version": "1"}, + }, + } + with TestClient(http_app) as client: + session_a = client.post("/mcp", headers=auth_headers, json=init_body) + session_b = client.post("/mcp", headers=auth_headers, json=init_body) + assert session_a.status_code == session_b.status_code == 200 + id_a = session_a.headers["mcp-session-id"] + id_b = session_b.headers["mcp-session-id"] + assert id_a != id_b + + # A client-supplied random ID is rejected; it cannot select stored state. + arbitrary = client.post( + "/mcp", + headers={**auth_headers, "mcp-session-id": "client-chosen"}, + json={"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}, + ) + assert arbitrary.status_code == 404 + + # Verified subject is included in the server-owned session key. + key_a = app._visibility_session_key( + SimpleNamespace(session=SimpleNamespace(id=id_a), request=SimpleNamespace(headers=auth_headers)) + ) + key_b = app._visibility_session_key( + SimpleNamespace(session=SimpleNamespace(id=id_b), request=SimpleNamespace(headers=auth_headers)) + ) + assert key_a == (id_a, "owner") + assert key_b == (id_b, "owner") + assert key_a != key_b + + # A state change in one live session does not affect the other. + app.visibility_transform.update(key_a, ["admin_tool"], True) + assert app.visibility_transform.is_visible(app._tools["admin_tool"], key_a) + assert not app.visibility_transform.is_visible(app._tools["admin_tool"], key_b) + DIContainer.reset() From 113b8dc09ab8c298b97ffc0413e30bb258b82f48 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Tue, 27 Oct 2026 23:02:00 +0530 Subject: [PATCH 031/146] feat(transforms): add search tokenizer and pure-Python BM25 engine (#64) --- nitrostack/transforms/search/bm25_engine.py | 71 +++++++++++++++++++++ nitrostack/transforms/search/tokenizer.py | 30 +++++++++ 2 files changed, 101 insertions(+) create mode 100644 nitrostack/transforms/search/bm25_engine.py create mode 100644 nitrostack/transforms/search/tokenizer.py diff --git a/nitrostack/transforms/search/bm25_engine.py b/nitrostack/transforms/search/bm25_engine.py new file mode 100644 index 0000000..8c61a4a --- /dev/null +++ b/nitrostack/transforms/search/bm25_engine.py @@ -0,0 +1,71 @@ +"""Pure-Python Okapi BM25 with weighted fields. No dependencies.""" +from __future__ import annotations + +import math +from collections import Counter +from typing import Dict, Iterable, List, Sequence, Tuple + +# One document: (doc_id, [(field_weight, tokens), ...]) +IndexDocument = Tuple[str, Sequence[Tuple[float, Sequence[str]]]] + + +class Bm25Engine: + def __init__(self, k1: float = 1.5, b: float = 0.75) -> None: + if k1 < 0: + raise ValueError("k1 must be >= 0.") + if not 0.0 <= b <= 1.0: + raise ValueError("b must be between 0 and 1.") + self.k1 = k1 + self.b = b + self._ids: List[str] = [] + self._lengths: List[float] = [] + self._postings: Dict[str, Dict[int, float]] = {} + self._avg_len = 0.0 + + @property + def size(self) -> int: + return len(self._ids) + + def build(self, documents: Iterable[IndexDocument]) -> None: + ids: List[str] = [] + lengths: List[float] = [] + postings: Dict[str, Dict[int, float]] = {} + for doc_index, (doc_id, fields) in enumerate(documents): + tf: Counter = Counter() + length = 0.0 + for weight, tokens in fields: + for token in tokens: + tf[token] += weight + length += weight + ids.append(doc_id) + lengths.append(length) + for term, freq in tf.items(): + postings.setdefault(term, {})[doc_index] = freq + self._ids = ids + self._lengths = lengths + self._postings = postings + self._avg_len = (sum(lengths) / len(lengths)) if lengths else 0.0 + + def idf(self, term: str) -> float: + n = len(self._postings.get(term, ())) + total = len(self._ids) + # The "1 +" keeps IDF positive even for terms that appear in most documents. + return math.log(1.0 + (total - n + 0.5) / (n + 0.5)) + + def search(self, query_tokens: Sequence[str]) -> List[Tuple[str, float]]: + """Return (doc_id, score) for documents with score > 0, best first, ties by id.""" + scores: Dict[int, float] = {} + for term in set(query_tokens): # a repeated query word counts once + docs = self._postings.get(term) + if not docs: + continue + idf = self.idf(term) + for doc_index, freq in docs.items(): + norm = 1.0 + if self._avg_len > 0: + norm = 1.0 - self.b + self.b * (self._lengths[doc_index] / self._avg_len) + denom = freq + self.k1 * norm + scores[doc_index] = scores.get(doc_index, 0.0) + idf * (freq * (self.k1 + 1.0)) / denom + ranked = [(self._ids[i], s) for i, s in scores.items() if s > 0] + ranked.sort(key=lambda pair: (-pair[1], pair[0])) + return ranked \ No newline at end of file diff --git a/nitrostack/transforms/search/tokenizer.py b/nitrostack/transforms/search/tokenizer.py new file mode 100644 index 0000000..c97d1c4 --- /dev/null +++ b/nitrostack/transforms/search/tokenizer.py @@ -0,0 +1,30 @@ +"""Tokenizer for tool search: lowercase, split on punctuation, snake_case and camelCase.""" +from __future__ import annotations + +import re +import unicodedata +from typing import List + +# Words that carry no search meaning. Removed from documents and queries alike. +STOP_WORDS = frozenset({ + "a", "an", "the", "of", "to", "for", "and", "or", "in", "on", "by", + "with", "is", "it", "this", "that", +}) + +# getRnaById -> get Rna By Id ; HTTPServer -> HTTP Server ; v2Api -> v2 Api +_CAMEL_LOWER_UPPER = re.compile(r"(?<=[a-z0-9])(?=[A-Z])") +_CAMEL_ACRONYM = re.compile(r"(?<=[A-Z])(?=[A-Z][a-z])") +# Letters and digits in any script; underscore is a separator, not a word character. +_WORD = re.compile(r"[^\W_]+", re.UNICODE) + + +def tokenize(text: str, *, drop_stop_words: bool = True) -> List[str]: + if not text: + return [] + text = unicodedata.normalize("NFC", text) + text = _CAMEL_LOWER_UPPER.sub(" ", text) + text = _CAMEL_ACRONYM.sub(" ", text) + tokens = [t.lower() for t in _WORD.findall(text)] + if drop_stop_words: + tokens = [t for t in tokens if t not in STOP_WORDS] + return tokens \ No newline at end of file From 28c9cd5da58d4fd47c2db763e2316d2ab47d3aa2 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Tue, 27 Oct 2026 23:02:17 +0530 Subject: [PATCH 032/146] feat(transforms): add Bm25SearchTransform with lazy fingerprinted index (#64) --- nitrostack/transforms/search/__init__.py | 4 ++ nitrostack/transforms/search/bm25.py | 73 ++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 nitrostack/transforms/search/bm25.py diff --git a/nitrostack/transforms/search/__init__.py b/nitrostack/transforms/search/__init__.py index 0779c25..1cf6512 100644 --- a/nitrostack/transforms/search/__init__.py +++ b/nitrostack/transforms/search/__init__.py @@ -4,9 +4,13 @@ CallToolInput, RankOutcome, SearchToolsInput, ) from nitrostack.transforms.search.regex import RegexSearchTransform +from nitrostack.transforms.search.bm25 import Bm25SearchTransform +from nitrostack.transforms.search.bm25_engine import Bm25Engine +from nitrostack.transforms.search.tokenizer import tokenize __all__ = [ "BaseSearchTransform", "RegexSearchTransform", "RankOutcome", "SearchToolsInput", "CallToolInput", "is_browse_query", "MAX_SEARCH_RESULTS", "DEFAULT_SEARCH_LIMIT", "BROWSE_MAX_RESULTS", + "Bm25SearchTransform", "Bm25Engine", "tokenize", ] \ No newline at end of file diff --git a/nitrostack/transforms/search/bm25.py b/nitrostack/transforms/search/bm25.py new file mode 100644 index 0000000..1a747d9 --- /dev/null +++ b/nitrostack/transforms/search/bm25.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import hashlib +from typing import Any, Optional, Sequence + +from nitrostack.transforms.search.base import BaseSearchTransform +from nitrostack.transforms.search.bm25_engine import Bm25Engine +from nitrostack.transforms.search.models import RankOutcome +from nitrostack.transforms.search.serializer import FIELD_WEIGHTS, tool_fields +from nitrostack.transforms.search.tokenizer import tokenize + + +def catalog_fingerprint(tools: Sequence[Any]) -> str: + """Order-independent hash of everything the index is built from.""" + digest = hashlib.sha256() + for fields in sorted(tool_fields(t) for t in tools): + for part in fields: + digest.update(part.encode("utf-8")) + digest.update(b"\x00") + digest.update(b"\x01") + return digest.hexdigest() + + +class Bm25SearchTransform(BaseSearchTransform): + """Ranks tools by BM25 over name, title, description and parameter text. + + Field weights (name > title > description > parameters) come from FIELD_WEIGHTS. + The index is built lazily and rebuilt only when the catalog fingerprint changes. + """ + + name = "bm25_search" + + def __init__(self, *, k1: float = 1.5, b: float = 0.75, **kwargs: Any) -> None: + super().__init__(**kwargs) + self._k1 = k1 + self._b = b + Bm25Engine(k1=k1, b=b) # validate parameters now, not on the first search + self._engine: Optional[Bm25Engine] = None + self._fingerprint: Optional[str] = None + self.build_count = 0 + + def _ensure_index(self, tools: Sequence[Any]) -> Bm25Engine: + fingerprint = catalog_fingerprint(tools) + if self._engine is None or fingerprint != self._fingerprint: + # Build a complete new engine, then swap. There is no await in between, + # so no search can observe a half-built index. + engine = Bm25Engine(k1=self._k1, b=self._b) + engine.build( + ( + tool.name, + [ + (weight, tokenize(text)) + for weight, text in zip(FIELD_WEIGHTS, tool_fields(tool)) + ], + ) + for tool in tools + ) + self._engine = engine + self._fingerprint = fingerprint + self.build_count += 1 + return self._engine + + async def rank(self, query: str, tools: Sequence[Any]) -> RankOutcome: + tokens = tokenize(query) + if not tokens: + return RankOutcome( + ranked=[], + note="The query has no searchable words. Try a specific term, or search with an empty query to browse.", + ) + engine = self._ensure_index(tools) + by_name = {tool.name: tool for tool in tools} + ranked = [(by_name[name], score) for name, score in engine.search(tokens) if name in by_name] + return RankOutcome(ranked=ranked) \ No newline at end of file From e5676f85fd1d8ec5a3a97d8cc06bc96feeb193fc Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Tue, 27 Oct 2026 23:03:33 +0530 Subject: [PATCH 033/146] test(transforms): BM25 scoring, golden ranking, index rebuild count (#64) --- tests/test_transforms_bm25.py | 209 ++++++++++++++++++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 tests/test_transforms_bm25.py diff --git a/tests/test_transforms_bm25.py b/tests/test_transforms_bm25.py new file mode 100644 index 0000000..3cb2d21 --- /dev/null +++ b/tests/test_transforms_bm25.py @@ -0,0 +1,209 @@ +import asyncio +import math + +import mcp.types as types +import pytest + +from nitrostack.transforms import TransformContext +from nitrostack.transforms.search import ( + Bm25Engine, Bm25SearchTransform, SearchToolsInput, tokenize, +) + + +def run(coro): + return asyncio.run(coro) + + +def make_tool(name, description="", props=None): + return types.Tool( + name=name, + description=description, + inputSchema={"type": "object", "properties": props or {}}, + ) + + +CATALOG = [ + make_tool("get_user", "Look up a user profile by id", {"user_id": {"type": "string"}}), + make_tool("get_order", "Fetch an order and its line items", {"order_id": {"type": "string"}}), + make_tool("send_email", "Send an email message to a recipient", {"to": {"type": "string"}}), + make_tool("search_genes", "Look up a gene by symbol and return annotations", {"symbol": {"type": "string"}}), + make_tool("get_rna_by_id", "Look up an RNA record by identifier", {"urs_id": {"type": "string"}}), + make_tool("list_invoices", "List invoices for a customer", {}), + make_tool("create_invoice", "Create an invoice for a customer order", {}), + make_tool("delete_user", "Delete a user account", {}), +] + + +class FakeRegistry: + def __init__(self, tools): + self.tools = tools + + def list_tools(self): + return list(self.tools) + + +def names(outcome): + return [tool.name for tool, _score in outcome.ranked] + + +# ---- tokenizer ------------------------------------------------------------- + +@pytest.mark.parametrize("text,expected", [ + ("getRnaById", ["get", "rna", "id"]), # "by" is a stop word + ("get_user_profile", ["get", "user", "profile"]), + ("HTTPServer", ["http", "server"]), + ("sha256Hash", ["sha256", "hash"]), # digits stay attached + ("find---genes!!", ["find", "genes"]), # repeated separators + ("Ünïcode Straße", ["ünïcode", "straße"]), + ("", []), + ("the of and", []), # stop words only +]) +def test_tokenizer(text, expected): + assert tokenize(text) == expected + + +def test_tokenizer_can_keep_stop_words(): + assert tokenize("the gene", drop_stop_words=False) == ["the", "gene"] + + +# ---- engine ---------------------------------------------------------------- + +def test_bm25_score_matches_hand_computation(): + engine = Bm25Engine(k1=1.5, b=0.75) + engine.build([("A", [(1.0, ["apple", "banana"])]), ("B", [(1.0, ["banana"])])]) + # N=2, n=1: idf = ln(1 + 1.5/1.5) = ln 2. avgdl = 1.5. A: tf=1, dl=2. + # denom = 1 + 1.5 * (0.25 + 0.75 * 2/1.5) = 2.875 ; num = 2.5 + expected = math.log(2) * 2.5 / 2.875 + result = engine.search(["apple"]) + assert [doc for doc, _ in result] == ["A"] + assert result[0][1] == pytest.approx(expected) + + +def test_idf_is_never_negative_for_common_terms(): + engine = Bm25Engine() + engine.build([(f"d{i}", [(1.0, ["common"])]) for i in range(5)]) + assert engine.idf("common") > 0 + + +def test_equal_scores_sort_by_id(): + engine = Bm25Engine() + engine.build([("b", [(1.0, ["x"])]), ("a", [(1.0, ["x"])])]) + assert [doc for doc, _ in engine.search(["x"])] == ["a", "b"] + + +def test_repeated_query_terms_count_once(): + engine = Bm25Engine() + engine.build([("a", [(1.0, ["x", "y"])])]) + assert engine.search(["x", "x", "x"]) == engine.search(["x"]) + + +@pytest.mark.parametrize("kwargs", [{"k1": -1}, {"b": 1.5}, {"b": -0.1}]) +def test_invalid_parameters_rejected(kwargs): + with pytest.raises(ValueError): + Bm25Engine(**kwargs) + + +# ---- ranking (golden) ------------------------------------------------------ +# These expectations are reasoned, not generated. Run once, and if one fails, +# check the reasoning before changing the expected value. + +def test_golden_single_match_queries(): + t = Bm25SearchTransform() + assert names(run(t.rank("email", CATALOG))) == ["send_email"] + assert names(run(t.rank("gene", CATALOG))) == ["search_genes"] # via description + assert names(run(t.rank("invoice", CATALOG))) == ["create_invoice"] + assert names(run(t.rank("invoices", CATALOG))) == ["list_invoices"] # no stemming + + +def test_golden_name_match_outranks_description_match(): + result = names(run(Bm25SearchTransform().rank("order", CATALOG))) + assert result[0] == "get_order" + assert "create_invoice" in result + + +def test_golden_user_query_returns_both_user_tools(): + result = names(run(Bm25SearchTransform().rank("user", CATALOG))) + assert set(result[:2]) == {"get_user", "delete_user"} + + +def test_ranking_is_deterministic_across_instances_and_catalog_order(): + first = names(run(Bm25SearchTransform().rank("look up", CATALOG))) + second = names(run(Bm25SearchTransform().rank("look up", list(reversed(CATALOG))))) + assert first == second + + +def test_no_match_returns_empty_list_not_error(): + outcome = run(Bm25SearchTransform().rank("zzzzzz", CATALOG)) + assert outcome.ranked == [] + + +def test_stop_word_only_query_explains_itself(): + outcome = run(Bm25SearchTransform().rank("of the", CATALOG)) + assert outcome.ranked == [] + assert "no searchable words" in outcome.note + + +# ---- index lifecycle ------------------------------------------------------- + +def test_index_is_not_rebuilt_on_every_search(): + t = Bm25SearchTransform() + assert t.build_count == 0 # lazy + for q in ("email", "gene", "order", "user"): + run(t.rank(q, CATALOG)) + assert t.build_count == 1 + + +def test_catalog_order_does_not_trigger_rebuild(): + t = Bm25SearchTransform() + run(t.rank("email", CATALOG)) + run(t.rank("email", list(reversed(CATALOG)))) + assert t.build_count == 1 + + +def test_adding_removing_or_editing_a_tool_rebuilds_once(): + t = Bm25SearchTransform() + run(t.rank("email", CATALOG)) + + added = CATALOG + [make_tool("send_sms", "Send a text message")] + assert "send_sms" in names(run(t.rank("sms", added))) + assert t.build_count == 2 + + run(t.rank("sms", added)) + assert t.build_count == 2 + + edited = [make_tool(x.name, "Totally new text") if x.name == "get_user" else x for x in added] + run(t.rank("totally", edited)) + assert t.build_count == 3 + + run(t.rank("email", [x for x in edited if x.name != "send_email"])) + assert t.build_count == 4 + + +# ---- through the search_tools handler -------------------------------------- + +async def _search(transform, **kw): + ctx = TransformContext() + + async def none(_name): + return None + + tool = await transform.resolve_tool(transform.search_tool_name, none, ctx) + return await tool.handler(SearchToolsInput(**kw), ctx) + + +def test_search_tools_handler_returns_ranked_results_and_clamps_limit(): + t = Bm25SearchTransform() + t.on_register(FakeRegistry(CATALOG)) + out = run(_search(t, query="email")) + assert [r["name"] for r in out["results"]] == ["send_email"] + big = run(_search(t, query="look", limit=500)) + assert len(big["results"]) <= 20 + assert "reduced" in big["note"] + + +def test_search_tools_handler_no_match_is_not_an_error(): + t = Bm25SearchTransform() + t.on_register(FakeRegistry(CATALOG)) + out = run(_search(t, query="zzzzzz")) + assert out["results"] == [] + assert "No tools matched" in out["note"] \ No newline at end of file From fe4e8862d6c25e91161a7e432e6a954dd9158f2a Mon Sep 17 00:00:00 2001 From: Aadarsh Mahesh K Date: Wed, 28 Oct 2026 10:45:00 +0530 Subject: [PATCH 034/146] feat(transforms): implement code-mode transform and quickjs worker pool --- nitrostack/transforms/__init__.py | 2 + nitrostack/transforms/code_mode/__init__.py | 35 ++ .../transforms/code_mode/destructive_guard.py | 46 +++ .../transforms/code_mode/guest_evaluator.py | 190 +++++++++ .../transforms/code_mode/legible_error.py | 43 ++ .../transforms/code_mode/sandbox_interface.py | 22 + .../transforms/code_mode/synthetic_tools.py | 147 +++++++ nitrostack/transforms/code_mode/transform.py | 141 +++++++ nitrostack/transforms/code_mode/types.py | 69 ++++ .../transforms/code_mode/worker_pool.py | 240 +++++++++++ pyproject.toml | 4 + tests/test_transforms_code_mode.py | 385 ++++++++++++++++++ uv.lock | 38 +- 13 files changed, 1355 insertions(+), 7 deletions(-) create mode 100644 nitrostack/transforms/code_mode/__init__.py create mode 100644 nitrostack/transforms/code_mode/destructive_guard.py create mode 100644 nitrostack/transforms/code_mode/guest_evaluator.py create mode 100644 nitrostack/transforms/code_mode/legible_error.py create mode 100644 nitrostack/transforms/code_mode/sandbox_interface.py create mode 100644 nitrostack/transforms/code_mode/synthetic_tools.py create mode 100644 nitrostack/transforms/code_mode/transform.py create mode 100644 nitrostack/transforms/code_mode/types.py create mode 100644 nitrostack/transforms/code_mode/worker_pool.py create mode 100644 tests/test_transforms_code_mode.py diff --git a/nitrostack/transforms/__init__.py b/nitrostack/transforms/__init__.py index a97d8c4..54e764d 100644 --- a/nitrostack/transforms/__init__.py +++ b/nitrostack/transforms/__init__.py @@ -13,9 +13,11 @@ ) from nitrostack.transforms.validation import ToolArgumentError, validate_tool_arguments from nitrostack.transforms.synthetic import SyntheticTool +from nitrostack.transforms.code_mode import CodeModeTransform __all__ = [ "CatalogTransform", "McpTransform", "McpTransformBase", "TransformContext", "TransformError", "TransformPipeline", "TransformRegistry", "ToolArgumentError", "validate_tool_arguments", "active_bypass", "bypassing", "SyntheticTool", + "CodeModeTransform", ] \ No newline at end of file diff --git a/nitrostack/transforms/code_mode/__init__.py b/nitrostack/transforms/code_mode/__init__.py new file mode 100644 index 0000000..6d45e45 --- /dev/null +++ b/nitrostack/transforms/code_mode/__init__.py @@ -0,0 +1,35 @@ +"""Code Mode transform for NitroStack.""" +from __future__ import annotations + +from nitrostack.transforms.code_mode.destructive_guard import ( + DestructiveToolError, + assert_tool_allowed, + is_destructive_tool, +) +from nitrostack.transforms.code_mode.legible_error import format_legible_error +from nitrostack.transforms.code_mode.sandbox_interface import SandboxProtocol, ToolsApi +from nitrostack.transforms.code_mode.transform import CodeModeTransform +from nitrostack.transforms.code_mode.types import ( + CodeModeLimits, + ExecuteScriptInput, + GetSchemaInput, + SandboxExecutionResult, + SearchToolsInput, +) +from nitrostack.transforms.code_mode.worker_pool import WorkerPool + +__all__ = [ + "CodeModeTransform", + "CodeModeLimits", + "SandboxExecutionResult", + "SandboxProtocol", + "ToolsApi", + "WorkerPool", + "is_destructive_tool", + "assert_tool_allowed", + "DestructiveToolError", + "format_legible_error", + "SearchToolsInput", + "GetSchemaInput", + "ExecuteScriptInput", +] diff --git a/nitrostack/transforms/code_mode/destructive_guard.py b/nitrostack/transforms/code_mode/destructive_guard.py new file mode 100644 index 0000000..7db9d9e --- /dev/null +++ b/nitrostack/transforms/code_mode/destructive_guard.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import Any, Optional + + +class DestructiveToolError(Exception): + """Raised when a destructive tool is called while allowDestructive is false.""" + pass + + +def _get_annotation(annotations: Any, *keys: str) -> Optional[bool]: + if annotations is None: + return None + for k in keys: + if isinstance(annotations, dict): + if k in annotations: + return annotations[k] + elif hasattr(annotations, k): + return getattr(annotations, k) + return None + + +def is_destructive_tool(tool: Any) -> bool: + """A tool is destructive unless readOnlyHint is true or destructiveHint is explicitly false.""" + annotations = getattr(tool, "annotations", None) + if annotations is None and hasattr(tool, "config"): + annotations = getattr(tool.config, "annotations", None) + + read_only = _get_annotation(annotations, "readOnlyHint", "read_only_hint", "read_only") + if read_only is True: + return False + + destructive = _get_annotation(annotations, "destructiveHint", "destructive_hint") + if destructive is False: + return False + + return True + + +def assert_tool_allowed(tool: Any, allow_destructive: bool) -> None: + """Reject tool if destructive and allow_destructive is False.""" + if not allow_destructive and is_destructive_tool(tool): + name = getattr(tool, "name", str(tool)) + raise DestructiveToolError( + f"Tool '{name}' is destructive and cannot be executed in code-mode when allowDestructive is false." + ) diff --git a/nitrostack/transforms/code_mode/guest_evaluator.py b/nitrostack/transforms/code_mode/guest_evaluator.py new file mode 100644 index 0000000..8ef57db --- /dev/null +++ b/nitrostack/transforms/code_mode/guest_evaluator.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import json +import logging +import time +from typing import Any, Dict, List, Optional +from multiprocessing.connection import Connection + +from nitrostack.transforms.code_mode.legible_error import format_legible_error +from nitrostack.transforms.code_mode.types import CodeModeLimits, SandboxExecutionResult + +logger = logging.getLogger(__name__) + +JS_PRELUDE = """ +const console = { + log: (...args) => { __nitrostack_log('info', __formatArgs(args)); }, + info: (...args) => { __nitrostack_log('info', __formatArgs(args)); }, + warn: (...args) => { __nitrostack_log('warn', __formatArgs(args)); }, + error: (...args) => { __nitrostack_log('error', __formatArgs(args)); } +}; + +function __formatArgs(args) { + return args.map(a => { + if (typeof a === 'object' && a !== null) { + try { return JSON.stringify(a); } catch(e) { return String(a); } + } + return String(a); + }).join(' '); +} + +const tools = new Proxy({ + call(name, args) { + const payload = JSON.stringify(args || {}); + const resStr = __nitrostack_call_tool(String(name), payload); + const parsed = JSON.parse(resStr); + if (parsed && parsed.__nitrostack_error) { + const err = new Error(parsed.__nitrostack_error); + err.name = parsed.__nitrostack_error_type || 'Error'; + throw err; + } + return parsed.__nitrostack_value; + } +}, { + get(target, prop) { + if (prop in target) return target[prop]; + return function(args) { + return target.call(prop, args); + }; + } +}); + +const call_tool = (name, args) => tools.call(name, args); +const call = (name, args) => tools.call(name, args); +""" + + +def get_quickjs_module(): + try: + import quickjs + return quickjs + except ImportError as exc: + raise RuntimeError( + "The 'quickjs' package is required for Code Mode. " + "Install it with: pip install 'nitrostack[code-mode]'" + ) from exc + + +def worker_process_main(conn: Connection) -> None: + """Main loop for isolated worker process.""" + quickjs = get_quickjs_module() + conn.send({"type": "ready"}) + + while True: + try: + if not conn.poll(None): + break + msg = conn.recv() + except (EOFError, KeyboardInterrupt): + break + + cmd = msg.get("cmd") + if cmd == "shutdown": + break + + if cmd == "run": + code = msg["code"] + limits_dict = msg["limits"] + memory_limit_mb = limits_dict.get("memory_limit_mb", 100) + + ctx = quickjs.Context() + memory_limit_bytes = int(memory_limit_mb * 1024 * 1024) + ctx.set_memory_limit(memory_limit_bytes) + + logs: List[str] = [] + tool_call_count = 0 + + def log_bridge(level: str, message: str) -> None: + logs.append(f"[{level}] {message}") + + def tool_call_bridge(name: str, args_json: str) -> str: + nonlocal tool_call_count + tool_call_count += 1 + try: + conn.send({ + "type": "tool_call", + "name": name, + "args_json": args_json, + "call_index": tool_call_count, + }) + response = conn.recv() + if response.get("status") == "error": + return json.dumps({ + "__nitrostack_error": response.get("error", "Tool execution error"), + "__nitrostack_error_type": response.get("error_type", "Error"), + }) + return json.dumps({ + "__nitrostack_value": response.get("value") + }) + except Exception as e: + return json.dumps({ + "__nitrostack_error": format_legible_error(e), + "__nitrostack_error_type": type(e).__name__, + }) + + ctx.add_callable("__nitrostack_log", log_bridge) + ctx.add_callable("__nitrostack_call_tool", tool_call_bridge) + + # Evaluate prelude + ctx.eval(JS_PRELUDE) + + start_time = time.perf_counter() + success = False + value = None + error = None + + try: + try: + raw_result = ctx.eval(code) + except quickjs.JSException as exc: + if "return not in a function" in str(exc): + wrapped = "(function() {\n" + code + "\n})()" + raw_result = ctx.eval(wrapped) + else: + raise + + if hasattr(raw_result, "json"): + try: + value = json.loads(raw_result.json()) + except Exception: + value = str(raw_result) + else: + value = raw_result + + success = True + except quickjs.JSException as exc: + err_str = str(exc) + if "out of memory" in err_str: + error = f"MemoryLimitExceededError: Script exceeded memory limit of {memory_limit_mb}MB." + else: + error = format_legible_error(exc) + except Exception as exc: + error = format_legible_error(exc) + finally: + duration_ms = (time.perf_counter() - start_time) * 1000.0 + memory_used_mb = 0.0 + try: + mem_info = ctx.memory() + if isinstance(mem_info, dict): + used_bytes = mem_info.get("memory_used_size", 0) + else: + used_bytes = getattr(mem_info, "memory_used_size", 0) + memory_used_mb = used_bytes / (1024 * 1024) + except Exception: + pass + + try: + ctx.gc() + except Exception: + pass + + conn.send({ + "type": "run_result", + "success": success, + "value": value, + "error": error, + "logs": logs, + "tool_call_count": tool_call_count, + "duration_ms": duration_ms, + "memory_used_mb": memory_used_mb, + }) diff --git a/nitrostack/transforms/code_mode/legible_error.py b/nitrostack/transforms/code_mode/legible_error.py new file mode 100644 index 0000000..903bbe5 --- /dev/null +++ b/nitrostack/transforms/code_mode/legible_error.py @@ -0,0 +1,43 @@ +"""Format legible error messages for models without leaking host paths or stack frames.""" +from __future__ import annotations + +import re + +_HOST_PATH_RE = re.compile( + r"(?:/[a-zA-Z0-9_\-\.]+)+|(?:[a-zA-Z]:\\[a-zA-Z0-9_\-\.\\]+)" +) + +# Match Python traceback line patterns +_PY_TRACEBACK_LINE_RE = re.compile( + r"^\s*File\s+\".*?\",\s+line\s+\d+.*$", + re.MULTILINE +) + + +def format_legible_error(exc: BaseException | str) -> str: + """Format an error message so it is readable (message and location) and leaks no host paths or stack frames.""" + raw = str(exc) + + # Clean up input markers + raw = raw.replace("", " - - -""" - -SAMPLE_PIZZA_PREVIEW_JSON = """{ - "shops": [ - { - "id": "tonys-pizza", - "name": "Tony's New York Pizza", - "address": "123 Main St, San Francisco, CA 94102", - "rating": 4.5, - "priceLevel": 2, - "openNow": true, - "image": "https://images.unsplash.com/photo-1513104890138-7c749659a591" - } - ], - "totalShops": 1 -}""" + + + + _GENERATE_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") @@ -1057,18 +183,6 @@ def ensure_python_widgets(project_dir: str) -> list: write_widget_preview(project_dir) return unique -MODULE_TEMPLATE = """from nitrostack import module - -@module( - name="{name}", - imports=[], - controllers=[], - providers=[], - exports=[] -) -class {camel_name}Module: - pass -""" def print_banner(): banner = """\033[34m╔══════════════════════════════════════════════════════════╗ diff --git a/nitrostack/cli/templates/legacy_app_module_template.txt b/nitrostack/cli/templates/legacy_app_module_template.txt new file mode 100644 index 0000000..5e018a5 --- /dev/null +++ b/nitrostack/cli/templates/legacy_app_module_template.txt @@ -0,0 +1,12 @@ +from nitrostack import module +from modules.calculator.calculator_module import CalculatorModule + +@module( + name="app", + imports=[CalculatorModule], + controllers=[], + providers=[], + exports=[] +) +class AppModule: + pass diff --git a/nitrostack/cli/templates/legacy_calc_module_template.txt b/nitrostack/cli/templates/legacy_calc_module_template.txt new file mode 100644 index 0000000..2996ee1 --- /dev/null +++ b/nitrostack/cli/templates/legacy_calc_module_template.txt @@ -0,0 +1,13 @@ +from nitrostack import module +from modules.calculator.calculator_tools import CalculatorController +from modules.calculator.calculator_service import CalculatorService + +@module( + name="calculator", + imports=[], + controllers=[CalculatorController], + providers=[CalculatorService], + exports=[CalculatorService] +) +class CalculatorModule: + pass diff --git a/nitrostack/cli/templates/legacy_calc_service_template.txt b/nitrostack/cli/templates/legacy_calc_service_template.txt new file mode 100644 index 0000000..f90382d --- /dev/null +++ b/nitrostack/cli/templates/legacy_calc_service_template.txt @@ -0,0 +1,6 @@ +from nitrostack import injectable + +@injectable(deps=[]) +class CalculatorService: + def add(self, a: float, b: float) -> float: + return a + b diff --git a/nitrostack/cli/templates/legacy_calc_tools_template.txt b/nitrostack/cli/templates/legacy_calc_tools_template.txt new file mode 100644 index 0000000..6a216db --- /dev/null +++ b/nitrostack/cli/templates/legacy_calc_tools_template.txt @@ -0,0 +1,21 @@ +from nitrostack import injectable, tool, ExecutionContext +from modules.calculator.calculator_service import CalculatorService +from pydantic import BaseModel + +class AddInput(BaseModel): + a: float + b: float + +@injectable(deps=[CalculatorService]) +class CalculatorController: + def __init__(self, service: CalculatorService): + self.service = service + + @tool( + name="add", + description="Add two numbers together", + input_schema=AddInput + ) + async def add(self, input: AddInput, context: ExecutionContext) -> float: + context.logger.info(f"Adding {input.a} and {input.b}") + return self.service.add(input.a, input.b) diff --git a/nitrostack/cli/templates/legacy_env_template.txt b/nitrostack/cli/templates/legacy_env_template.txt new file mode 100644 index 0000000..766252b --- /dev/null +++ b/nitrostack/cli/templates/legacy_env_template.txt @@ -0,0 +1,2 @@ +PORT=3000 +NODE_ENV=development diff --git a/nitrostack/cli/templates/legacy_flight_app_module_template.txt b/nitrostack/cli/templates/legacy_flight_app_module_template.txt new file mode 100644 index 0000000..f7e8bae --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_app_module_template.txt @@ -0,0 +1,31 @@ +from nitrostack import module, ConfigModule, OAuthModule +from modules.flights.flights_module import FlightsModule +from health.system_health import SystemHealthCheck +import os + +@module( + name="app", + imports=[ + ConfigModule.for_root( + env_file_path=".env", + defaults={"RESOURCE_URI": "https://mcplocal", "PORT": "3000"} + ), + # Configure OAuth resource protection + OAuthModule.for_root( + resource_uri=os.environ.get("RESOURCE_URI", "https://mcplocal"), + authorization_servers=[os.environ.get("AUTH_SERVER_URL", "https://dev-5dt0utuk315713tjm.us.auth0.com")], + scopes_supported=["read", "write", "admin"], + token_introspection_endpoint=os.environ.get("INTROSPECTION_ENDPOINT"), + token_introspection_client_id=os.environ.get("INTROSPECTION_CLIENT_ID"), + token_introspection_client_secret=os.environ.get("INTROSPECTION_CLIENT_SECRET"), + audience=os.environ.get("TOKEN_AUDIENCE"), + issuer=os.environ.get("TOKEN_ISSUER") + ), + FlightsModule + ], + controllers=[], + providers=[SystemHealthCheck], + exports=[] +) +class AppModule: + pass diff --git a/nitrostack/cli/templates/legacy_flight_booking_tools_template.txt b/nitrostack/cli/templates/legacy_flight_booking_tools_template.txt new file mode 100644 index 0000000..c6ccb02 --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_booking_tools_template.txt @@ -0,0 +1,92 @@ +from nitrostack import injectable, tool, use_guards, OAuthGuard, ExecutionContext +from services.duffel_service import DuffelService +from guards.oauth_guard import create_scope_guard +from pydantic import BaseModel, Field +import json + +class CreateOrderInput(BaseModel): + offerId: str = Field(description="The offer ID to book") + passengers: str = Field(description="JSON string containing array of passenger objects. Each passenger must have: title (mr/ms/mrs/miss/dr), givenName (first name), familyName (last name), gender (M/F), bornOn (YYYY-MM-DD), email, phoneNumber.") + +class OrderDetailsInput(BaseModel): + orderId: str = Field(description="The order ID") + +class SeatMapInput(BaseModel): + offerId: str = Field(description="The offer ID to get seats for") + +class CancelOrderInput(BaseModel): + orderId: str = Field(description="The order ID to cancel") + +@injectable(deps=[DuffelService]) +class BookingTools: + def __init__(self, service: DuffelService): + self.service = service + + @tool( + name="create_order", + title="Create Order", + description="Create a flight order with hold (no payment required). Collect passenger details first.", + input_schema=CreateOrderInput + ) + @use_guards(OAuthGuard, create_scope_guard(["write"])) + async def create_order(self, input: CreateOrderInput, context: ExecutionContext) -> dict: + context.logger.info(f"Creating flight order for offer {input.offerId}") + try: + passengers_array = json.loads(input.passengers) + except Exception: + raise ValueError("Invalid passengers JSON format") + + passengers = [] + for p in passengers_array: + passengers.append({ + "title": p.get("title", "mr"), + "given_name": p.get("givenName"), + "family_name": p.get("familyName"), + "gender": p.get("gender", "M"), + "born_on": p.get("bornOn"), + "email": p.get("email"), + "phone_number": p.get("phoneNumber") + }) + + order_params = { + "selectedOffers": [input.offerId], + "passengers": passengers + } + res = await self.service.create_order(order_params) + return res + + @tool( + name="get_order_details", + title="Get Order Details", + description="Get detailed information about an order.", + input_schema=OrderDetailsInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + async def get_order_details(self, input: OrderDetailsInput, context: ExecutionContext) -> dict: + context.logger.info(f"Fetching details for order {input.orderId}") + res = await self.service.get_order(input.orderId) + return res + + @tool( + name="get_seat_map", + title="Get Seat Map", + description="Get available seats for a flight offer to allow seat selection.", + input_schema=SeatMapInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + async def get_seat_map(self, input: SeatMapInput, context: ExecutionContext) -> dict: + context.logger.info(f"Fetching seat map for offer {input.offerId}") + res = await self.service.get_seats_for_offer(input.offerId) + return {"offerId": input.offerId, "cabins": res} + + @tool( + name="cancel_order", + title="Cancel Order", + description="Cancel a flight order and request refund if applicable.", + input_schema=CancelOrderInput + ) + @use_guards(OAuthGuard, create_scope_guard(["write"])) + async def cancel_order(self, input: CancelOrderInput, context: ExecutionContext) -> dict: + context.logger.info(f"Cancelling order {input.orderId}") + res = await self.service.cancel_order(input.orderId) + return res diff --git a/nitrostack/cli/templates/legacy_flight_duffel_service_template.txt b/nitrostack/cli/templates/legacy_flight_duffel_service_template.txt new file mode 100644 index 0000000..8eaa8b7 --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_duffel_service_template.txt @@ -0,0 +1,264 @@ +import os +import sys +import json +import urllib.request +import urllib.parse +from typing import List, Dict, Any, Optional +from nitrostack import injectable + +@injectable() +class DuffelService: + def __init__(self): + self.api_key = os.environ.get("DUFFEL_API_KEY") + self.is_mock = not self.api_key or self.api_key.startswith("your-") or len(self.api_key) < 5 + + def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + if self.is_mock: + raise ValueError("Duffel API key is not configured. Running in mock mode.") + + headers = { + "Authorization": f"Bearer {self.api_key}", + "Duffel-Version": "v2", + "Content-Type": "application/json" + } + url = f"https://api.duffel.com{path}" + req_data = json.dumps({"data": data}).encode("utf-8") if data else None + + req = urllib.request.Request(url, data=req_data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=10) as response: + res_payload = json.loads(response.read().decode("utf-8")) + return res_payload.get("data", {}) + except Exception as e: + sys.stderr.write(f"Duffel API Request failed: {e}\n") + sys.stderr.flush() + raise e + + async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]: + if self.is_mock: + return { + "id": "orq_mock123456", + "offers": [ + { + "id": "off_mock123456", + "total_amount": "450.00", + "total_currency": "USD", + "expires_at": "2026-12-31T12:00:00Z", + "slices": [ + { + "origin": {"iata_code": params["origin"], "name": "Origin Airport", "city_name": "Origin City"}, + "destination": {"iata_code": params["destination"], "name": "Dest Airport", "city_name": "Dest City"}, + "duration": "PT6H30M", + "segments": [ + { + "id": "seg_outbound", + "origin": {"iata_code": params["origin"]}, + "destination": {"iata_code": params["destination"]}, + "departing_at": f"{params['departureDate']}T08:00:00Z", + "arriving_at": f"{params['departureDate']}T14:30:00Z", + "marketing_carrier": {"name": "Mock Airlines"}, + "marketing_carrier_flight_number": "MK123", + "aircraft": {"name": "Boeing 787"} + } + ] + } + ] + } + ] + } + + slices = [ + { + "origin": params["origin"], + "destination": params["destination"], + "departure_date": params["departureDate"] + } + ] + if params.get("returnDate"): + slices.append({ + "origin": params["destination"], + "destination": params["origin"], + "departure_date": params["returnDate"] + }) + + duffel_params = { + "slices": slices, + "passengers": params.get("passengers", [{"type": "adult"}]), + "cabin_class": params.get("cabinClass", "economy"), + "return_offers": True + } + res = self._request("POST", "/air/offer_requests", duffel_params) + return { + "id": res.get("id"), + "offers": res.get("offers", []), + "passengers": res.get("passengers", []), + "slices": res.get("slices", []) + } + + async def get_offer(self, offer_id: str) -> Dict[str, Any]: + if self.is_mock: + return { + "id": offer_id, + "total_amount": "450.00", + "total_currency": "USD", + "expires_at": "2026-12-31T12:00:00Z", + "slices": [ + { + "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"}, + "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"}, + "duration": "PT6H30M", + "segments": [ + { + "id": "seg_mock", + "origin": {"iata_code": "JFK"}, + "destination": {"iata_code": "LAX"}, + "departing_at": "2026-07-15T08:00:00Z", + "arriving_at": "2026-07-15T14:30:00Z", + "marketing_carrier": {"name": "Mock Airlines"}, + "marketing_carrier_flight_number": "MK123", + "aircraft": {"name": "Boeing 787"} + } + ] + } + ] + } + return self._request("GET", f"/air/offers/{offer_id}") + + async def get_seats_for_offer(self, offer_id: str) -> List[Dict[str, Any]]: + if self.is_mock: + return [ + { + "cabin_class": "economy", + "rows": [ + { + "row_number": 10, + "sections": [ + { + "elements": [ + { + "type": "seat", + "id": "seat_10a", + "designator": "10A", + "available_services": [{"total_amount": "25.00", "total_currency": "USD"}], + "disclosures": ["window"] + }, + { + "type": "seat", + "id": "seat_10b", + "designator": "10B", + "available_services": [{"total_amount": "0.00", "total_currency": "USD"}], + "disclosures": ["middle"] + } + ] + } + ] + } + ] + } + ] + res = self._request("GET", f"/air/seat_maps?offer_id={offer_id}") + return res if isinstance(res, list) else [] + + async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]: + if self.is_mock: + return { + "id": "ord_mock123456", + "status": "held", + "total_amount": "450.00", + "total_currency": "USD", + "expires_at": "2026-12-31T12:00:00Z", + "booking_reference": "ABCXYZ", + "passengers": [ + { + "id": f"pax_{idx}", + "given_name": p["given_name"], + "family_name": p["family_name"], + "type": "adult" + } for idx, p in enumerate(params["passengers"]) + ], + "slices": [ + { + "origin": {"iata_code": "JFK"}, + "destination": {"iata_code": "LAX"}, + "duration": "PT6H30M", + "segments": [ + { + "departing_at": "2026-07-15T08:00:00Z", + "arriving_at": "2026-07-15T14:30:00Z" + } + ] + } + ] + } + + order_payload = { + "selected_offers": params["selectedOffers"], + "passengers": params["passengers"], + "type": "hold" + } + return self._request("POST", "/air/orders", order_payload) + + async def get_order(self, order_id: str) -> Dict[str, Any]: + if self.is_mock: + return { + "id": order_id, + "status": "held", + "total_amount": "450.00", + "total_currency": "USD", + "booking_reference": "ABCXYZ", + "created_at": "2026-06-25T12:00:00Z", + "expires_at": "2026-12-31T12:00:00Z", + "passengers": [ + { + "id": "pax_0", + "given_name": "John", + "family_name": "Doe", + "type": "adult", + "email": "john@example.com", + "phone_number": "+1234567890" + } + ], + "slices": [ + { + "id": "sli_mock", + "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"}, + "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"}, + "duration": "PT6H30M", + "segments": [ + { + "id": "seg_mock", + "origin": {"iata_code": "JFK"}, + "destination": {"iata_code": "LAX"}, + "departing_at": "2026-07-15T08:00:00Z", + "arriving_at": "2026-07-15T14:30:00Z", + "marketing_carrier": {"name": "Mock Airlines"}, + "marketing_carrier_flight_number": "MK123", + "aircraft": {"name": "Boeing 787"} + } + ] + } + ] + } + return self._request("GET", f"/air/orders/{order_id}") + + async def cancel_order(self, order_id: str) -> Dict[str, Any]: + if self.is_mock: + return { + "id": "ocr_mock123456", + "refund_amount": "450.00", + "refund_currency": "USD", + "confirmed_at": "2026-06-25T12:30:00Z" + } + cancel_payload = {"order_id": order_id} + return self._request("POST", "/air/order_cancellations", cancel_payload) + + async def get_airlines(self) -> List[Dict[str, Any]]: + if self.is_mock: + return [ + {"iata_code": "AA", "name": "American Airlines"}, + {"iata_code": "DL", "name": "Delta Air Lines"}, + {"iata_code": "UA", "name": "United Airlines"}, + {"iata_code": "BA", "name": "British Airways"} + ] + res = self._request("GET", "/air/airlines") + return res if isinstance(res, list) else [] diff --git a/nitrostack/cli/templates/legacy_flight_module_template.txt b/nitrostack/cli/templates/legacy_flight_module_template.txt new file mode 100644 index 0000000..a7b3d9f --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_module_template.txt @@ -0,0 +1,15 @@ +from nitrostack import module +from modules.flights.flights_tools import FlightTools +from modules.flights.booking_tools import BookingTools +from modules.flights.flights_prompts import FlightPrompts +from modules.flights.flights_resources import FlightResources +from services.duffel_service import DuffelService + +@module( + name="flights", + controllers=[FlightTools, BookingTools, FlightPrompts, FlightResources], + providers=[DuffelService], + exports=[DuffelService] +) +class FlightsModule: + pass diff --git a/nitrostack/cli/templates/legacy_flight_oauth_guard_template.txt b/nitrostack/cli/templates/legacy_flight_oauth_guard_template.txt new file mode 100644 index 0000000..03c3a07 --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_oauth_guard_template.txt @@ -0,0 +1,14 @@ +from nitrostack import ExecutionContext + +def create_scope_guard(required_scopes: list): + class ScopeGuard: + async def can_activate(self, context: ExecutionContext) -> bool: + user_scopes = getattr(context.auth, "scopes", []) + missing_scopes = [s for s in required_scopes if s not in user_scopes] + if missing_scopes: + raise ValueError( + f"Insufficient scope. Required: {', '.join(required_scopes)}. " + f"Missing: {', '.join(missing_scopes)}" + ) + return True + return ScopeGuard diff --git a/nitrostack/cli/templates/legacy_flight_prompts_template.txt b/nitrostack/cli/templates/legacy_flight_prompts_template.txt new file mode 100644 index 0000000..a6b797b --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_prompts_template.txt @@ -0,0 +1,22 @@ +from nitrostack import injectable, prompt, ExecutionContext +from services.duffel_service import DuffelService +from typing import List + +@injectable(deps=[DuffelService]) +class FlightPrompts: + def __init__(self, service: DuffelService): + self.service = service + + @prompt( + name="flight_search_assistant", + description="An AI assistant specialized in helping users search for flights and make booking decisions." + ) + async def flight_search_assistant(self, args: dict, context: ExecutionContext) -> str: + return "You are a professional flight booking assistant. Help the user search for flights using search_flights, search_airports, and assist in booking holds." + + @prompt( + name="flight_comparison", + description="Compare multiple flight offers and provide recommendations." + ) + async def flight_comparison(self, args: dict, context: ExecutionContext) -> str: + return "Compare the provided flight offer details, check layover times, durations, and pricing, and give the user a summary of best options." diff --git a/nitrostack/cli/templates/legacy_flight_resources_template.txt b/nitrostack/cli/templates/legacy_flight_resources_template.txt new file mode 100644 index 0000000..f542dd0 --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_resources_template.txt @@ -0,0 +1,30 @@ +from nitrostack import injectable, resource, ExecutionContext +from services.duffel_service import DuffelService + +@injectable(deps=[DuffelService]) +class FlightResources: + def __init__(self, service: DuffelService): + self.service = service + + @resource( + uri="flight://popular-routes", + name="Popular Flight Routes", + description="Information about popular routes and pricing", + mime_type="application/json" + ) + async def popular_routes(self, context: ExecutionContext) -> dict: + return { + "routes": [ + {"route": "JFK -> LAX", "price": "$200-400"}, + {"route": "LHR -> JFK", "price": "$400-800"} + ] + } + + @resource( + uri="flight://booking-guide", + name="Flight Booking Guide", + description="Guide on searching and booking flights", + mime_type="text/markdown" + ) + async def booking_guide(self, context: ExecutionContext) -> str: + return "# Flight Booking Guide\n\n1. Search flights.\n2. Collect passenger info.\n3. Create order hold." diff --git a/nitrostack/cli/templates/legacy_flight_system_health_template.txt b/nitrostack/cli/templates/legacy_flight_system_health_template.txt new file mode 100644 index 0000000..1e1a3bb --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_system_health_template.txt @@ -0,0 +1,11 @@ +import time +from nitrostack import health_check + +class SystemHealthCheck: + def __init__(self): + self.start_time = time.time() + + @health_check("system") + def check_system(self) -> bool: + uptime = time.time() - self.start_time + return uptime >= 0 diff --git a/nitrostack/cli/templates/legacy_flight_tools_template.txt b/nitrostack/cli/templates/legacy_flight_tools_template.txt new file mode 100644 index 0000000..fc5ed8a --- /dev/null +++ b/nitrostack/cli/templates/legacy_flight_tools_template.txt @@ -0,0 +1,74 @@ +from nitrostack import injectable, tool, use_guards, OAuthGuard, ExecutionContext +from services.duffel_service import DuffelService +from guards.oauth_guard import create_scope_guard +from pydantic import BaseModel, Field +from typing import Optional + +class SearchFlightsInput(BaseModel): + origin: str = Field(description="Origin airport IATA code (e.g., 'JFK', 'LHR')") + destination: str = Field(description="Destination airport IATA code (e.g., 'LAX', 'CDG')") + departureDate: str = Field(description="Departure date in YYYY-MM-DD format") + returnDate: Optional[str] = Field(default=None, description="Return date in YYYY-MM-DD format for round trip") + adults: int = Field(default=1, description="Number of adult passengers (18+)") + cabinClass: str = Field(default="economy", description="Preferred cabin class (economy, premium_economy, business, first)") + +class FlightDetailsInput(BaseModel): + offerId: str = Field(description="The flight offer ID from search results") + +class AirportSearchInput(BaseModel): + query: str = Field(description="The search query for airports (e.g., 'London', 'New York')") + +class GetAirlinesInput(BaseModel): + pass + +@injectable(deps=[DuffelService]) +class FlightTools: + def __init__(self, service: DuffelService): + self.service = service + + @tool( + name="search_flights", + title="Search Flights", + description="Search for flight offers based on origin, destination, dates, and preferences.", + input_schema=SearchFlightsInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + async def search_flights(self, input: SearchFlightsInput, context: ExecutionContext) -> dict: + context.logger.info(f"Searching flights from {input.origin} to {input.destination}") + res = await self.service.search_flights(input.model_dump()) + return res + + @tool( + name="get_flight_details", + title="Get Flight Details", + description="Get detailed information about a specific flight offer including baggage allowance, conditions.", + input_schema=FlightDetailsInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + async def get_flight_details(self, input: FlightDetailsInput, context: ExecutionContext) -> dict: + context.logger.info(f"Fetching flight details for offer {input.offerId}") + res = await self.service.get_offer(input.offerId) + return res + + @tool( + name="search_airports", + title="Search Airports", + description="Search for airports by query string.", + input_schema=AirportSearchInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + async def search_airports(self, input: AirportSearchInput, context: ExecutionContext) -> dict: + context.logger.info(f"Searching airports for query: {input.query}") + return {"airports": [{"iataCode": "JFK", "name": "John F. Kennedy Airport"}]} + + @tool( + name="get_airlines", + title="Get Airlines", + description="Get list of common airlines.", + input_schema=GetAirlinesInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + async def get_airlines(self, input: GetAirlinesInput, context: ExecutionContext) -> dict: + context.logger.info("Fetching common airlines") + res = await self.service.get_airlines() + return {"airlines": res} diff --git a/nitrostack/cli/templates/legacy_food_app_module_template.txt b/nitrostack/cli/templates/legacy_food_app_module_template.txt new file mode 100644 index 0000000..f0c130a --- /dev/null +++ b/nitrostack/cli/templates/legacy_food_app_module_template.txt @@ -0,0 +1,12 @@ +from nitrostack import module +from modules.food_delivery.food_delivery_module import FoodDeliveryModule + +@module( + name="app", + imports=[FoodDeliveryModule], + controllers=[], + providers=[], + exports=[] +) +class AppModule: + pass diff --git a/nitrostack/cli/templates/legacy_food_delivery_module_template.txt b/nitrostack/cli/templates/legacy_food_delivery_module_template.txt new file mode 100644 index 0000000..f8f1431 --- /dev/null +++ b/nitrostack/cli/templates/legacy_food_delivery_module_template.txt @@ -0,0 +1,13 @@ +from nitrostack import module +from modules.food_delivery.food_delivery_tools import FoodDeliveryController +from modules.food_delivery.food_delivery_service import FoodDeliveryService + +@module( + name="food_delivery", + imports=[], + controllers=[FoodDeliveryController], + providers=[FoodDeliveryService], + exports=[FoodDeliveryService] +) +class FoodDeliveryModule: + pass diff --git a/nitrostack/cli/templates/legacy_food_delivery_service_template.txt b/nitrostack/cli/templates/legacy_food_delivery_service_template.txt new file mode 100644 index 0000000..f2eddaf --- /dev/null +++ b/nitrostack/cli/templates/legacy_food_delivery_service_template.txt @@ -0,0 +1,41 @@ +from nitrostack import injectable + +@injectable(deps=[]) +class FoodDeliveryService: + def __init__(self): + # In-memory database of items and orders + self.menu = { + "pizza": {"price": 12.99, "prep_time": 15}, + "burger": {"price": 8.99, "prep_time": 10}, + "salad": {"price": 7.49, "prep_time": 5}, + "sushi": {"price": 15.99, "prep_time": 20} + } + self.orders = {} + self.order_counter = 1000 + + def get_menu(self): + return self.menu + + def place_order(self, item: str, quantity: int) -> dict: + item_lower = item.lower() + if item_lower not in self.menu: + return {"status": "error", "message": f"Item '{item}' not found in the menu."} + + self.order_counter += 1 + order_id = f"ORDER-{self.order_counter}" + + price = self.menu[item_lower]["price"] * quantity + prep_time = self.menu[item_lower]["prep_time"] + + self.orders[order_id] = { + "order_id": order_id, + "item": item_lower, + "quantity": quantity, + "total_price": round(price, 2), + "status": "Preparing", + "time_remaining": prep_time + } + return self.orders[order_id] + + def get_order_status(self, order_id: str) -> dict: + return self.orders.get(order_id, {"status": "error", "message": f"Order {order_id} not found."}) diff --git a/nitrostack/cli/templates/legacy_food_delivery_tools_template.txt b/nitrostack/cli/templates/legacy_food_delivery_tools_template.txt new file mode 100644 index 0000000..46efa3f --- /dev/null +++ b/nitrostack/cli/templates/legacy_food_delivery_tools_template.txt @@ -0,0 +1,45 @@ +from nitrostack import injectable, tool, ExecutionContext +from modules.food_delivery.food_delivery_service import FoodDeliveryService +from pydantic import BaseModel, Field + +class ViewMenuInput(BaseModel): + pass + +class PlaceOrderInput(BaseModel): + item: str = Field(description="The food item to order (e.g., pizza, burger, salad, sushi)") + quantity: int = Field(default=1, description="Number of items to order") + +class OrderStatusInput(BaseModel): + order_id: str = Field(description="The ID of the order to track (e.g., ORDER-1001)") + +@injectable(deps=[FoodDeliveryService]) +class FoodDeliveryController: + def __init__(self, service: FoodDeliveryService): + self.service = service + + @tool( + name="view_menu", + description="View the menu and list available food items and prices", + input_schema=ViewMenuInput + ) + async def view_menu(self, input: ViewMenuInput, context: ExecutionContext) -> dict: + context.logger.info("Fetching food delivery menu...") + return {"menu": self.service.get_menu()} + + @tool( + name="place_order", + description="Place a food delivery order for a menu item", + input_schema=PlaceOrderInput + ) + async def place_order(self, input: PlaceOrderInput, context: ExecutionContext) -> dict: + context.logger.info(f"Placing order for {input.quantity}x {input.item}") + return self.service.place_order(input.item, input.quantity) + + @tool( + name="track_order", + description="Track the status of an existing food delivery order", + input_schema=OrderStatusInput + ) + async def track_order(self, input: OrderStatusInput, context: ExecutionContext) -> dict: + context.logger.info(f"Tracking order status for {input.order_id}") + return self.service.get_order_status(input.order_id) diff --git a/nitrostack/cli/templates/legacy_main_template.txt b/nitrostack/cli/templates/legacy_main_template.txt new file mode 100644 index 0000000..6de69ef --- /dev/null +++ b/nitrostack/cli/templates/legacy_main_template.txt @@ -0,0 +1,10 @@ +import asyncio +from nitrostack import McpApplicationFactory +from app_module import AppModule + +async def main(): + app = await McpApplicationFactory.create(AppModule) + await app.start() + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/nitrostack/cli/templates/legacy_module_template.txt b/nitrostack/cli/templates/legacy_module_template.txt new file mode 100644 index 0000000..c3fcb8f --- /dev/null +++ b/nitrostack/cli/templates/legacy_module_template.txt @@ -0,0 +1,11 @@ +from nitrostack import module + +@module( + name="{name}", + imports=[], + controllers=[], + providers=[], + exports=[] +) +class {camel_name}Module: + pass diff --git a/nitrostack/cli/templates/legacy_oauth_setup_template.txt b/nitrostack/cli/templates/legacy_oauth_setup_template.txt new file mode 100644 index 0000000..c704b1d --- /dev/null +++ b/nitrostack/cli/templates/legacy_oauth_setup_template.txt @@ -0,0 +1,59 @@ +# OAuth 2.1 Server Setup Guide + +To run your flight booking MCP server with OAuth 2.1 protection, you need to configure an OAuth authorization server (like Keycloak, Auth0, Hydra, or a local mock OAuth server). + +## 1. Local Configuration + +Add the following environment variables to your `.env` file to configure resource protection: + +```env +# --- Enforcement gate ------------------------------------------------------- +# Unset / false (default): tokens are NOT enforced. Studio and Inspector can +# call tools without authenticating, against mock data. Best for local dev. +# true: Bearer tokens are enforced. If no verifier (JWKS_URI or an +# introspection endpoint) is configured, the server still starts but rejects +# every protected request -- fail closed, never fail open. +OAUTH_REQUIRED=true + +# --- Server identity -------------------------------------------------------- +RESOURCE_URI=http://localhost:3000/mcp +AUTH_SERVER_URL=https://your-tenant.us.auth0.com + +# --- Token verification: pick ONE of the two --------------------------------- +# 1) JWKS -- verifies signatures locally, no network call per request. +JWKS_URI=https://your-tenant.us.auth0.com/.well-known/jwks.json + +# 2) Or RFC 7662 introspection -- asks the authorization server per token. +# Both spellings are accepted; OAUTH_INTROSPECTION_ENDPOINT wins if both set. +# OAUTH_INTROSPECTION_ENDPOINT=http://localhost:3000/oauth/introspect +# INTROSPECTION_ENDPOINT=http://localhost:3000/oauth/introspect +# INTROSPECTION_CLIENT_ID=your-introspection-client-id +# INTROSPECTION_CLIENT_SECRET=your-introspection-client-secret + +# --- Token claim validation -------------------------------------------------- +# Audience must match, or the token is rejected (RFC 8707). Defaults to RESOURCE_URI. +TOKEN_AUDIENCE=http://localhost:3000/mcp +TOKEN_ISSUER=https://your-tenant.us.auth0.com/ + +# --- Dynamic Client Registration (RFC 7591, optional, off by default) -------- +# Serves only the statically configured client below. Requires BOTH the flag +# and OAUTH_CLIENT_ID -- without a client id it stays disabled. +# OAUTH_ENABLE_CLIENT_REGISTRATION=true +# OAUTH_CLIENT_ID=your-client-id +# OAUTH_CLIENT_SECRET=your-client-secret + +# --- Tuning ------------------------------------------------------------------ +# Seconds to cache a successful introspection result (default 300; 0 disables). +# OAUTH_TOKEN_CACHE_SECONDS=300 +# Port for the .well-known discovery server (default 3005). +# OAUTH_DISCOVERY_PORT=3005 +``` + +## 2. Protected Routes + +The tools in this server use the `@use_guards(OAuthGuard, create_scope_guard([...]))` decorators to automatically protect endpoints: +* **Public**: No guards (or custom public filters). +* **Read-Protected**: Requires valid access token with `read` scope. +* **Write-Protected**: Requires valid access token with `write` scope. + +When calling protected tools, the client must pass a valid Bearer token in the `Authorization` header. diff --git a/nitrostack/cli/templates/legacy_requirements_template.txt b/nitrostack/cli/templates/legacy_requirements_template.txt new file mode 100644 index 0000000..9e875ce --- /dev/null +++ b/nitrostack/cli/templates/legacy_requirements_template.txt @@ -0,0 +1 @@ +nitrostack diff --git a/nitrostack/cli/templates/legacy_sample_pizza_preview_json.txt b/nitrostack/cli/templates/legacy_sample_pizza_preview_json.txt new file mode 100644 index 0000000..60d81b4 --- /dev/null +++ b/nitrostack/cli/templates/legacy_sample_pizza_preview_json.txt @@ -0,0 +1,14 @@ +{ + "shops": [ + { + "id": "tonys-pizza", + "name": "Tony's New York Pizza", + "address": "123 Main St, San Francisco, CA 94102", + "rating": 4.5, + "priceLevel": 2, + "openNow": true, + "image": "https://images.unsplash.com/photo-1513104890138-7c749659a591" + } + ], + "totalShops": 1 +} \ No newline at end of file diff --git a/nitrostack/cli/templates/legacy_tool_template.txt b/nitrostack/cli/templates/legacy_tool_template.txt new file mode 100644 index 0000000..84759fa --- /dev/null +++ b/nitrostack/cli/templates/legacy_tool_template.txt @@ -0,0 +1,16 @@ +from nitrostack import tool, widget, ExecutionContext +from pydantic import BaseModel + +class {camel_name}Input(BaseModel): + # Add input parameters here + pass + +@tool( + name="{name}", + description="Implement your tool description here", + input_schema={camel_name}Input +) +@widget("{name}") +async def {name}_handler(input: {camel_name}Input, context: ExecutionContext): + context.logger.info("Executing tool {name}") + return {{"status": "success"}} diff --git a/nitrostack/cli/templates/legacy_widget_preview_html.txt b/nitrostack/cli/templates/legacy_widget_preview_html.txt new file mode 100644 index 0000000..83222c7 --- /dev/null +++ b/nitrostack/cli/templates/legacy_widget_preview_html.txt @@ -0,0 +1,52 @@ + + + + + Widget preview + + + +

+ This static file does not follow MCP Inspector tool calls. + Inspector JSON is the live result (e.g. all matching pizza shops). Open + http://localhost:3000/widgets/preview with the server running to + render that same output, or paste structuredContent below and Inject. +

+
+ +

+ + + + From 10af7956a85693cc4e17bc1c114ad877ed577b1b Mon Sep 17 00:00:00 2001 From: Siddharth Date: Fri, 6 Nov 2026 23:36:16 +0530 Subject: [PATCH 110/146] refactor(cli): separate command implementations from compatibility entry points --- nitrostack/cli/_interaction.py | 89 +++ nitrostack/cli/_parser.py | 139 ++++ nitrostack/cli/_project_init.py | 222 +++++++ nitrostack/cli/_registration.py | 155 +++++ nitrostack/cli/_runtime.py | 112 ++++ nitrostack/cli/_scaffolding.py | 53 ++ nitrostack/cli/_servers.py | 184 ++++++ nitrostack/cli/_widgets.py | 131 ++++ nitrostack/cli/main.py | 1091 ++++--------------------------- 9 files changed, 1228 insertions(+), 948 deletions(-) create mode 100644 nitrostack/cli/_interaction.py create mode 100644 nitrostack/cli/_parser.py create mode 100644 nitrostack/cli/_project_init.py create mode 100644 nitrostack/cli/_registration.py create mode 100644 nitrostack/cli/_runtime.py create mode 100644 nitrostack/cli/_scaffolding.py create mode 100644 nitrostack/cli/_servers.py create mode 100644 nitrostack/cli/_widgets.py diff --git a/nitrostack/cli/_interaction.py b/nitrostack/cli/_interaction.py new file mode 100644 index 0000000..a9bb90f --- /dev/null +++ b/nitrostack/cli/_interaction.py @@ -0,0 +1,89 @@ +"""Terminal prompts and template selection.""" + +import sys + + +def print_banner(): + banner = """\033[34m╔══════════════════════════════════════════════════════════╗ +║ ║ +║ _ _ ___ _____ ____ ___ ║ +║ | \\ | ||_ _|_ _| _ \\ / _ \\ ║ +║ | \\| | | | | | | |_) | | | | ║ +║ | |\\ | | | | | | _ <| |_| | ║ +║ |_| \\_||___| |_| |_| \\_\\\\___/ ║ +║ ║ +║ \033[1;34mNITROSTACK\033[0;34m — Official MCP Framework ║ +║ ║ +╚══════════════════════════════════════════════════════════╝\033[0m""" + print(banner) + +def _stdin_is_interactive() -> bool: + """False for Studio/CI, which inherit an stdin that may never write.""" + try: + return sys.stdin is not None and sys.stdin.isatty() + except Exception: + return False + +def _prompt(message: str, default: str='', *, _stdin_is_interactive) -> str: + default_hint = f" [{default}]" if default else "" + sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m{default_hint} ") + if not _stdin_is_interactive(): + sys.stdout.write(f"{default}\n") + sys.stdout.flush() + return default + sys.stdout.flush() + try: + value = sys.stdin.readline().strip() + except Exception: + value = "" + return value or default + +def _resolve_template(template: str, *, OFFICIAL_TEMPLATES) -> str: + key = (template or "").strip().lower() + if key not in OFFICIAL_TEMPLATES: + names = ", ".join(OFFICIAL_TEMPLATES) + print(f"Error: Unknown template '{template}'. Use one of: {names}") + sys.exit(1) + return key + +def _prompt_template(*, OFFICIAL_TEMPLATES, _prompt) -> str: + print("\033[32m? \033[1;37mChoose a template:\033[0m") + print(" \033[34m1. python-starter\033[0m Starter — simple calculator for learning basics") + print(" \033[34m2. python-pizzaz\033[0m Advanced — pizza shop finder with maps & widgets") + print(" \033[34m3. python-oauth\033[0m Flight booking with OAuth 2.1 auth") + print(" \033[34m4. python-enterprise-search\033[0m BM25 progressive tool discovery") + print(" \033[34m5. python-code-mode\033[0m QuickJS multi-tool workflows") + by_choice = { + "1": "python-starter", + "2": "python-pizzaz", + "3": "python-oauth", + "4": "python-enterprise-search", + "5": "python-code-mode", + } + while True: + choice = _prompt("Enter choice (1-5) or template name", "1") + if choice in by_choice: + return by_choice[choice] + if choice.lower() in OFFICIAL_TEMPLATES: + return choice.lower() + print("Please enter 1-5, or an explicit template name (" + ", ".join(OFFICIAL_TEMPLATES) + ").") + +def _prompt_yes_no(message: str, default_yes: bool=True, *, _stdin_is_interactive) -> bool: + hint = "Y/n" if default_yes else "y/N" + sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m ({hint}) ") + if not _stdin_is_interactive(): + sys.stdout.write(("yes" if default_yes else "no") + "\n") + sys.stdout.flush() + return default_yes + sys.stdout.flush() + try: + ans = sys.stdin.readline().strip().lower() + except Exception: + ans = "" + if not ans: + return default_yes + if ans in ("y", "yes"): + return True + if ans in ("n", "no"): + return False + return default_yes diff --git a/nitrostack/cli/_parser.py b/nitrostack/cli/_parser.py new file mode 100644 index 0000000..111716e --- /dev/null +++ b/nitrostack/cli/_parser.py @@ -0,0 +1,139 @@ +"""CLI argument declarations; dispatch stays in the public entry module.""" + +import argparse +import os + + +def build_parser(*, _add_port_flags, OFFICIAL_TEMPLATES): + parser = argparse.ArgumentParser( + prog="nitrostack-py", + description="nitrostack-py CLI — Scaffold, develop, pack, and run NitroStack Python MCP servers", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "examples:\n" + " nitrostack-py init my-server\n" + " nitrostack-py generate guard MyGuard\n" + " nitrostack-py pack --dry-run\n" + " nitrostack-py upgrade --dry-run\n" + " nitrostack-py install --production\n" + " nitrostack-py validate\n" + ), + ) + subparsers = parser.add_subparsers(dest="command", metavar="command") + + # init command + init_parser = subparsers.add_parser("init", help="Initialize a new NitroStack MCP server project") + init_parser.add_argument("name", nargs="?", default=None, help="Name of the project directory (prompted if omitted)") + init_parser.add_argument( + "--template", + choices=list(OFFICIAL_TEMPLATES.keys()), + default=None, + help="Template to use: " + ", ".join(OFFICIAL_TEMPLATES) + " (default: interactive prompt)", + ) + init_parser.add_argument("--skip-install", action="store_true", help="Skip installing Python (and widget npm) dependencies") + init_parser.add_argument( + "--force", + action="store_true", + help="Overwrite existing agent skill directories when installing", + ) + _add_port_flags(init_parser) + + # dev command + dev_parser = subparsers.add_parser("dev", help="Start the hot-reloading development server") + _add_port_flags(dev_parser) + + # start command + start_parser = subparsers.add_parser("start", help="Start the production server") + _add_port_flags(start_parser) + + # register command + reg_parser = subparsers.add_parser("register", help="Register server script inside Claude Desktop configuration") + reg_parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="Name of the server (defaults to folder name)") + reg_parser.add_argument("--file", default="main.py", help="Python script to register (defaults to main.py)") + + # cursor command + cursor_parser = subparsers.add_parser("cursor", help="Register this server in Cursor MCP configuration") + cursor_parser.add_argument("--global", dest="global_config", action="store_true", help="Write to ~/.cursor/mcp.json") + cursor_parser.add_argument( + "--transport", + choices=("command", "streamable-http", "sse"), + default="command", + help="Connection type (default: command)", + ) + cursor_parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="Name of the server") + cursor_parser.add_argument("--file", default="main.py", help="Python script to register for command transport") + + # generate command + gen_parser = subparsers.add_parser( + "generate", + help="Generate boilerplate code (tool, module, guard, pipe, interceptor, filter, service)", + ) + gen_subparsers = gen_parser.add_subparsers(dest="generator", metavar="type") + + tool_parser = gen_subparsers.add_parser("tool", help="Generate a new tool boilerplate") + tool_parser.add_argument("name", help="Name of the tool") + + mod_parser = gen_subparsers.add_parser("module", help="Generate a new module boilerplate") + mod_parser.add_argument("name", help="Name of the module") + + for kind, kind_help in ( + ("guard", "Generate an authorization guard"), + ("pipe", "Generate a validation/transform pipe"), + ("interceptor", "Generate an execution interceptor"), + ("filter", "Generate an exception filter"), + ("service", "Generate an injectable service"), + ): + kind_parser = gen_subparsers.add_parser(kind, help=kind_help) + kind_parser.add_argument("name", help=f"Name of the {kind}") + + # pack command + pack_parser = subparsers.add_parser( + "pack", + help="Build a deployable wheel of the current project (never includes .env/secrets)", + ) + pack_parser.add_argument( + "--dry-run", + action="store_true", + help="Show files that would be packed without creating the artifact", + ) + + # upgrade command + upgrade_parser = subparsers.add_parser( + "upgrade", + help="Update the nitrostack dependency to the latest (or a specific) PyPI version", + ) + upgrade_parser.add_argument( + "--version", + dest="target_version", + metavar="X.Y.Z", + help="Pin nitrostack to this version instead of the latest PyPI release", + ) + upgrade_parser.add_argument( + "--dry-run", + action="store_true", + help="Show the version change without modifying pyproject.toml", + ) + upgrade_parser.add_argument( + "--allow-downgrade", + action="store_true", + help="Allow --version to pin an older release than the one currently declared", + ) + + # install command + install_parser = subparsers.add_parser( + "install", + help="Install project dependencies from pyproject.toml / requirements.txt", + ) + install_parser.add_argument( + "--production", + action="store_true", + help="Skip development dependencies (optional extras and requirements-dev.txt)", + ) + + # validate command + subparsers.add_parser( + "validate", + help="Lint project config, @mcp_app imports, and @module() class references", + ) + + return parser, gen_parser diff --git a/nitrostack/cli/_project_init.py b/nitrostack/cli/_project_init.py new file mode 100644 index 0000000..f8584be --- /dev/null +++ b/nitrostack/cli/_project_init.py @@ -0,0 +1,222 @@ +"""Project initialization and dependency setup.""" + +import os +import sys +import shutil +import subprocess + + +def init_project( + name: str = None, + template: str = None, + skip_install: bool = False, + port = None, + widget = None, + force: bool = False, + *, + DEFAULT_MCP_PORT, + DEFAULT_PROJECT_NAME, + DEFAULT_WIDGETS_PORT, + OFFICIAL_TEMPLATES, + _normalize_port, + _prompt, + _prompt_template, + _prompt_yes_no, + _resolve_template, + _run_npm, + _stdin_is_interactive, + _upsert_env_var, + ensure_python_widgets, + install_dependencies, + lock_with_uv, + print_banner, + rewrite_pyproject_identity, + run_skills_flow, +): + print_banner() + + # 1. Project name — optional CLI arg, otherwise the next readline + if not name: + name = _prompt("Project name", DEFAULT_PROJECT_NAME) + name = (name or "").strip() + if not name: + print("Error: Project name cannot be empty.") + sys.exit(1) + + # 2. Overwrite check + if os.path.exists(name): + if not _stdin_is_interactive(): + print(f"Error: Directory '{name}' already exists.") + sys.exit(1) + sys.stdout.write(f"\033[32m? \033[1;37mDirectory '{name}' already exists. Overwrite?\033[0m (Yes/No) [No]: ") + sys.stdout.flush() + ans = sys.stdin.readline().strip().lower() + if ans not in ("y", "yes"): + print("Initialization cancelled.") + sys.exit(0) + shutil.rmtree(name, ignore_errors=True) + + # 3. Select template (explicit python-* names) + if not template: + template = _prompt_template() + else: + template = _resolve_template(template) + + # 4. Description and Author (defaults when stdin is not a TTY) + description = _prompt("Description", "My awesome MCP server") + author = _prompt("Author", "developer") + + # 5. Install dependencies (Y/n). --skip-install skips the prompt. + if skip_install: + install_deps = False + else: + install_deps = _prompt_yes_no("Install dependencies", default_yes=True) + + mcp_port = _normalize_port(port, "--port") if port is not None else DEFAULT_MCP_PORT + widgets_port = _normalize_port(widget, "--widget") if widget is not None else DEFAULT_WIDGETS_PORT + + # 6. Copy template directory + import nitrostack + package_dir = os.path.dirname(nitrostack.__file__) + template_dir = OFFICIAL_TEMPLATES[template] + template_src_dir = os.path.join(package_dir, "templates", template_dir) + + if not os.path.exists(template_src_dir): + print(f"Error: Template '{template}' not found at '{template_src_dir}'.") + sys.exit(1) + + shutil.copytree(template_src_dir, name) + rewrite_pyproject_identity( + os.path.join(name, "pyproject.toml"), + name=os.path.basename(os.path.abspath(name)), + description=description, + ) + from nitrostack.cli.vendor import ensure_vendored_nitrostack + ensure_vendored_nitrostack(name) + lock_with_uv(name) + widget_routes = ensure_python_widgets(name) + print("\n\033[32m✓\033[0m Project created") + if widget_routes: + print(f"\033[32m✓\033[0m Python widgets: {', '.join(widget_routes)}") + print(" HTML in widgets/out/ — preview: widgets/preview.html") + + # 7. Update .env file + env_path = os.path.join(name, ".env") + env_example_path = os.path.join(name, ".env.example") + if not os.path.exists(env_path) and os.path.isfile(env_example_path): + shutil.copyfile(env_example_path, env_path) + if os.path.exists(env_path): + with open(env_path, "r", encoding="utf-8") as f: + lines = f.readlines() + new_lines = [] + for line in lines: + if line.startswith("SERVER_NAME="): + new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n') + elif line.startswith("SERVER_DESC="): + new_lines.append(f'SERVER_DESC="{description}"\n') + elif line.startswith("SERVER_AUTHOR="): + new_lines.append(f'SERVER_AUTHOR="{author}"\n') + else: + new_lines.append(line) + has_name = any(line.startswith("SERVER_NAME=") for line in new_lines) + has_desc = any(line.startswith("SERVER_DESC=") for line in new_lines) + has_author = any(line.startswith("SERVER_AUTHOR=") for line in new_lines) + if not has_name: + new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n') + if not has_desc: + new_lines.append(f'SERVER_DESC="{description}"\n') + if not has_author: + new_lines.append(f'SERVER_AUTHOR="{author}"\n') + new_lines = _upsert_env_var(new_lines, "PORT", mcp_port) + new_lines = _upsert_env_var(new_lines, "WIDGETS_DEV_PORT", widgets_port) + new_lines = _upsert_env_var(new_lines, "NITROSTACK_APP_MODE", "universal") + with open(env_path, "w", encoding="utf-8") as f: + f.writelines(new_lines) + + # 8. Update widgets package.json + widgets_package_path = os.path.join(name, "src", "widgets", "package.json") + if os.path.exists(widgets_package_path): + import json + try: + with open(widgets_package_path, "r", encoding="utf-8") as f: + pkg = json.load(f) + pkg["name"] = f"{name}-widgets" + # The port is passed once by the CLI (`npm run dev -- --port N`), so it + # is deliberately not baked into the script. + scripts = pkg.setdefault("scripts", {}) + scripts["dev"] = "next dev" + scripts["start"] = "next start" + with open(widgets_package_path, "w", encoding="utf-8") as f: + json.dump(pkg, f, indent=2) + except Exception: + pass + + # 9. Install Python deps (requirements.txt / pyproject.toml), then widget npm if present. + if install_deps: + print("Installing dependencies...") + try: + install_dependencies(cwd=name) + print("\033[32m✓\033[0m Dependencies installed") + except Exception as e: + print(f"Warning: Failed to install dependencies: {e}") + print("Please run 'nitrostack-py install' from the project directory.\n") + widgets_dir = os.path.join(name, "src", "widgets") + if os.path.exists(widgets_dir): + print("Installing widget dependencies...") + try: + _run_npm(["--version"], capture_output=True, check=True, text=True) + _run_npm(["install"], cwd=widgets_dir, check=True) + print("\033[32m✓\033[0m Widget dependencies installed\n") + except FileNotFoundError as e: + print(f"Warning: {e}") + print("Please run 'npm install' inside 'src/widgets' manually.\n") + except subprocess.CalledProcessError as e: + detail = (getattr(e, "stderr", None) or getattr(e, "stdout", None) or str(e)).strip() + print(f"Warning: Failed to install widget dependencies: {detail}") + print("Please run 'npm install' inside 'src/widgets' manually.\n") + else: + print("\033[32m✓\033[0m Skipped dependency install") + + run_skills_flow(os.path.abspath(name), force=force) + + # Success Card + abs_path = os.path.abspath(name) + success_box = f"""\033[36m╔══════════════════════════════════════════════════════════╗ +║ \033[32m✓ Project Ready\033[36m ║ +║ ║ +║ Name: {name:<48} ║ +║ Template: {template:<44} ║ +║ Path: {abs_path:<48} ║ +╚══════════════════════════════════════════════════════════╝\033[0m""" + print(success_box) + + # Next Steps + print("\n\033[1;37mNext steps:\033[0m") + print(f" 1. \033[34mcd {name}\033[0m") + if template in ("python-enterprise-search", "python-code-mode"): + print(" 2. Read README.md for sample tool calls and local demonstration data") + print(" 3. Validate the project: nitrostack-py validate") + print(" 4. Install dependencies if skipped: nitrostack-py install") + print(" 5. Start an MCP stdio server: python main.py") + print(" For HTTP set MCP_TRANSPORT_TYPE=http, then connect to http://localhost:3000/mcp") + if template == "python-code-mode": + print(" Try scripts/sample-batch.js through execute; QuickJS must be installed") + else: + print(" Try search_tools with 'overdue invoices', then invoke it through call_tool") + print("\nHappy coding! 🚀\n") + return + if template == "python-oauth": + print(" 2. Configure OAuth credentials in your \033[34m.env\033[0m file") + print(" See \033[34mOAUTH_SETUP.md\033[0m for provider guides") + else: + print(" 2. Configure environment variables in \033[34m.env\033[0m") + print(" 3. Start development server: \033[34mnitrostack-py dev\033[0m (or `python -m nitrostack.cli.main dev`)") + print(" 4. Preview widgets: \033[34mhttp://localhost:3000/widgets/preview\033[0m (server running)") + print(" Static file (manual JSON): \033[34mopen widgets/preview.html\033[0m") + print(" 5. Inspector (HTTP): \033[34mMCP_TRANSPORT_TYPE=http MCP_STATELESS=true NITROSTACK_APP_MODE=universal python main.py\033[0m") + print(" Connect Streamable HTTP to \033[34mhttp://localhost:3000/mcp\033[0m with \033[34mAuthentication = Off\033[0m") + print(" Apps tab renders the widget from live \033[34mstructuredContent\033[0m (not widgets/preview.html)") + print(" For open shops only set \033[34mopenNow=true\033[0m (list) or \033[34mfilter=open_now\033[0m (map)") + print(" 6. NitroStudio cannot folder-connect a Python project (it looks for @nitrostack/core).") + print(" Use Inspector HTTP as above, or Studio's custom MCP URL if it offers Streamable HTTP.") + print("\nHappy coding! 🚀\n") diff --git a/nitrostack/cli/_registration.py b/nitrostack/cli/_registration.py new file mode 100644 index 0000000..229a7b9 --- /dev/null +++ b/nitrostack/cli/_registration.py @@ -0,0 +1,155 @@ +"""Claude Desktop and Cursor client registration.""" + +import os +import sys + + +def get_claude_config_paths(): + paths = [] + home = os.path.expanduser("~") + + # Windows + if sys.platform == "win32": + appdata = os.environ.get("APPDATA") + if appdata: + paths.append(os.path.join(appdata, "Claude", "claude_desktop_config.json")) + # Windows Store app path + localappdata = os.environ.get("LOCALAPPDATA") + if localappdata: + store_dir = os.path.join(localappdata, "Packages") + if os.path.exists(store_dir): + try: + for folder in os.listdir(store_dir): + if folder.startswith("Claude_"): + paths.append(os.path.join(store_dir, folder, "LocalCache", "Roaming", "Claude", "claude_desktop_config.json")) + except Exception: + pass + # macOS + elif sys.platform == "darwin": + paths.append(os.path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json")) + # Linux + else: + paths.append(os.path.join(home, ".config", "Claude", "claude_desktop_config.json")) + + return [p for p in paths if os.path.exists(os.path.dirname(p))] + +def register_server(name: str, file_path: str, *, _build_server_entry, get_claude_config_paths): + import json + + if not os.path.exists(file_path): + print(f"Error: Script file '{file_path}' does not exist.") + sys.exit(1) + + server_entry = _build_server_entry(file_path) + + config_paths = get_claude_config_paths() + if not config_paths: + print("Error: Could not find any Claude Desktop installation directories.") + print("Please ensure Claude Desktop is installed on your machine.") + sys.exit(1) + + registered_any = False + for path in config_paths: + try: + config = {} + if os.path.exists(path): + with open(path, "r", encoding="utf-8") as f: + content = f.read().strip() + if content: + try: + config = json.loads(content) + except json.JSONDecodeError: + print(f"Warning: Configuration file at '{path}' is not valid JSON. Resetting it.") + + if "mcpServers" not in config: + config["mcpServers"] = {} + + config["mcpServers"][name] = server_entry + + # Create directory if needed + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + json.dump(config, f, indent=2) + + print(f"Successfully registered server '{name}' in: {path}") + registered_any = True + except Exception as e: + print(f"Error writing to config at '{path}': {e}") + + if registered_any: + print("\nAll done! Please fully restart Claude Desktop to load your new server.") + else: + print("Error: Failed to register the server in any configuration files.") + +def _build_server_entry(file_path: str): + """Build the stdio server entry shared by register and Cursor configs.""" + return { + "command": sys.executable, + "args": [os.path.abspath(file_path)], + } + +def _write_json_atomic(path: str, data): + """Replace a JSON config atomically so readers never see a partial write.""" + import json + import tempfile + + directory = os.path.dirname(path) + os.makedirs(directory, exist_ok=True) + fd, temp_path = tempfile.mkstemp(prefix=".mcp-", suffix=".tmp", dir=directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + f.write("\n") + os.replace(temp_path, path) + except Exception: + try: + os.unlink(temp_path) + except OSError: + pass + raise + +def register_cursor_server( + name: str, + file_path: str = 'main.py', + *, + global_config: bool = False, + transport: str = 'command', + _build_server_entry, + _write_json_atomic, +): + """Merge this project into Cursor's project or user MCP configuration.""" + import json + + if transport not in ("command", "streamable-http", "sse"): + raise ValueError("transport must be command, streamable-http, or sse") + if transport == "command" and not os.path.exists(file_path): + print(f"Error: Script file '{file_path}' does not exist.") + sys.exit(1) + + if global_config: + config_path = os.path.join(os.path.expanduser("~"), ".cursor", "mcp.json") + else: + config_path = os.path.join(os.getcwd(), ".cursor", "mcp.json") + + config = {} + if os.path.exists(config_path): + try: + with open(config_path, "r", encoding="utf-8") as f: + config = json.load(f) + except (json.JSONDecodeError, OSError): + config = {} + if not isinstance(config, dict): + config = {} + servers = config.get("mcpServers") + if not isinstance(servers, dict): + servers = {} + config["mcpServers"] = servers + + if transport == "command": + entry = _build_server_entry(file_path) + else: + route = "mcp" if transport == "streamable-http" else "sse" + entry = {"url": f"http://localhost:3000/{route}"} + servers[name] = entry + _write_json_atomic(config_path, config) + print(f"Successfully registered server '{name}' in Cursor config: {config_path}") diff --git a/nitrostack/cli/_runtime.py b/nitrostack/cli/_runtime.py new file mode 100644 index 0000000..d5d8340 --- /dev/null +++ b/nitrostack/cli/_runtime.py @@ -0,0 +1,112 @@ +"""Runtime ports, environment settings and npm launch helpers.""" + +import os +import sys +import shutil +import subprocess + + +def _normalize_port(value, label): + try: + port = int(value) + except (TypeError, ValueError): + print(f"Error: Invalid {label} '{value}'.") + sys.exit(1) + if port < 1 or port > 65535: + print(f"Error: {label} {port} is out of range (1-65535).") + sys.exit(1) + return str(port) + +def _read_project_env(): + values = {} + env_path = os.path.join(os.getcwd(), ".env") + if not os.path.exists(env_path): + return values + try: + with open(env_path, encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, val = line.partition("=") + values[key.strip()] = val.strip().strip('"').strip("'") + except Exception: + pass + return values + +def _resolve_runtime_ports( + port = None, + widget = None, + *, + DEFAULT_MCP_PORT, + DEFAULT_WIDGETS_PORT, + _normalize_port, + _read_project_env, +): + """Resolve MCP and widget ports. Explicit --port/--widget flags override defaults.""" + project_env = _read_project_env() + if port is not None: + mcp_port = _normalize_port(port, "--port") + else: + mcp_port = ( + os.environ.get("PORT") + or os.environ.get("MCP_SERVER_PORT") + or project_env.get("PORT") + or project_env.get("MCP_SERVER_PORT") + or DEFAULT_MCP_PORT + ) + mcp_port = str(mcp_port) + if widget is None and mcp_port == DEFAULT_WIDGETS_PORT: + mcp_port = DEFAULT_MCP_PORT + + if widget is not None: + widgets_port = _normalize_port(widget, "--widget") + else: + widgets_port = os.environ.get("WIDGETS_DEV_PORT") or project_env.get("WIDGETS_DEV_PORT") or DEFAULT_WIDGETS_PORT + widgets_port = str(widgets_port) + if port is None and widgets_port == DEFAULT_MCP_PORT: + widgets_port = DEFAULT_WIDGETS_PORT + return mcp_port, widgets_port + +def _upsert_env_var(lines, key, value): + prefix = f"{key}=" + updated = False + new_lines = [] + for line in lines: + if line.startswith(prefix): + new_lines.append(f"{key}={value}\n") + updated = True + else: + new_lines.append(line) + if not updated: + new_lines.append(f"{key}={value}\n") + return new_lines + +def _find_npm(): + npm = shutil.which("npm") or shutil.which("npm.cmd") + if not npm: + raise FileNotFoundError( + "npm was not found on PATH. Install Node.js (https://nodejs.org) and retry." + ) + return npm + +def _run_npm(args, *, _find_npm, **kwargs): + """Run npm without shell=True. A list + shell=True is treated as `sh -c npm` and drops flags.""" + kwargs.pop("shell", None) + return subprocess.run([_find_npm(), *args], **kwargs) + +def _popen_npm(args, *, _find_npm, **kwargs): + kwargs.pop("shell", None) + return subprocess.Popen([_find_npm(), *args], **kwargs) + +def _add_port_flags(parser, *, DEFAULT_MCP_PORT, DEFAULT_WIDGETS_PORT): + parser.add_argument( + "--port", + default=None, + help=f"MCP HTTP port (default: {DEFAULT_MCP_PORT}; overrides PORT when set)", + ) + parser.add_argument( + "--widget", + default=None, + help=f"Widget dev server port (default: {DEFAULT_WIDGETS_PORT}; overrides WIDGETS_DEV_PORT when set)", + ) diff --git a/nitrostack/cli/_scaffolding.py b/nitrostack/cli/_scaffolding.py new file mode 100644 index 0000000..ab3ef35 --- /dev/null +++ b/nitrostack/cli/_scaffolding.py @@ -0,0 +1,53 @@ +"""Tool and module generation commands.""" + +import os +import sys + + +def generate_tool( + name: str, + *, + TOOL_TEMPLATE, + _assert_dest_inside_root, + _sanitize_widget_route, + _validate_generate_name, + write_widget_html, + write_widget_preview, +): + # Both validators run before anything is written. `_validate_generate_name` and + # `_sanitize_widget_route` accept overlapping-but-different character sets (e.g. + # `_foo` is a valid identifier but not a valid route; `my-tool` is the reverse), + # so validating the route lazily inside `write_widget_html` would leave an orphan + # `{name}_tool.py` behind whenever the two disagree — and that orphan then blocks + # any retry with "File already exists". + try: + name = _validate_generate_name(name) + _sanitize_widget_route(name) + except ValueError as exc: + print(f"Error: {exc}") + sys.exit(1) + filename = f"{name}_tool.py" + dest_py = os.path.abspath(filename) + try: + _assert_dest_inside_root(dest_py, os.getcwd()) + except ValueError as exc: + print(f"Error: {exc}") + sys.exit(1) + if os.path.exists(filename): + print(f"Error: File '{filename}' already exists.") + sys.exit(1) + camel_name = "".join(part.capitalize() for part in name.split("_")) + content = TOOL_TEMPLATE.format(name=name, camel_name=camel_name) + with open(filename, "w", encoding="utf-8") as f: + f.write(content) + try: + html_path = write_widget_html(".", name, overwrite=False) + except ValueError as exc: + print(f"Error: {exc}") + sys.exit(1) + write_widget_preview(".") + print(f"Generated tool boilerplate in '{filename}'") + print(f"Generated widget HTML in '{html_path}'") + +def generate_module(name: str, *, generate_module_from_template): + generate_module_from_template(name) diff --git a/nitrostack/cli/_servers.py b/nitrostack/cli/_servers.py new file mode 100644 index 0000000..97f1029 --- /dev/null +++ b/nitrostack/cli/_servers.py @@ -0,0 +1,184 @@ +"""Development and production process lifecycles.""" + +import os +import sys +import subprocess +import time + + +def run_dev(port=None, widget=None, *, _popen_npm, _resolve_runtime_ports): + target = "main.py" + if not os.path.exists(target): + print("Error: main.py not found in current directory.") + sys.exit(1) + + mcp_port, widgets_port = _resolve_runtime_ports(port, widget) + + print(f"Starting hot-reload development server for {target}...") + print(f"MCP server port: {mcp_port}") + process = None + widgets_process = None + + # Check if Next.js widgets are present + widgets_dir = os.path.join(os.getcwd(), "src", "widgets") + has_widgets = os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json")) + if has_widgets: + print(f"Starting widget development server on port {widgets_port}...") + try: + widgets_process = _popen_npm( + ["run", "dev", "--", "--port", str(widgets_port)], + cwd=widgets_dir, + ) + except Exception as e: + print(f"Warning: Could not start widget development server: {e}") + + def start_process(): + nonlocal process + if process: + try: + process.terminate() + process.wait(timeout=2) + except Exception: + try: + process.kill() + except Exception: + pass + env = os.environ.copy() + env["PYTHONPATH"] = os.path.abspath(".") + env["PORT"] = mcp_port + if has_widgets: + env["WIDGETS_DEV_PORT"] = str(widgets_port) + process = subprocess.Popen([sys.executable, target], env=env) + + def cleanup(): + nonlocal process, widgets_process + if process: + try: + process.terminate() + except Exception: + pass + if widgets_process: + try: + widgets_process.terminate() + except Exception: + pass + + try: + start_process() + + watched_extensions = {".py", ".env"} + + def get_mtimes(): + mtimes = {} + for root, dirs, files in os.walk("."): + if any(part.startswith(".") or part in ("venv", "env", "__pycache__") for part in root.split(os.sep)): + continue + for file in files: + ext = os.path.splitext(file)[1] + if ext in watched_extensions: + path = os.path.join(root, file) + try: + mtimes[path] = os.path.getmtime(path) + except Exception: + pass + return mtimes + + # Try using watchfiles for high-performance, low-CPU file monitoring + try: + from watchfiles import watch + print("Using watchfiles for high-performance file monitoring.") + + while True: + for changes in watch("."): + should_restart = False + for change_type, path in changes: + ext = os.path.splitext(path)[1] + if ext in watched_extensions: + parts = os.path.normpath(path).split(os.sep) + if not any(p in parts for p in ("venv", "env", "__pycache__", ".git", ".pytest_cache", "nitrostack.egg-info")): + should_restart = True + break + if should_restart: + print("File changes detected! Restarting server...") + start_process() + + time.sleep(0.5) + if process and process.poll() is not None: + print("Server process exited. Waiting for file changes to restart...") + + except ImportError: + print("watchfiles library not found. Falling back to standard polling...") + last_mtimes = get_mtimes() + try: + while True: + time.sleep(1) + if process and process.poll() is not None: + print("Server process exited. Waiting for file changes to restart...") + current_mtimes = get_mtimes() + changed = False + if set(current_mtimes.keys()) != set(last_mtimes.keys()): + changed = True + else: + for path, mtime in current_mtimes.items(): + if last_mtimes.get(path) != mtime: + changed = True + break + if changed: + print("File changes detected! Restarting server...") + start_process() + last_mtimes = current_mtimes + except KeyboardInterrupt: + pass + except KeyboardInterrupt: + print("\nStopping development server...") + cleanup() + +def run_start(port=None, widget=None, *, _popen_npm, _resolve_runtime_ports): + target = "main.py" + if not os.path.exists(target): + print("Error: main.py not found in current directory.") + sys.exit(1) + + mcp_port, widgets_port = _resolve_runtime_ports(port, widget) + + print(f"Starting production server for {target}...") + print(f"MCP HTTP: http://localhost:{mcp_port}/mcp") + env = os.environ.copy() + env["PYTHONPATH"] = os.path.abspath(".") + env["PORT"] = mcp_port + env["WIDGETS_DEV_PORT"] = widgets_port + env["NODE_ENV"] = "production" + # Select HTTP explicitly rather than letting NODE_ENV=production fall through + # to dual. Dual shuts HTTP down when STDIO reaches EOF, so `start` would exit + # immediately wherever stdin is not held open (Docker without -i, systemd, CI). + # `setdefault` keeps an explicit MCP_TRANSPORT_TYPE from the caller. + env.setdefault("MCP_TRANSPORT_TYPE", "http") + + widgets_dir = os.path.join(os.getcwd(), "src", "widgets") + widgets_process = None + if os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json")): + # `next start` needs a production build; Popen would succeed and the child + # would fail with a bare "Could not find a production build", so check here. + if not os.path.exists(os.path.join(widgets_dir, ".next")): + print("Widgets are not built yet — skipping the widget server.") + print("Run 'npm run build' inside 'src/widgets', then retry.\n") + else: + print(f"Starting widget server on port {widgets_port}...") + try: + widgets_process = _popen_npm( + ["run", "start", "--", "--port", str(widgets_port)], + cwd=widgets_dir, + ) + except Exception as e: + print(f"Warning: Could not start widget server: {e}") + + try: + subprocess.run([sys.executable, target], env=env) + except KeyboardInterrupt: + print("\nStopping server...") + finally: + if widgets_process: + try: + widgets_process.terminate() + except Exception: + pass diff --git a/nitrostack/cli/_widgets.py b/nitrostack/cli/_widgets.py new file mode 100644 index 0000000..2a9e391 --- /dev/null +++ b/nitrostack/cli/_widgets.py @@ -0,0 +1,131 @@ +"""Widget scaffolding and safe output paths.""" + +import os +import re +from pathlib import Path + + +_GENERATE_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +_WIDGET_ROUTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") + + +def _validate_generate_name(name: str) -> str: + """Reject path segments so ``generate tool ../../ESCAPED`` cannot write outside cwd.""" + name = (name or "").strip() + if not name or os.path.basename(name) != name or ".." in name or not _GENERATE_NAME_RE.fullmatch(name): + raise ValueError( + "name must be a Python identifier (letters, digits, underscore) " + "and cannot contain path separators" + ) + return name + +def _sanitize_widget_route(route: str) -> str: + route = (route or "").strip() + if not route or os.path.basename(route) != route or ".." in route or not _WIDGET_ROUTE_RE.fullmatch(route): + raise ValueError("widget route must be a single alphanumeric path segment") + return route + +def _assert_dest_inside_root(dest: str, root: str) -> str: + dest_abs = os.path.realpath(dest) + root_abs = os.path.realpath(root) + try: + common = os.path.commonpath([dest_abs, root_abs]) + except ValueError as exc: + raise ValueError("generated path would escape the project directory") from exc + if common != root_abs: + raise ValueError("generated path would escape the project directory") + return dest_abs + +def write_widget_html( + project_dir: str, + route: str, + *, + overwrite: bool = False, + _assert_dest_inside_root, + _sanitize_widget_route, +) -> str: + """Write ``widgets/out/{route}.html`` if missing (Python-only static widget).""" + from nitrostack.widgets.route_templates import build_widget_html_for_route + + route = _sanitize_widget_route(route) + project_dir = os.path.abspath(project_dir or ".") + out_dir = os.path.join(project_dir, "widgets", "out") + os.makedirs(out_dir, exist_ok=True) + dest = os.path.join(out_dir, f"{route}.html") + _assert_dest_inside_root(dest, project_dir) + if overwrite or not os.path.exists(dest): + with open(dest, "w", encoding="utf-8") as f: + f.write(build_widget_html_for_route(route)) + return dest + +def write_widget_preview( + project_dir: str, + *, + SAMPLE_PIZZA_PREVIEW_JSON, + WIDGET_PREVIEW_HTML, +) -> None: + from html import escape as html_escape + + from nitrostack.widgets.html_util import json_for_inline_script + + out_dir = os.path.join(project_dir, "widgets", "out") + if not os.path.isdir(out_dir): + return + routes = sorted(p[:-5] for p in os.listdir(out_dir) if p.endswith(".html")) + if not routes: + return + first = "pizza-list" if "pizza-list" in routes else routes[0] + default_payload: dict = {"status": "success"} + if "pizza-list" in routes or "pizza-map" in routes: + import json as json_lib + + default_payload = json_lib.loads(SAMPLE_PIZZA_PREVIEW_JSON) + html = ( + WIDGET_PREVIEW_HTML.replace("__FIRST__", html_escape(first, quote=True)) + .replace("__ROUTES__", json_for_inline_script(routes)) + .replace("__DEFAULT_JSON__", html_escape(json_for_inline_script(default_payload), quote=False)) + ) + dest = os.path.join(project_dir, "widgets", "preview.html") + with open(dest, "w", encoding="utf-8") as f: + f.write(html) + +def ensure_python_widgets( + project_dir: str, + *, + Path, + write_widget_html, + write_widget_preview, +) -> list: + """Create missing ``widgets/out/{route}.html`` for every ``@widget`` in the project.""" + routes = [] + for root, _dirs, files in os.walk(project_dir): + parts = set(root.split(os.sep)) + if "node_modules" in parts or ".venv" in parts: + continue + for name in files: + if not name.endswith(".py"): + continue + path = os.path.join(root, name) + try: + text = Path(path).read_text(encoding="utf-8") + except OSError: + continue + routes.extend(re.findall(r'@widget\(\s*["\']([^"\']+)["\']', text)) + routes.extend(re.findall(r'WidgetOptions\(\s*route\s*=\s*["\']([^"\']+)["\']', text)) + # Only routes that were actually scaffolded go into the returned list — callers + # print it as "created", so appending before the write would report a widget that + # never landed on disk. A rejected route is surfaced rather than skipped silently. + unique = [] + seen = set() + for route in routes: + if route in seen: + continue + seen.add(route) + try: + write_widget_html(project_dir, route, overwrite=False) + except ValueError as exc: + print(f"Warning: skipped widget route {route!r}: {exc}") + continue + unique.append(route) + write_widget_preview(project_dir) + return unique diff --git a/nitrostack/cli/main.py b/nitrostack/cli/main.py index b55a7a8..eb22ce9 100644 --- a/nitrostack/cli/main.py +++ b/nitrostack/cli/main.py @@ -1,3 +1,5 @@ +"""CLI entry points and backwards-compatible helper imports.""" + from nitrostack.cli._config import DEFAULT_PROJECT_NAME, DEFAULT_MCP_PORT, DEFAULT_WIDGETS_PORT, OFFICIAL_TEMPLATES from nitrostack.cli._template_text import ( MAIN_TEMPLATE, @@ -26,7 +28,6 @@ SAMPLE_PIZZA_PREVIEW_JSON, MODULE_TEMPLATE, ) - import os import re import sys @@ -35,899 +36,219 @@ import subprocess import time from pathlib import Path - from nitrostack.cli.generate import generate_component, generate_module as generate_module_from_template from nitrostack.cli.install import install_dependencies, lock_with_uv, rewrite_pyproject_identity from nitrostack.cli.pack import pack_project from nitrostack.cli.skills import run_skills_flow from nitrostack.cli.upgrade import upgrade_project from nitrostack.cli.validators import format_report, validate_project +from nitrostack.cli._parser import build_parser +from nitrostack.cli import _widgets +from nitrostack.cli import _interaction +from nitrostack.cli import _runtime +from nitrostack.cli import _project_init +from nitrostack.cli import _servers +from nitrostack.cli import _scaffolding +from nitrostack.cli import _registration +_GENERATE_NAME_RE = _widgets._GENERATE_NAME_RE +_WIDGET_ROUTE_RE = _widgets._WIDGET_ROUTE_RE +_validate_generate_name = _widgets._validate_generate_name +_sanitize_widget_route = _widgets._sanitize_widget_route +_assert_dest_inside_root = _widgets._assert_dest_inside_root +def write_widget_html(project_dir: str, route: str, *, overwrite: bool = False) -> str: + 'Write ``widgets/out/{route}.html`` if missing (Python-only static widget).' + return _widgets.write_widget_html( + project_dir, + route, + overwrite=overwrite, + _assert_dest_inside_root=_assert_dest_inside_root, + _sanitize_widget_route=_sanitize_widget_route, + ) +def write_widget_preview(project_dir: str) -> None: + return _widgets.write_widget_preview( + project_dir, + SAMPLE_PIZZA_PREVIEW_JSON=SAMPLE_PIZZA_PREVIEW_JSON, + WIDGET_PREVIEW_HTML=WIDGET_PREVIEW_HTML, + ) +def ensure_python_widgets(project_dir: str) -> list: + 'Create missing ``widgets/out/{route}.html`` for every ``@widget`` in the project.' + return _widgets.ensure_python_widgets( + project_dir, + Path=Path, + write_widget_html=write_widget_html, + write_widget_preview=write_widget_preview, + ) +print_banner = _interaction.print_banner +_stdin_is_interactive = _interaction._stdin_is_interactive +def _prompt(message: str, default: str = "") -> str: + return _interaction._prompt(message, default, _stdin_is_interactive=_stdin_is_interactive) -# Official CLI names → on-disk template directories. - - - - - - -_GENERATE_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") -_WIDGET_ROUTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") - +def _resolve_template(template: str) -> str: + return _interaction._resolve_template(template, OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES) -def _validate_generate_name(name: str) -> str: - """Reject path segments so ``generate tool ../../ESCAPED`` cannot write outside cwd.""" - name = (name or "").strip() - if not name or os.path.basename(name) != name or ".." in name or not _GENERATE_NAME_RE.fullmatch(name): - raise ValueError( - "name must be a Python identifier (letters, digits, underscore) " - "and cannot contain path separators" - ) - return name +def _prompt_template() -> str: + return _interaction._prompt_template(OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES, _prompt=_prompt) -def _sanitize_widget_route(route: str) -> str: - route = (route or "").strip() - if not route or os.path.basename(route) != route or ".." in route or not _WIDGET_ROUTE_RE.fullmatch(route): - raise ValueError("widget route must be a single alphanumeric path segment") - return route +def _prompt_yes_no(message: str, default_yes: bool = True) -> bool: + return _interaction._prompt_yes_no(message, default_yes, _stdin_is_interactive=_stdin_is_interactive) -def _assert_dest_inside_root(dest: str, root: str) -> str: - dest_abs = os.path.realpath(dest) - root_abs = os.path.realpath(root) - try: - common = os.path.commonpath([dest_abs, root_abs]) - except ValueError as exc: - raise ValueError("generated path would escape the project directory") from exc - if common != root_abs: - raise ValueError("generated path would escape the project directory") - return dest_abs +_normalize_port = _runtime._normalize_port -def write_widget_html(project_dir: str, route: str, *, overwrite: bool = False) -> str: - """Write ``widgets/out/{route}.html`` if missing (Python-only static widget).""" - from nitrostack.widgets.route_templates import build_widget_html_for_route - route = _sanitize_widget_route(route) - project_dir = os.path.abspath(project_dir or ".") - out_dir = os.path.join(project_dir, "widgets", "out") - os.makedirs(out_dir, exist_ok=True) - dest = os.path.join(out_dir, f"{route}.html") - _assert_dest_inside_root(dest, project_dir) - if overwrite or not os.path.exists(dest): - with open(dest, "w", encoding="utf-8") as f: - f.write(build_widget_html_for_route(route)) - return dest +_read_project_env = _runtime._read_project_env -def write_widget_preview(project_dir: str) -> None: - from html import escape as html_escape - - from nitrostack.widgets.html_util import json_for_inline_script - - out_dir = os.path.join(project_dir, "widgets", "out") - if not os.path.isdir(out_dir): - return - routes = sorted(p[:-5] for p in os.listdir(out_dir) if p.endswith(".html")) - if not routes: - return - first = "pizza-list" if "pizza-list" in routes else routes[0] - default_payload: dict = {"status": "success"} - if "pizza-list" in routes or "pizza-map" in routes: - import json as json_lib - - default_payload = json_lib.loads(SAMPLE_PIZZA_PREVIEW_JSON) - html = ( - WIDGET_PREVIEW_HTML.replace("__FIRST__", html_escape(first, quote=True)) - .replace("__ROUTES__", json_for_inline_script(routes)) - .replace("__DEFAULT_JSON__", html_escape(json_for_inline_script(default_payload), quote=False)) +def _resolve_runtime_ports(port=None, widget=None): + 'Resolve MCP and widget ports. Explicit --port/--widget flags override defaults.' + return _runtime._resolve_runtime_ports( + port, + widget, + DEFAULT_MCP_PORT=DEFAULT_MCP_PORT, + DEFAULT_WIDGETS_PORT=DEFAULT_WIDGETS_PORT, + _normalize_port=_normalize_port, + _read_project_env=_read_project_env, ) - dest = os.path.join(project_dir, "widgets", "preview.html") - with open(dest, "w", encoding="utf-8") as f: - f.write(html) -def ensure_python_widgets(project_dir: str) -> list: - """Create missing ``widgets/out/{route}.html`` for every ``@widget`` in the project.""" - routes = [] - for root, _dirs, files in os.walk(project_dir): - parts = set(root.split(os.sep)) - if "node_modules" in parts or ".venv" in parts: - continue - for name in files: - if not name.endswith(".py"): - continue - path = os.path.join(root, name) - try: - text = Path(path).read_text(encoding="utf-8") - except OSError: - continue - routes.extend(re.findall(r'@widget\(\s*["\']([^"\']+)["\']', text)) - routes.extend(re.findall(r'WidgetOptions\(\s*route\s*=\s*["\']([^"\']+)["\']', text)) - # Only routes that were actually scaffolded go into the returned list — callers - # print it as "created", so appending before the write would report a widget that - # never landed on disk. A rejected route is surfaced rather than skipped silently. - unique = [] - seen = set() - for route in routes: - if route in seen: - continue - seen.add(route) - try: - write_widget_html(project_dir, route, overwrite=False) - except ValueError as exc: - print(f"Warning: skipped widget route {route!r}: {exc}") - continue - unique.append(route) - write_widget_preview(project_dir) - return unique - - -def print_banner(): - banner = """\033[34m╔══════════════════════════════════════════════════════════╗ -║ ║ -║ _ _ ___ _____ ____ ___ ║ -║ | \\ | ||_ _|_ _| _ \\ / _ \\ ║ -║ | \\| | | | | | | |_) | | | | ║ -║ | |\\ | | | | | | _ <| |_| | ║ -║ |_| \\_||___| |_| |_| \\_\\\\___/ ║ -║ ║ -║ \033[1;34mNITROSTACK\033[0;34m — Official MCP Framework ║ -║ ║ -╚══════════════════════════════════════════════════════════╝\033[0m""" - print(banner) - -def _stdin_is_interactive() -> bool: - """False for Studio/CI, which inherit an stdin that may never write.""" - try: - return sys.stdin is not None and sys.stdin.isatty() - except Exception: - return False +_upsert_env_var = _runtime._upsert_env_var -def _prompt(message: str, default: str = "") -> str: - default_hint = f" [{default}]" if default else "" - sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m{default_hint} ") - if not _stdin_is_interactive(): - sys.stdout.write(f"{default}\n") - sys.stdout.flush() - return default - sys.stdout.flush() - try: - value = sys.stdin.readline().strip() - except Exception: - value = "" - return value or default - - -def _resolve_template(template: str) -> str: - key = (template or "").strip().lower() - if key not in OFFICIAL_TEMPLATES: - names = ", ".join(OFFICIAL_TEMPLATES) - print(f"Error: Unknown template '{template}'. Use one of: {names}") - sys.exit(1) - return key - - -def _prompt_template() -> str: - print("\033[32m? \033[1;37mChoose a template:\033[0m") - print(" \033[34m1. python-starter\033[0m Starter — simple calculator for learning basics") - print(" \033[34m2. python-pizzaz\033[0m Advanced — pizza shop finder with maps & widgets") - print(" \033[34m3. python-oauth\033[0m Flight booking with OAuth 2.1 auth") - print(" \033[34m4. python-enterprise-search\033[0m BM25 progressive tool discovery") - print(" \033[34m5. python-code-mode\033[0m QuickJS multi-tool workflows") - by_choice = { - "1": "python-starter", - "2": "python-pizzaz", - "3": "python-oauth", - "4": "python-enterprise-search", - "5": "python-code-mode", - } - while True: - choice = _prompt("Enter choice (1-5) or template name", "1") - if choice in by_choice: - return by_choice[choice] - if choice.lower() in OFFICIAL_TEMPLATES: - return choice.lower() - print("Please enter 1-5, or an explicit template name (" + ", ".join(OFFICIAL_TEMPLATES) + ").") - - -def _normalize_port(value, label): - try: - port = int(value) - except (TypeError, ValueError): - print(f"Error: Invalid {label} '{value}'.") - sys.exit(1) - if port < 1 or port > 65535: - print(f"Error: {label} {port} is out of range (1-65535).") - sys.exit(1) - return str(port) - - -def _read_project_env(): - values = {} - env_path = os.path.join(os.getcwd(), ".env") - if not os.path.exists(env_path): - return values - try: - with open(env_path, encoding="utf-8") as f: - for line in f: - line = line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - key, _, val = line.partition("=") - values[key.strip()] = val.strip().strip('"').strip("'") - except Exception: - pass - return values - - -def _resolve_runtime_ports(port=None, widget=None): - """Resolve MCP and widget ports. Explicit --port/--widget flags override defaults.""" - project_env = _read_project_env() - if port is not None: - mcp_port = _normalize_port(port, "--port") - else: - mcp_port = ( - os.environ.get("PORT") - or os.environ.get("MCP_SERVER_PORT") - or project_env.get("PORT") - or project_env.get("MCP_SERVER_PORT") - or DEFAULT_MCP_PORT - ) - mcp_port = str(mcp_port) - if widget is None and mcp_port == DEFAULT_WIDGETS_PORT: - mcp_port = DEFAULT_MCP_PORT - - if widget is not None: - widgets_port = _normalize_port(widget, "--widget") - else: - widgets_port = os.environ.get("WIDGETS_DEV_PORT") or project_env.get("WIDGETS_DEV_PORT") or DEFAULT_WIDGETS_PORT - widgets_port = str(widgets_port) - if port is None and widgets_port == DEFAULT_MCP_PORT: - widgets_port = DEFAULT_WIDGETS_PORT - return mcp_port, widgets_port - - -def _upsert_env_var(lines, key, value): - prefix = f"{key}=" - updated = False - new_lines = [] - for line in lines: - if line.startswith(prefix): - new_lines.append(f"{key}={value}\n") - updated = True - else: - new_lines.append(line) - if not updated: - new_lines.append(f"{key}={value}\n") - return new_lines - - -def _prompt_yes_no(message: str, default_yes: bool = True) -> bool: - hint = "Y/n" if default_yes else "y/N" - sys.stdout.write(f"\033[32m? \033[1;37m{message}:\033[0m ({hint}) ") - if not _stdin_is_interactive(): - sys.stdout.write(("yes" if default_yes else "no") + "\n") - sys.stdout.flush() - return default_yes - sys.stdout.flush() - try: - ans = sys.stdin.readline().strip().lower() - except Exception: - ans = "" - if not ans: - return default_yes - if ans in ("y", "yes"): - return True - if ans in ("n", "no"): - return False - return default_yes - - -def _find_npm(): - npm = shutil.which("npm") or shutil.which("npm.cmd") - if not npm: - raise FileNotFoundError( - "npm was not found on PATH. Install Node.js (https://nodejs.org) and retry." - ) - return npm +_find_npm = _runtime._find_npm def _run_npm(args, **kwargs): - """Run npm without shell=True. A list + shell=True is treated as `sh -c npm` and drops flags.""" - kwargs.pop("shell", None) - return subprocess.run([_find_npm(), *args], **kwargs) + 'Run npm without shell=True. A list + shell=True is treated as `sh -c npm` and drops flags.' + return _runtime._run_npm(args, _find_npm=_find_npm, **kwargs) def _popen_npm(args, **kwargs): - kwargs.pop("shell", None) - return subprocess.Popen([_find_npm(), *args], **kwargs) + return _runtime._popen_npm(args, _find_npm=_find_npm, **kwargs) def _add_port_flags(parser): - parser.add_argument( - "--port", - default=None, - help=f"MCP HTTP port (default: {DEFAULT_MCP_PORT}; overrides PORT when set)", - ) - parser.add_argument( - "--widget", - default=None, - help=f"Widget dev server port (default: {DEFAULT_WIDGETS_PORT}; overrides WIDGETS_DEV_PORT when set)", + return _runtime._add_port_flags( + parser, + DEFAULT_MCP_PORT=DEFAULT_MCP_PORT, + DEFAULT_WIDGETS_PORT=DEFAULT_WIDGETS_PORT, ) def init_project(name: str = None, template: str = None, skip_install: bool = False, port=None, widget=None, force: bool = False): - print_banner() - - # 1. Project name — optional CLI arg, otherwise the next readline - if not name: - name = _prompt("Project name", DEFAULT_PROJECT_NAME) - name = (name or "").strip() - if not name: - print("Error: Project name cannot be empty.") - sys.exit(1) - - # 2. Overwrite check - if os.path.exists(name): - if not _stdin_is_interactive(): - print(f"Error: Directory '{name}' already exists.") - sys.exit(1) - sys.stdout.write(f"\033[32m? \033[1;37mDirectory '{name}' already exists. Overwrite?\033[0m (Yes/No) [No]: ") - sys.stdout.flush() - ans = sys.stdin.readline().strip().lower() - if ans not in ("y", "yes"): - print("Initialization cancelled.") - sys.exit(0) - shutil.rmtree(name, ignore_errors=True) - - # 3. Select template (explicit python-* names) - if not template: - template = _prompt_template() - else: - template = _resolve_template(template) - - # 4. Description and Author (defaults when stdin is not a TTY) - description = _prompt("Description", "My awesome MCP server") - author = _prompt("Author", "developer") - - # 5. Install dependencies (Y/n). --skip-install skips the prompt. - if skip_install: - install_deps = False - else: - install_deps = _prompt_yes_no("Install dependencies", default_yes=True) - - mcp_port = _normalize_port(port, "--port") if port is not None else DEFAULT_MCP_PORT - widgets_port = _normalize_port(widget, "--widget") if widget is not None else DEFAULT_WIDGETS_PORT - - # 6. Copy template directory - import nitrostack - package_dir = os.path.dirname(nitrostack.__file__) - template_dir = OFFICIAL_TEMPLATES[template] - template_src_dir = os.path.join(package_dir, "templates", template_dir) - - if not os.path.exists(template_src_dir): - print(f"Error: Template '{template}' not found at '{template_src_dir}'.") - sys.exit(1) - - shutil.copytree(template_src_dir, name) - rewrite_pyproject_identity( - os.path.join(name, "pyproject.toml"), - name=os.path.basename(os.path.abspath(name)), - description=description, + return _project_init.init_project( + name, + template, + skip_install, + port, + widget, + force, + DEFAULT_MCP_PORT=DEFAULT_MCP_PORT, + DEFAULT_PROJECT_NAME=DEFAULT_PROJECT_NAME, + DEFAULT_WIDGETS_PORT=DEFAULT_WIDGETS_PORT, + OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES, + _normalize_port=_normalize_port, + _prompt=_prompt, + _prompt_template=_prompt_template, + _prompt_yes_no=_prompt_yes_no, + _resolve_template=_resolve_template, + _run_npm=_run_npm, + _stdin_is_interactive=_stdin_is_interactive, + _upsert_env_var=_upsert_env_var, + ensure_python_widgets=ensure_python_widgets, + install_dependencies=install_dependencies, + lock_with_uv=lock_with_uv, + print_banner=print_banner, + rewrite_pyproject_identity=rewrite_pyproject_identity, + run_skills_flow=run_skills_flow, ) - from nitrostack.cli.vendor import ensure_vendored_nitrostack - ensure_vendored_nitrostack(name) - lock_with_uv(name) - widget_routes = ensure_python_widgets(name) - print("\n\033[32m✓\033[0m Project created") - if widget_routes: - print(f"\033[32m✓\033[0m Python widgets: {', '.join(widget_routes)}") - print(" HTML in widgets/out/ — preview: widgets/preview.html") - - # 7. Update .env file - env_path = os.path.join(name, ".env") - env_example_path = os.path.join(name, ".env.example") - if not os.path.exists(env_path) and os.path.isfile(env_example_path): - shutil.copyfile(env_example_path, env_path) - if os.path.exists(env_path): - with open(env_path, "r", encoding="utf-8") as f: - lines = f.readlines() - new_lines = [] - for line in lines: - if line.startswith("SERVER_NAME="): - new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n') - elif line.startswith("SERVER_DESC="): - new_lines.append(f'SERVER_DESC="{description}"\n') - elif line.startswith("SERVER_AUTHOR="): - new_lines.append(f'SERVER_AUTHOR="{author}"\n') - else: - new_lines.append(line) - has_name = any(line.startswith("SERVER_NAME=") for line in new_lines) - has_desc = any(line.startswith("SERVER_DESC=") for line in new_lines) - has_author = any(line.startswith("SERVER_AUTHOR=") for line in new_lines) - if not has_name: - new_lines.append(f'SERVER_NAME="{os.path.basename(os.path.abspath(name))}"\n') - if not has_desc: - new_lines.append(f'SERVER_DESC="{description}"\n') - if not has_author: - new_lines.append(f'SERVER_AUTHOR="{author}"\n') - new_lines = _upsert_env_var(new_lines, "PORT", mcp_port) - new_lines = _upsert_env_var(new_lines, "WIDGETS_DEV_PORT", widgets_port) - new_lines = _upsert_env_var(new_lines, "NITROSTACK_APP_MODE", "universal") - with open(env_path, "w", encoding="utf-8") as f: - f.writelines(new_lines) - - # 8. Update widgets package.json - widgets_package_path = os.path.join(name, "src", "widgets", "package.json") - if os.path.exists(widgets_package_path): - import json - try: - with open(widgets_package_path, "r", encoding="utf-8") as f: - pkg = json.load(f) - pkg["name"] = f"{name}-widgets" - # The port is passed once by the CLI (`npm run dev -- --port N`), so it - # is deliberately not baked into the script. - scripts = pkg.setdefault("scripts", {}) - scripts["dev"] = "next dev" - scripts["start"] = "next start" - with open(widgets_package_path, "w", encoding="utf-8") as f: - json.dump(pkg, f, indent=2) - except Exception: - pass - # 9. Install Python deps (requirements.txt / pyproject.toml), then widget npm if present. - if install_deps: - print("Installing dependencies...") - try: - install_dependencies(cwd=name) - print("\033[32m✓\033[0m Dependencies installed") - except Exception as e: - print(f"Warning: Failed to install dependencies: {e}") - print("Please run 'nitrostack-py install' from the project directory.\n") - widgets_dir = os.path.join(name, "src", "widgets") - if os.path.exists(widgets_dir): - print("Installing widget dependencies...") - try: - _run_npm(["--version"], capture_output=True, check=True, text=True) - _run_npm(["install"], cwd=widgets_dir, check=True) - print("\033[32m✓\033[0m Widget dependencies installed\n") - except FileNotFoundError as e: - print(f"Warning: {e}") - print("Please run 'npm install' inside 'src/widgets' manually.\n") - except subprocess.CalledProcessError as e: - detail = (getattr(e, "stderr", None) or getattr(e, "stdout", None) or str(e)).strip() - print(f"Warning: Failed to install widget dependencies: {detail}") - print("Please run 'npm install' inside 'src/widgets' manually.\n") - else: - print("\033[32m✓\033[0m Skipped dependency install") - - run_skills_flow(os.path.abspath(name), force=force) - - # Success Card - abs_path = os.path.abspath(name) - success_box = f"""\033[36m╔══════════════════════════════════════════════════════════╗ -║ \033[32m✓ Project Ready\033[36m ║ -║ ║ -║ Name: {name:<48} ║ -║ Template: {template:<44} ║ -║ Path: {abs_path:<48} ║ -╚══════════════════════════════════════════════════════════╝\033[0m""" - print(success_box) - - # Next Steps - print("\n\033[1;37mNext steps:\033[0m") - print(f" 1. \033[34mcd {name}\033[0m") - if template in ("python-enterprise-search", "python-code-mode"): - print(" 2. Read README.md for sample tool calls and local demonstration data") - print(" 3. Validate the project: nitrostack-py validate") - print(" 4. Install dependencies if skipped: nitrostack-py install") - print(" 5. Start an MCP stdio server: python main.py") - print(" For HTTP set MCP_TRANSPORT_TYPE=http, then connect to http://localhost:3000/mcp") - if template == "python-code-mode": - print(" Try scripts/sample-batch.js through execute; QuickJS must be installed") - else: - print(" Try search_tools with 'overdue invoices', then invoke it through call_tool") - print("\nHappy coding! 🚀\n") - return - if template == "python-oauth": - print(" 2. Configure OAuth credentials in your \033[34m.env\033[0m file") - print(" See \033[34mOAUTH_SETUP.md\033[0m for provider guides") - else: - print(" 2. Configure environment variables in \033[34m.env\033[0m") - print(" 3. Start development server: \033[34mnitrostack-py dev\033[0m (or `python -m nitrostack.cli.main dev`)") - print(" 4. Preview widgets: \033[34mhttp://localhost:3000/widgets/preview\033[0m (server running)") - print(" Static file (manual JSON): \033[34mopen widgets/preview.html\033[0m") - print(" 5. Inspector (HTTP): \033[34mMCP_TRANSPORT_TYPE=http MCP_STATELESS=true NITROSTACK_APP_MODE=universal python main.py\033[0m") - print(" Connect Streamable HTTP to \033[34mhttp://localhost:3000/mcp\033[0m with \033[34mAuthentication = Off\033[0m") - print(" Apps tab renders the widget from live \033[34mstructuredContent\033[0m (not widgets/preview.html)") - print(" For open shops only set \033[34mopenNow=true\033[0m (list) or \033[34mfilter=open_now\033[0m (map)") - print(" 6. NitroStudio cannot folder-connect a Python project (it looks for @nitrostack/core).") - print(" Use Inspector HTTP as above, or Studio's custom MCP URL if it offers Streamable HTTP.") - print("\nHappy coding! 🚀\n") def run_dev(port=None, widget=None): - target = "main.py" - if not os.path.exists(target): - print("Error: main.py not found in current directory.") - sys.exit(1) - - mcp_port, widgets_port = _resolve_runtime_ports(port, widget) + return _servers.run_dev( + port, + widget, + _popen_npm=_popen_npm, + _resolve_runtime_ports=_resolve_runtime_ports, + ) - print(f"Starting hot-reload development server for {target}...") - print(f"MCP server port: {mcp_port}") - process = None - widgets_process = None - - # Check if Next.js widgets are present - widgets_dir = os.path.join(os.getcwd(), "src", "widgets") - has_widgets = os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json")) - if has_widgets: - print(f"Starting widget development server on port {widgets_port}...") - try: - widgets_process = _popen_npm( - ["run", "dev", "--", "--port", str(widgets_port)], - cwd=widgets_dir, - ) - except Exception as e: - print(f"Warning: Could not start widget development server: {e}") - - def start_process(): - nonlocal process - if process: - try: - process.terminate() - process.wait(timeout=2) - except Exception: - try: - process.kill() - except Exception: - pass - env = os.environ.copy() - env["PYTHONPATH"] = os.path.abspath(".") - env["PORT"] = mcp_port - if has_widgets: - env["WIDGETS_DEV_PORT"] = str(widgets_port) - process = subprocess.Popen([sys.executable, target], env=env) - - def cleanup(): - nonlocal process, widgets_process - if process: - try: - process.terminate() - except Exception: - pass - if widgets_process: - try: - widgets_process.terminate() - except Exception: - pass - - try: - start_process() - - watched_extensions = {".py", ".env"} - - def get_mtimes(): - mtimes = {} - for root, dirs, files in os.walk("."): - if any(part.startswith(".") or part in ("venv", "env", "__pycache__") for part in root.split(os.sep)): - continue - for file in files: - ext = os.path.splitext(file)[1] - if ext in watched_extensions: - path = os.path.join(root, file) - try: - mtimes[path] = os.path.getmtime(path) - except Exception: - pass - return mtimes - - # Try using watchfiles for high-performance, low-CPU file monitoring - try: - from watchfiles import watch - print("Using watchfiles for high-performance file monitoring.") - - while True: - for changes in watch("."): - should_restart = False - for change_type, path in changes: - ext = os.path.splitext(path)[1] - if ext in watched_extensions: - parts = os.path.normpath(path).split(os.sep) - if not any(p in parts for p in ("venv", "env", "__pycache__", ".git", ".pytest_cache", "nitrostack.egg-info")): - should_restart = True - break - if should_restart: - print("File changes detected! Restarting server...") - start_process() - - time.sleep(0.5) - if process and process.poll() is not None: - print("Server process exited. Waiting for file changes to restart...") - - except ImportError: - print("watchfiles library not found. Falling back to standard polling...") - last_mtimes = get_mtimes() - try: - while True: - time.sleep(1) - if process and process.poll() is not None: - print("Server process exited. Waiting for file changes to restart...") - current_mtimes = get_mtimes() - changed = False - if set(current_mtimes.keys()) != set(last_mtimes.keys()): - changed = True - else: - for path, mtime in current_mtimes.items(): - if last_mtimes.get(path) != mtime: - changed = True - break - if changed: - print("File changes detected! Restarting server...") - start_process() - last_mtimes = current_mtimes - except KeyboardInterrupt: - pass - except KeyboardInterrupt: - print("\nStopping development server...") - cleanup() def run_start(port=None, widget=None): - target = "main.py" - if not os.path.exists(target): - print("Error: main.py not found in current directory.") - sys.exit(1) + return _servers.run_start( + port, + widget, + _popen_npm=_popen_npm, + _resolve_runtime_ports=_resolve_runtime_ports, + ) - mcp_port, widgets_port = _resolve_runtime_ports(port, widget) - - print(f"Starting production server for {target}...") - print(f"MCP HTTP: http://localhost:{mcp_port}/mcp") - env = os.environ.copy() - env["PYTHONPATH"] = os.path.abspath(".") - env["PORT"] = mcp_port - env["WIDGETS_DEV_PORT"] = widgets_port - env["NODE_ENV"] = "production" - # Select HTTP explicitly rather than letting NODE_ENV=production fall through - # to dual. Dual shuts HTTP down when STDIO reaches EOF, so `start` would exit - # immediately wherever stdin is not held open (Docker without -i, systemd, CI). - # `setdefault` keeps an explicit MCP_TRANSPORT_TYPE from the caller. - env.setdefault("MCP_TRANSPORT_TYPE", "http") - - widgets_dir = os.path.join(os.getcwd(), "src", "widgets") - widgets_process = None - if os.path.exists(widgets_dir) and os.path.exists(os.path.join(widgets_dir, "package.json")): - # `next start` needs a production build; Popen would succeed and the child - # would fail with a bare "Could not find a production build", so check here. - if not os.path.exists(os.path.join(widgets_dir, ".next")): - print("Widgets are not built yet — skipping the widget server.") - print("Run 'npm run build' inside 'src/widgets', then retry.\n") - else: - print(f"Starting widget server on port {widgets_port}...") - try: - widgets_process = _popen_npm( - ["run", "start", "--", "--port", str(widgets_port)], - cwd=widgets_dir, - ) - except Exception as e: - print(f"Warning: Could not start widget server: {e}") - - try: - subprocess.run([sys.executable, target], env=env) - except KeyboardInterrupt: - print("\nStopping server...") - finally: - if widgets_process: - try: - widgets_process.terminate() - except Exception: - pass def generate_tool(name: str): - # Both validators run before anything is written. `_validate_generate_name` and - # `_sanitize_widget_route` accept overlapping-but-different character sets (e.g. - # `_foo` is a valid identifier but not a valid route; `my-tool` is the reverse), - # so validating the route lazily inside `write_widget_html` would leave an orphan - # `{name}_tool.py` behind whenever the two disagree — and that orphan then blocks - # any retry with "File already exists". - try: - name = _validate_generate_name(name) - _sanitize_widget_route(name) - except ValueError as exc: - print(f"Error: {exc}") - sys.exit(1) - filename = f"{name}_tool.py" - dest_py = os.path.abspath(filename) - try: - _assert_dest_inside_root(dest_py, os.getcwd()) - except ValueError as exc: - print(f"Error: {exc}") - sys.exit(1) - if os.path.exists(filename): - print(f"Error: File '{filename}' already exists.") - sys.exit(1) - camel_name = "".join(part.capitalize() for part in name.split("_")) - content = TOOL_TEMPLATE.format(name=name, camel_name=camel_name) - with open(filename, "w", encoding="utf-8") as f: - f.write(content) - try: - html_path = write_widget_html(".", name, overwrite=False) - except ValueError as exc: - print(f"Error: {exc}") - sys.exit(1) - write_widget_preview(".") - print(f"Generated tool boilerplate in '{filename}'") - print(f"Generated widget HTML in '{html_path}'") + return _scaffolding.generate_tool( + name, + TOOL_TEMPLATE=TOOL_TEMPLATE, + _assert_dest_inside_root=_assert_dest_inside_root, + _sanitize_widget_route=_sanitize_widget_route, + _validate_generate_name=_validate_generate_name, + write_widget_html=write_widget_html, + write_widget_preview=write_widget_preview, + ) + def generate_module(name: str): - generate_module_from_template(name) - -def get_claude_config_paths(): - paths = [] - home = os.path.expanduser("~") - - # Windows - if sys.platform == "win32": - appdata = os.environ.get("APPDATA") - if appdata: - paths.append(os.path.join(appdata, "Claude", "claude_desktop_config.json")) - # Windows Store app path - localappdata = os.environ.get("LOCALAPPDATA") - if localappdata: - store_dir = os.path.join(localappdata, "Packages") - if os.path.exists(store_dir): - try: - for folder in os.listdir(store_dir): - if folder.startswith("Claude_"): - paths.append(os.path.join(store_dir, folder, "LocalCache", "Roaming", "Claude", "claude_desktop_config.json")) - except Exception: - pass - # macOS - elif sys.platform == "darwin": - paths.append(os.path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json")) - # Linux - else: - paths.append(os.path.join(home, ".config", "Claude", "claude_desktop_config.json")) - - return [p for p in paths if os.path.exists(os.path.dirname(p))] + return _scaffolding.generate_module(name, generate_module_from_template=generate_module_from_template) + + +get_claude_config_paths = _registration.get_claude_config_paths + def register_server(name: str, file_path: str): - import json - - if not os.path.exists(file_path): - print(f"Error: Script file '{file_path}' does not exist.") - sys.exit(1) - - server_entry = _build_server_entry(file_path) - - config_paths = get_claude_config_paths() - if not config_paths: - print("Error: Could not find any Claude Desktop installation directories.") - print("Please ensure Claude Desktop is installed on your machine.") - sys.exit(1) - - registered_any = False - for path in config_paths: - try: - config = {} - if os.path.exists(path): - with open(path, "r", encoding="utf-8") as f: - content = f.read().strip() - if content: - try: - config = json.loads(content) - except json.JSONDecodeError: - print(f"Warning: Configuration file at '{path}' is not valid JSON. Resetting it.") - - if "mcpServers" not in config: - config["mcpServers"] = {} - - config["mcpServers"][name] = server_entry - - # Create directory if needed - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - json.dump(config, f, indent=2) - - print(f"Successfully registered server '{name}' in: {path}") - registered_any = True - except Exception as e: - print(f"Error writing to config at '{path}': {e}") - - if registered_any: - print("\nAll done! Please fully restart Claude Desktop to load your new server.") - else: - print("Error: Failed to register the server in any configuration files.") - - -def _build_server_entry(file_path: str): - """Build the stdio server entry shared by register and Cursor configs.""" - return { - "command": sys.executable, - "args": [os.path.abspath(file_path)], - } - - -def _write_json_atomic(path: str, data): - """Replace a JSON config atomically so readers never see a partial write.""" - import json - import tempfile - - directory = os.path.dirname(path) - os.makedirs(directory, exist_ok=True) - fd, temp_path = tempfile.mkstemp(prefix=".mcp-", suffix=".tmp", dir=directory) - try: - with os.fdopen(fd, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2) - f.write("\n") - os.replace(temp_path, path) - except Exception: - try: - os.unlink(temp_path) - except OSError: - pass - raise + return _registration.register_server( + name, + file_path, + _build_server_entry=_build_server_entry, + get_claude_config_paths=get_claude_config_paths, + ) -def register_cursor_server(name: str, file_path: str = "main.py", *, global_config: bool = False, transport: str = "command"): - """Merge this project into Cursor's project or user MCP configuration.""" - import json +_build_server_entry = _registration._build_server_entry - if transport not in ("command", "streamable-http", "sse"): - raise ValueError("transport must be command, streamable-http, or sse") - if transport == "command" and not os.path.exists(file_path): - print(f"Error: Script file '{file_path}' does not exist.") - sys.exit(1) - if global_config: - config_path = os.path.join(os.path.expanduser("~"), ".cursor", "mcp.json") - else: - config_path = os.path.join(os.getcwd(), ".cursor", "mcp.json") +_write_json_atomic = _registration._write_json_atomic + + +def register_cursor_server(name: str, file_path: str = "main.py", *, global_config: bool = False, transport: str = "command"): + "Merge this project into Cursor's project or user MCP configuration." + return _registration.register_cursor_server( + name, + file_path, + global_config=global_config, + transport=transport, + _build_server_entry=_build_server_entry, + _write_json_atomic=_write_json_atomic, + ) - config = {} - if os.path.exists(config_path): - try: - with open(config_path, "r", encoding="utf-8") as f: - config = json.load(f) - except (json.JSONDecodeError, OSError): - config = {} - if not isinstance(config, dict): - config = {} - servers = config.get("mcpServers") - if not isinstance(servers, dict): - servers = {} - config["mcpServers"] = servers - - if transport == "command": - entry = _build_server_entry(file_path) - else: - route = "mcp" if transport == "streamable-http" else "sse" - entry = {"url": f"http://localhost:3000/{route}"} - servers[name] = entry - _write_json_atomic(config_path, config) - print(f"Successfully registered server '{name}' in Cursor config: {config_path}") def main(): if hasattr(sys.stdout, "reconfigure"): @@ -941,135 +262,8 @@ def main(): except Exception: pass - parser = argparse.ArgumentParser( - prog="nitrostack-py", - description="nitrostack-py CLI — Scaffold, develop, pack, and run NitroStack Python MCP servers", - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=( - "examples:\n" - " nitrostack-py init my-server\n" - " nitrostack-py generate guard MyGuard\n" - " nitrostack-py pack --dry-run\n" - " nitrostack-py upgrade --dry-run\n" - " nitrostack-py install --production\n" - " nitrostack-py validate\n" - ), - ) - subparsers = parser.add_subparsers(dest="command", metavar="command") - - # init command - init_parser = subparsers.add_parser("init", help="Initialize a new NitroStack MCP server project") - init_parser.add_argument("name", nargs="?", default=None, help="Name of the project directory (prompted if omitted)") - init_parser.add_argument( - "--template", - choices=list(OFFICIAL_TEMPLATES.keys()), - default=None, - help="Template to use: " + ", ".join(OFFICIAL_TEMPLATES) + " (default: interactive prompt)", - ) - init_parser.add_argument("--skip-install", action="store_true", help="Skip installing Python (and widget npm) dependencies") - init_parser.add_argument( - "--force", - action="store_true", - help="Overwrite existing agent skill directories when installing", - ) - _add_port_flags(init_parser) - - # dev command - dev_parser = subparsers.add_parser("dev", help="Start the hot-reloading development server") - _add_port_flags(dev_parser) - - # start command - start_parser = subparsers.add_parser("start", help="Start the production server") - _add_port_flags(start_parser) - - # register command - reg_parser = subparsers.add_parser("register", help="Register server script inside Claude Desktop configuration") - reg_parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="Name of the server (defaults to folder name)") - reg_parser.add_argument("--file", default="main.py", help="Python script to register (defaults to main.py)") - - # cursor command - cursor_parser = subparsers.add_parser("cursor", help="Register this server in Cursor MCP configuration") - cursor_parser.add_argument("--global", dest="global_config", action="store_true", help="Write to ~/.cursor/mcp.json") - cursor_parser.add_argument( - "--transport", - choices=("command", "streamable-http", "sse"), - default="command", - help="Connection type (default: command)", - ) - cursor_parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="Name of the server") - cursor_parser.add_argument("--file", default="main.py", help="Python script to register for command transport") - - # generate command - gen_parser = subparsers.add_parser( - "generate", - help="Generate boilerplate code (tool, module, guard, pipe, interceptor, filter, service)", - ) - gen_subparsers = gen_parser.add_subparsers(dest="generator", metavar="type") - - tool_parser = gen_subparsers.add_parser("tool", help="Generate a new tool boilerplate") - tool_parser.add_argument("name", help="Name of the tool") - - mod_parser = gen_subparsers.add_parser("module", help="Generate a new module boilerplate") - mod_parser.add_argument("name", help="Name of the module") - - for kind, kind_help in ( - ("guard", "Generate an authorization guard"), - ("pipe", "Generate a validation/transform pipe"), - ("interceptor", "Generate an execution interceptor"), - ("filter", "Generate an exception filter"), - ("service", "Generate an injectable service"), - ): - kind_parser = gen_subparsers.add_parser(kind, help=kind_help) - kind_parser.add_argument("name", help=f"Name of the {kind}") - - # pack command - pack_parser = subparsers.add_parser( - "pack", - help="Build a deployable wheel of the current project (never includes .env/secrets)", - ) - pack_parser.add_argument( - "--dry-run", - action="store_true", - help="Show files that would be packed without creating the artifact", - ) - - # upgrade command - upgrade_parser = subparsers.add_parser( - "upgrade", - help="Update the nitrostack dependency to the latest (or a specific) PyPI version", - ) - upgrade_parser.add_argument( - "--version", - dest="target_version", - metavar="X.Y.Z", - help="Pin nitrostack to this version instead of the latest PyPI release", - ) - upgrade_parser.add_argument( - "--dry-run", - action="store_true", - help="Show the version change without modifying pyproject.toml", - ) - upgrade_parser.add_argument( - "--allow-downgrade", - action="store_true", - help="Allow --version to pin an older release than the one currently declared", - ) - - # install command - install_parser = subparsers.add_parser( - "install", - help="Install project dependencies from pyproject.toml / requirements.txt", - ) - install_parser.add_argument( - "--production", - action="store_true", - help="Skip development dependencies (optional extras and requirements-dev.txt)", - ) - - # validate command - subparsers.add_parser( - "validate", - help="Lint project config, @mcp_app imports, and @module() class references", + parser, gen_parser = build_parser( + _add_port_flags=_add_port_flags, OFFICIAL_TEMPLATES=OFFICIAL_TEMPLATES, ) args = parser.parse_args() @@ -1129,5 +323,6 @@ def _run_command(fn, *fn_args, **fn_kwargs): if any(issue.severity == "error" for issue in issues): sys.exit(1) + if __name__ == "__main__": main() From 217a621732afb9694a93d86ecab5f27f74357ed2 Mon Sep 17 00:00:00 2001 From: Siddharth Date: Fri, 6 Nov 2026 23:36:17 +0530 Subject: [PATCH 111/146] refactor(examples): split flight booking into cohesive local modules --- examples/flight_booking/__init__.py | 1 + examples/flight_booking/application.py | 46 ++ examples/flight_booking/definitions.py | 64 +++ examples/flight_booking/guards.py | 17 + examples/flight_booking/models.py | 42 ++ examples/flight_booking/service.py | 257 +++++++++++ examples/flight_booking/tools.py | 137 ++++++ examples/flight_booking_server.py | 579 ++----------------------- 8 files changed, 596 insertions(+), 547 deletions(-) create mode 100644 examples/flight_booking/__init__.py create mode 100644 examples/flight_booking/application.py create mode 100644 examples/flight_booking/definitions.py create mode 100644 examples/flight_booking/guards.py create mode 100644 examples/flight_booking/models.py create mode 100644 examples/flight_booking/service.py create mode 100644 examples/flight_booking/tools.py diff --git a/examples/flight_booking/__init__.py b/examples/flight_booking/__init__.py new file mode 100644 index 0000000..7f542a9 --- /dev/null +++ b/examples/flight_booking/__init__.py @@ -0,0 +1 @@ +"""Implementation of the standalone flight-booking example.""" diff --git a/examples/flight_booking/application.py b/examples/flight_booking/application.py new file mode 100644 index 0000000..7c1c8ec --- /dev/null +++ b/examples/flight_booking/application.py @@ -0,0 +1,46 @@ +"""Flight-booking example application.""" + +import os +from nitrostack import module, mcp_app, ServerConfig +from nitrostack.auth.oauth import OAuthModule +from .service import DuffelService +from .tools import FlightTools, BookingTools +from .definitions import FlightPrompts, FlightResources, SystemHealthCheck + + +@module( + name="flights", + controllers=[FlightTools, BookingTools, FlightPrompts, FlightResources], + providers=[DuffelService], + exports=[DuffelService] +) +class FlightsModule: + pass + + +@module( + name="app", + imports=[ + # Configure OAuth resource protection + OAuthModule.for_root( + resource_uri="https://mcplocal", + authorization_servers=["https://dev-5dt0utuk315713tjm.us.auth0.com"], + scopes_supported=["read", "write", "admin"], + token_introspection_endpoint=os.environ.get("INTROSPECTION_ENDPOINT") + ), + FlightsModule + ], + controllers=[], + providers=[SystemHealthCheck], + exports=[] +) +class AppModule: + pass + + +@mcp_app( + module=AppModule, + server=ServerConfig(name="airline-ticketing-server", version="1.0.0") +) +class App: + pass diff --git a/examples/flight_booking/definitions.py b/examples/flight_booking/definitions.py new file mode 100644 index 0000000..c6a37e3 --- /dev/null +++ b/examples/flight_booking/definitions.py @@ -0,0 +1,64 @@ +"""Flight-booking example definitions.""" + +import time +from nitrostack import prompt, resource, injectable, ExecutionContext, health_check +from .service import DuffelService + + +@injectable(deps=[DuffelService]) +class FlightPrompts: + def __init__(self, service: DuffelService): + self.service = service + + @prompt( + name="flight_search_assistant", + description="An AI assistant specialized in helping users search for flights and make booking decisions." + ) + async def flight_search_assistant(self, args: dict, context: ExecutionContext) -> str: + return "You are a professional flight booking assistant. Help the user search for flights using search_flights, search_airports, and assist in booking holds." + + @prompt( + name="flight_comparison", + description="Compare multiple flight offers and provide recommendations." + ) + async def flight_comparison(self, args: dict, context: ExecutionContext) -> str: + return "Compare the provided flight offer details, check layover times, durations, and pricing, and give the user a summary of best options." + + +@injectable(deps=[DuffelService]) +class FlightResources: + def __init__(self, service: DuffelService): + self.service = service + + @resource( + uri="flight://popular-routes", + name="Popular Flight Routes", + description="Information about popular routes and pricing", + mime_type="application/json" + ) + async def popular_routes(self, context: ExecutionContext) -> dict: + return { + "routes": [ + {"route": "JFK -> LAX", "price": "$200-400"}, + {"route": "LHR -> JFK", "price": "$400-800"} + ] + } + + @resource( + uri="flight://booking-guide", + name="Flight Booking Guide", + description="Guide on searching and booking flights", + mime_type="text/markdown" + ) + async def booking_guide(self, context: ExecutionContext) -> str: + return "# Flight Booking Guide\n\n1. Search flights.\n2. Collect passenger info.\n3. Create order hold." + + +class SystemHealthCheck: + def __init__(self): + self.start_time = time.time() + + @health_check("system") + def check_system(self) -> bool: + uptime = time.time() - self.start_time + return uptime >= 0 diff --git a/examples/flight_booking/guards.py b/examples/flight_booking/guards.py new file mode 100644 index 0000000..9da72b5 --- /dev/null +++ b/examples/flight_booking/guards.py @@ -0,0 +1,17 @@ +"""Flight-booking example guards.""" + +from nitrostack import ExecutionContext + + +def create_scope_guard(required_scopes: list): + class ScopeGuard: + async def can_activate(self, context: ExecutionContext) -> bool: + user_scopes = getattr(context.auth, "scopes", []) + missing_scopes = [s for s in required_scopes if s not in user_scopes] + if missing_scopes: + raise ValueError( + f"Insufficient scope. Required: {', '.join(required_scopes)}. " + f"Missing: {', '.join(missing_scopes)}" + ) + return True + return ScopeGuard diff --git a/examples/flight_booking/models.py b/examples/flight_booking/models.py new file mode 100644 index 0000000..5b63a74 --- /dev/null +++ b/examples/flight_booking/models.py @@ -0,0 +1,42 @@ +"""Flight-booking example models.""" + +from typing import Optional +from pydantic import BaseModel, Field + + +class SearchFlightsInput(BaseModel): + origin: str = Field(description="Origin airport IATA code (e.g., 'JFK', 'LHR')") + destination: str = Field(description="Destination airport IATA code (e.g., 'LAX', 'CDG')") + departureDate: str = Field(description="Departure date in YYYY-MM-DD format") + returnDate: Optional[str] = Field(default=None, description="Return date in YYYY-MM-DD format for round trip") + adults: int = Field(default=1, description="Number of adult passengers (18+)") + cabinClass: str = Field(default="economy", description="Preferred cabin class (economy, premium_economy, business, first)") + + +class FlightDetailsInput(BaseModel): + offerId: str = Field(description="The flight offer ID from search results") + + +class AirportSearchInput(BaseModel): + query: str = Field(description="The search query for airports (e.g., 'London', 'New York')") + + +class CreateOrderInput(BaseModel): + offerId: str = Field(description="The offer ID to book") + passengers: str = Field(description="JSON string containing array of passenger objects. Each passenger must have: title (mr/ms/mrs/miss/dr), givenName (first name), familyName (last name), gender (M/F), bornOn (YYYY-MM-DD), email, phoneNumber.") + + +class OrderDetailsInput(BaseModel): + orderId: str = Field(description="The order ID") + + +class SeatMapInput(BaseModel): + offerId: str = Field(description="The offer ID to get seats for") + + +class CancelOrderInput(BaseModel): + orderId: str = Field(description="The order ID to cancel") + + +class GetAirlinesInput(BaseModel): + pass diff --git a/examples/flight_booking/service.py b/examples/flight_booking/service.py new file mode 100644 index 0000000..ec0c761 --- /dev/null +++ b/examples/flight_booking/service.py @@ -0,0 +1,257 @@ +"""Flight-booking example service.""" + +import os +import sys +import json +import urllib.request +import urllib.parse +from typing import Dict, Any, List, Optional +from nitrostack import injectable + + +@injectable() +class DuffelService: + def __init__(self): + self.api_key = os.environ.get("DUFFEL_API_KEY") + self.is_mock = not self.api_key or self.api_key.startswith("your-") or len(self.api_key) < 5 + + def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + if self.is_mock: + raise ValueError("Duffel API key is not configured. Running in mock mode.") + + headers = { + "Authorization": f"Bearer {self.api_key}", + "Duffel-Version": "v1", + "Content-Type": "application/json" + } + url = f"https://api.duffel.com{path}" + req_data = json.dumps({"data": data}).encode("utf-8") if data else None + + req = urllib.request.Request(url, data=req_data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=10) as response: + res_payload = json.loads(response.read().decode("utf-8")) + return res_payload.get("data", {}) + except Exception as e: + sys.stderr.write(f"Duffel API Request failed: {e}\n") + sys.stderr.flush() + raise e + + async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]: + if self.is_mock: + return { + "id": "orq_mock123456", + "offers": [ + { + "id": "off_mock123456", + "total_amount": "450.00", + "total_currency": "USD", + "expires_at": "2026-12-31T12:00:00Z", + "slices": [ + { + "origin": {"iata_code": params["origin"], "name": "Origin Airport", "city_name": "Origin City"}, + "destination": {"iata_code": params["destination"], "name": "Dest Airport", "city_name": "Dest City"}, + "duration": "PT6H30M", + "segments": [ + { + "id": "seg_outbound", + "origin": {"iata_code": params["origin"]}, + "destination": {"iata_code": params["destination"]}, + "departing_at": f"{params['departureDate']}T08:00:00Z", + "arriving_at": f"{params['departureDate']}T14:30:00Z", + "marketing_carrier": {"name": "Mock Airlines"}, + "marketing_carrier_flight_number": "MK123", + "aircraft": {"name": "Boeing 787"} + } + ] + } + ] + } + ] + } + + slices = [{"origin": params["origin"], "destination": params["destination"], "departure_date": params["departureDate"]}] + if params.get("returnDate"): + slices.append({"origin": params["destination"], "destination": params["origin"], "departure_date": params["returnDate"]}) + + duffel_params = { + "slices": slices, + "passengers": params.get("passengers", [{"type": "adult"}]), + "cabin_class": params.get("cabinClass", "economy"), + "return_offers": True + } + res = self._request("POST", "/offer_requests", duffel_params) + return { + "id": res.get("id"), + "offers": res.get("offers", []), + "passengers": res.get("passengers", []), + "slices": res.get("slices", []) + } + + async def get_offer(self, offer_id: str) -> Dict[str, Any]: + if self.is_mock: + return { + "id": offer_id, + "total_amount": "450.00", + "total_currency": "USD", + "expires_at": "2026-12-31T12:00:00Z", + "slices": [ + { + "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"}, + "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"}, + "duration": "PT6H30M", + "segments": [ + { + "id": "seg_mock", + "origin": {"iata_code": "JFK"}, + "destination": {"iata_code": "LAX"}, + "departing_at": "2026-07-15T08:00:00Z", + "arriving_at": "2026-07-15T14:30:00Z", + "marketing_carrier": {"name": "Mock Airlines"}, + "marketing_carrier_flight_number": "MK123", + "aircraft": {"name": "Boeing 787"} + } + ] + } + ] + } + return self._request("GET", f"/offers/{offer_id}") + + async def get_seats_for_offer(self, offer_id: str) -> List[Dict[str, Any]]: + if self.is_mock: + return [ + { + "cabin_class": "economy", + "rows": [ + { + "row_number": 10, + "sections": [ + { + "elements": [ + { + "type": "seat", + "id": "seat_10a", + "designator": "10A", + "available_services": [{"total_amount": "25.00", "total_currency": "USD"}], + "disclosures": ["window"] + }, + { + "type": "seat", + "id": "seat_10b", + "designator": "10B", + "available_services": [{"total_amount": "0.00", "total_currency": "USD"}], + "disclosures": ["middle"] + } + ] + } + ] + } + ] + } + ] + res = self._request("GET", f"/seat_maps?offer_id={offer_id}") + return res if isinstance(res, list) else [] + + async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]: + if self.is_mock: + return { + "id": "ord_mock123456", + "status": "held", + "total_amount": "450.00", + "total_currency": "USD", + "expires_at": "2026-12-31T12:00:00Z", + "booking_reference": "ABCXYZ", + "passengers": [ + { + "id": f"pax_{idx}", + "given_name": p["given_name"], + "family_name": p["family_name"], + "type": "adult" + } for idx, p in enumerate(params["passengers"]) + ], + "slices": [ + { + "origin": {"iata_code": "JFK"}, + "destination": {"iata_code": "LAX"}, + "duration": "PT6H30M", + "segments": [ + { + "departing_at": "2026-07-15T08:00:00Z", + "arriving_at": "2026-07-15T14:30:00Z" + } + ] + } + ] + } + + order_payload = { + "selected_offers": params["selectedOffers"], + "passengers": params["passengers"], + "type": "hold" + } + return self._request("POST", "/orders", order_payload) + + async def get_order(self, order_id: str) -> Dict[str, Any]: + if self.is_mock: + return { + "id": order_id, + "status": "held", + "total_amount": "450.00", + "total_currency": "USD", + "booking_reference": "ABCXYZ", + "created_at": "2026-06-25T12:00:00Z", + "expires_at": "2026-12-31T12:00:00Z", + "passengers": [ + { + "id": "pax_0", + "given_name": "John", + "family_name": "Doe", + "type": "adult", + "email": "john@example.com", + "phone_number": "+1234567890" + } + ], + "slices": [ + { + "id": "sli_mock", + "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"}, + "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"}, + "duration": "PT6H30M", + "segments": [ + { + "id": "seg_mock", + "origin": {"iata_code": "JFK"}, + "destination": {"iata_code": "LAX"}, + "departing_at": "2026-07-15T08:00:00Z", + "arriving_at": "2026-07-15T14:30:00Z", + "marketing_carrier": {"name": "Mock Airlines"}, + "marketing_carrier_flight_number": "MK123", + "aircraft": {"name": "Boeing 787"} + } + ] + } + ] + } + return self._request("GET", f"/orders/{order_id}") + + async def cancel_order(self, order_id: str) -> Dict[str, Any]: + if self.is_mock: + return { + "id": "ocr_mock123456", + "refund_amount": "450.00", + "refund_currency": "USD", + "confirmed_at": "2026-06-25T12:30:00Z" + } + cancel_payload = {"order_id": order_id} + return self._request("POST", "/order_cancellations", cancel_payload) + + async def get_airlines(self) -> List[Dict[str, Any]]: + if self.is_mock: + return [ + {"iata_code": "AA", "name": "American Airlines"}, + {"iata_code": "DL", "name": "Delta Air Lines"}, + {"iata_code": "UA", "name": "United Airlines"}, + {"iata_code": "BA", "name": "British Airways"} + ] + res = self._request("GET", "/airlines") + return res if isinstance(res, list) else [] diff --git a/examples/flight_booking/tools.py b/examples/flight_booking/tools.py new file mode 100644 index 0000000..3e49878 --- /dev/null +++ b/examples/flight_booking/tools.py @@ -0,0 +1,137 @@ +"""Flight-booking example tools.""" + +import json +from nitrostack import tool, injectable, ExecutionContext, use_guards, widget, OAuthGuard +from .models import SearchFlightsInput, FlightDetailsInput, AirportSearchInput, CreateOrderInput, OrderDetailsInput, SeatMapInput, CancelOrderInput, GetAirlinesInput +from .guards import create_scope_guard +from .service import DuffelService + + +@injectable(deps=[DuffelService]) +class FlightTools: + def __init__(self, service: DuffelService): + self.service = service + + @tool( + name="search_flights", + title="Search Flights", + description="Search for flight offers based on origin, destination, dates, and preferences.", + input_schema=SearchFlightsInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + @widget("flight-search-results") + async def search_flights(self, input: SearchFlightsInput, context: ExecutionContext) -> dict: + context.logger.info(f"Searching flights from {input.origin} to {input.destination}") + return await self.service.search_flights(input.model_dump()) + + @tool( + name="get_flight_details", + title="Get Flight Details", + description="Get detailed information about a specific flight offer including baggage allowance, conditions.", + input_schema=FlightDetailsInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + @widget("flight-details") + async def get_flight_details(self, input: FlightDetailsInput, context: ExecutionContext) -> dict: + context.logger.info(f"Fetching flight details for offer {input.offerId}") + return await self.service.get_offer(input.offerId) + + @tool( + name="search_airports", + title="Search Airports", + description="Search for airports by query string.", + input_schema=AirportSearchInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + @widget("airport-search") + async def search_airports(self, input: AirportSearchInput, context: ExecutionContext) -> dict: + context.logger.info(f"Searching airports for query: {input.query}") + return {"airports": [{"iataCode": "JFK", "name": "John F. Kennedy Airport"}]} + + @tool( + name="get_airlines", + title="Get Airlines", + description="Get list of common airlines.", + input_schema=GetAirlinesInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + async def get_airlines(self, input: GetAirlinesInput, context: ExecutionContext) -> dict: + context.logger.info("Fetching common airlines") + res = await self.service.get_airlines() + return {"airlines": res} + + +@injectable(deps=[DuffelService]) +class BookingTools: + def __init__(self, service: DuffelService): + self.service = service + + @tool( + name="create_order", + title="Create Order", + description="Create a flight order with hold (no payment required). Collect passenger details first.", + input_schema=CreateOrderInput + ) + @use_guards(OAuthGuard, create_scope_guard(["write"])) + @widget("order-summary") + async def create_order(self, input: CreateOrderInput, context: ExecutionContext) -> dict: + context.logger.info(f"Creating flight order for offer {input.offerId}") + try: + passengers_array = json.loads(input.passengers) + except Exception: + raise ValueError("Invalid passengers JSON format") + + passengers = [] + for p in passengers_array: + passengers.append({ + "title": p.get("title", "mr"), + "given_name": p.get("givenName"), + "family_name": p.get("familyName"), + "gender": p.get("gender", "M"), + "born_on": p.get("bornOn"), + "email": p.get("email"), + "phone_number": p.get("phoneNumber") + }) + + order_params = { + "selectedOffers": [input.offerId], + "passengers": passengers + } + return await self.service.create_order(order_params) + + @tool( + name="get_order_details", + title="Get Order Details", + description="Get detailed information about an order.", + input_schema=OrderDetailsInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + @widget("order-summary") + async def get_order_details(self, input: OrderDetailsInput, context: ExecutionContext) -> dict: + context.logger.info(f"Fetching details for order {input.orderId}") + return await self.service.get_order(input.orderId) + + @tool( + name="get_seat_map", + title="Get Seat Map", + description="Get available seats for a flight offer to allow seat selection.", + input_schema=SeatMapInput + ) + @use_guards(OAuthGuard, create_scope_guard(["read"])) + @widget("seat-selection") + async def get_seat_map(self, input: SeatMapInput, context: ExecutionContext) -> dict: + context.logger.info(f"Fetching seat map for offer {input.offerId}") + res = await self.service.get_seats_for_offer(input.offerId) + return {"offerId": input.offerId, "cabins": res} + + @tool( + name="cancel_order", + title="Cancel Order", + description="Cancel a flight order and request refund if applicable.", + input_schema=CancelOrderInput + ) + @use_guards(OAuthGuard, create_scope_guard(["write"])) + @widget("order-cancellation") + async def cancel_order(self, input: CancelOrderInput, context: ExecutionContext) -> dict: + context.logger.info(f"Cancelling order {input.orderId}") + return await self.service.cancel_order(input.orderId) diff --git a/examples/flight_booking_server.py b/examples/flight_booking_server.py index bc6b74e..18d35f8 100644 --- a/examples/flight_booking_server.py +++ b/examples/flight_booking_server.py @@ -14,563 +14,47 @@ # # TOKEN_AUDIENCE=https://mcplocal # # TOKEN_ISSUER=https://dev-5dt0utuk315713tjm.us.auth0.com +import asyncio + import asyncio import os import sys -import json -import uuid -import time -import urllib.request -import urllib.parse -from typing import Dict, Any, List, Optional -from pydantic import BaseModel, Field -# Ensure parent directory is in sys.path so nitrostack can be imported +# Keep direct execution working outside the repository working directory. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) -from nitrostack import ( - tool, - prompt, - resource, - injectable, - module, - mcp_app, - McpApplicationFactory, - ServerConfig, - ExecutionContext, - use_guards, - widget, - OAuthGuard, - health_check, +from nitrostack import McpApplicationFactory +from examples.flight_booking.models import ( + SearchFlightsInput, + FlightDetailsInput, + AirportSearchInput, + CreateOrderInput, + OrderDetailsInput, + SeatMapInput, + CancelOrderInput, + GetAirlinesInput, ) -from nitrostack.auth.oauth import OAuthModule - -# 1. Custom Scope Guard Factory -def create_scope_guard(required_scopes: list): - class ScopeGuard: - async def can_activate(self, context: ExecutionContext) -> bool: - user_scopes = getattr(context.auth, "scopes", []) - missing_scopes = [s for s in required_scopes if s not in user_scopes] - if missing_scopes: - raise ValueError( - f"Insufficient scope. Required: {', '.join(required_scopes)}. " - f"Missing: {', '.join(missing_scopes)}" - ) - return True - return ScopeGuard - -# 2. Input Validation Schemas -class SearchFlightsInput(BaseModel): - origin: str = Field(description="Origin airport IATA code (e.g., 'JFK', 'LHR')") - destination: str = Field(description="Destination airport IATA code (e.g., 'LAX', 'CDG')") - departureDate: str = Field(description="Departure date in YYYY-MM-DD format") - returnDate: Optional[str] = Field(default=None, description="Return date in YYYY-MM-DD format for round trip") - adults: int = Field(default=1, description="Number of adult passengers (18+)") - cabinClass: str = Field(default="economy", description="Preferred cabin class (economy, premium_economy, business, first)") - -class FlightDetailsInput(BaseModel): - offerId: str = Field(description="The flight offer ID from search results") - -class AirportSearchInput(BaseModel): - query: str = Field(description="The search query for airports (e.g., 'London', 'New York')") - -class CreateOrderInput(BaseModel): - offerId: str = Field(description="The offer ID to book") - passengers: str = Field(description="JSON string containing array of passenger objects. Each passenger must have: title (mr/ms/mrs/miss/dr), givenName (first name), familyName (last name), gender (M/F), bornOn (YYYY-MM-DD), email, phoneNumber.") - -class OrderDetailsInput(BaseModel): - orderId: str = Field(description="The order ID") - -class SeatMapInput(BaseModel): - offerId: str = Field(description="The offer ID to get seats for") - -class CancelOrderInput(BaseModel): - orderId: str = Field(description="The order ID to cancel") - -class GetAirlinesInput(BaseModel): - pass - - - -# 3. Duffel Flight API Service -@injectable() -class DuffelService: - def __init__(self): - self.api_key = os.environ.get("DUFFEL_API_KEY") - self.is_mock = not self.api_key or self.api_key.startswith("your-") or len(self.api_key) < 5 - - def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: - if self.is_mock: - raise ValueError("Duffel API key is not configured. Running in mock mode.") - - headers = { - "Authorization": f"Bearer {self.api_key}", - "Duffel-Version": "v1", - "Content-Type": "application/json" - } - url = f"https://api.duffel.com{path}" - req_data = json.dumps({"data": data}).encode("utf-8") if data else None - - req = urllib.request.Request(url, data=req_data, headers=headers, method=method) - try: - with urllib.request.urlopen(req, timeout=10) as response: - res_payload = json.loads(response.read().decode("utf-8")) - return res_payload.get("data", {}) - except Exception as e: - sys.stderr.write(f"Duffel API Request failed: {e}\n") - sys.stderr.flush() - raise e - - async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]: - if self.is_mock: - return { - "id": "orq_mock123456", - "offers": [ - { - "id": "off_mock123456", - "total_amount": "450.00", - "total_currency": "USD", - "expires_at": "2026-12-31T12:00:00Z", - "slices": [ - { - "origin": {"iata_code": params["origin"], "name": "Origin Airport", "city_name": "Origin City"}, - "destination": {"iata_code": params["destination"], "name": "Dest Airport", "city_name": "Dest City"}, - "duration": "PT6H30M", - "segments": [ - { - "id": "seg_outbound", - "origin": {"iata_code": params["origin"]}, - "destination": {"iata_code": params["destination"]}, - "departing_at": f"{params['departureDate']}T08:00:00Z", - "arriving_at": f"{params['departureDate']}T14:30:00Z", - "marketing_carrier": {"name": "Mock Airlines"}, - "marketing_carrier_flight_number": "MK123", - "aircraft": {"name": "Boeing 787"} - } - ] - } - ] - } - ] - } - - slices = [{"origin": params["origin"], "destination": params["destination"], "departure_date": params["departureDate"]}] - if params.get("returnDate"): - slices.append({"origin": params["destination"], "destination": params["origin"], "departure_date": params["returnDate"]}) - - duffel_params = { - "slices": slices, - "passengers": params.get("passengers", [{"type": "adult"}]), - "cabin_class": params.get("cabinClass", "economy"), - "return_offers": True - } - res = self._request("POST", "/offer_requests", duffel_params) - return { - "id": res.get("id"), - "offers": res.get("offers", []), - "passengers": res.get("passengers", []), - "slices": res.get("slices", []) - } - - async def get_offer(self, offer_id: str) -> Dict[str, Any]: - if self.is_mock: - return { - "id": offer_id, - "total_amount": "450.00", - "total_currency": "USD", - "expires_at": "2026-12-31T12:00:00Z", - "slices": [ - { - "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"}, - "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"}, - "duration": "PT6H30M", - "segments": [ - { - "id": "seg_mock", - "origin": {"iata_code": "JFK"}, - "destination": {"iata_code": "LAX"}, - "departing_at": "2026-07-15T08:00:00Z", - "arriving_at": "2026-07-15T14:30:00Z", - "marketing_carrier": {"name": "Mock Airlines"}, - "marketing_carrier_flight_number": "MK123", - "aircraft": {"name": "Boeing 787"} - } - ] - } - ] - } - return self._request("GET", f"/offers/{offer_id}") - - async def get_seats_for_offer(self, offer_id: str) -> List[Dict[str, Any]]: - if self.is_mock: - return [ - { - "cabin_class": "economy", - "rows": [ - { - "row_number": 10, - "sections": [ - { - "elements": [ - { - "type": "seat", - "id": "seat_10a", - "designator": "10A", - "available_services": [{"total_amount": "25.00", "total_currency": "USD"}], - "disclosures": ["window"] - }, - { - "type": "seat", - "id": "seat_10b", - "designator": "10B", - "available_services": [{"total_amount": "0.00", "total_currency": "USD"}], - "disclosures": ["middle"] - } - ] - } - ] - } - ] - } - ] - res = self._request("GET", f"/seat_maps?offer_id={offer_id}") - return res if isinstance(res, list) else [] - - async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]: - if self.is_mock: - return { - "id": "ord_mock123456", - "status": "held", - "total_amount": "450.00", - "total_currency": "USD", - "expires_at": "2026-12-31T12:00:00Z", - "booking_reference": "ABCXYZ", - "passengers": [ - { - "id": f"pax_{idx}", - "given_name": p["given_name"], - "family_name": p["family_name"], - "type": "adult" - } for idx, p in enumerate(params["passengers"]) - ], - "slices": [ - { - "origin": {"iata_code": "JFK"}, - "destination": {"iata_code": "LAX"}, - "duration": "PT6H30M", - "segments": [ - { - "departing_at": "2026-07-15T08:00:00Z", - "arriving_at": "2026-07-15T14:30:00Z" - } - ] - } - ] - } - - order_payload = { - "selected_offers": params["selectedOffers"], - "passengers": params["passengers"], - "type": "hold" - } - return self._request("POST", "/orders", order_payload) - - async def get_order(self, order_id: str) -> Dict[str, Any]: - if self.is_mock: - return { - "id": order_id, - "status": "held", - "total_amount": "450.00", - "total_currency": "USD", - "booking_reference": "ABCXYZ", - "created_at": "2026-06-25T12:00:00Z", - "expires_at": "2026-12-31T12:00:00Z", - "passengers": [ - { - "id": "pax_0", - "given_name": "John", - "family_name": "Doe", - "type": "adult", - "email": "john@example.com", - "phone_number": "+1234567890" - } - ], - "slices": [ - { - "id": "sli_mock", - "origin": {"iata_code": "JFK", "name": "John F. Kennedy Airport", "city_name": "New York"}, - "destination": {"iata_code": "LAX", "name": "Los Angeles Airport", "city_name": "Los Angeles"}, - "duration": "PT6H30M", - "segments": [ - { - "id": "seg_mock", - "origin": {"iata_code": "JFK"}, - "destination": {"iata_code": "LAX"}, - "departing_at": "2026-07-15T08:00:00Z", - "arriving_at": "2026-07-15T14:30:00Z", - "marketing_carrier": {"name": "Mock Airlines"}, - "marketing_carrier_flight_number": "MK123", - "aircraft": {"name": "Boeing 787"} - } - ] - } - ] - } - return self._request("GET", f"/orders/{order_id}") - - async def cancel_order(self, order_id: str) -> Dict[str, Any]: - if self.is_mock: - return { - "id": "ocr_mock123456", - "refund_amount": "450.00", - "refund_currency": "USD", - "confirmed_at": "2026-06-25T12:30:00Z" - } - cancel_payload = {"order_id": order_id} - return self._request("POST", "/order_cancellations", cancel_payload) - - async def get_airlines(self) -> List[Dict[str, Any]]: - if self.is_mock: - return [ - {"iata_code": "AA", "name": "American Airlines"}, - {"iata_code": "DL", "name": "Delta Air Lines"}, - {"iata_code": "UA", "name": "United Airlines"}, - {"iata_code": "BA", "name": "British Airways"} - ] - res = self._request("GET", "/airlines") - return res if isinstance(res, list) else [] - - -# 4. Controllers Exposing Tools -@injectable(deps=[DuffelService]) -class FlightTools: - def __init__(self, service: DuffelService): - self.service = service - - @tool( - name="search_flights", - title="Search Flights", - description="Search for flight offers based on origin, destination, dates, and preferences.", - input_schema=SearchFlightsInput - ) - @use_guards(OAuthGuard, create_scope_guard(["read"])) - @widget("flight-search-results") - async def search_flights(self, input: SearchFlightsInput, context: ExecutionContext) -> dict: - context.logger.info(f"Searching flights from {input.origin} to {input.destination}") - return await self.service.search_flights(input.model_dump()) - - @tool( - name="get_flight_details", - title="Get Flight Details", - description="Get detailed information about a specific flight offer including baggage allowance, conditions.", - input_schema=FlightDetailsInput - ) - @use_guards(OAuthGuard, create_scope_guard(["read"])) - @widget("flight-details") - async def get_flight_details(self, input: FlightDetailsInput, context: ExecutionContext) -> dict: - context.logger.info(f"Fetching flight details for offer {input.offerId}") - return await self.service.get_offer(input.offerId) - - @tool( - name="search_airports", - title="Search Airports", - description="Search for airports by query string.", - input_schema=AirportSearchInput - ) - @use_guards(OAuthGuard, create_scope_guard(["read"])) - @widget("airport-search") - async def search_airports(self, input: AirportSearchInput, context: ExecutionContext) -> dict: - context.logger.info(f"Searching airports for query: {input.query}") - return {"airports": [{"iataCode": "JFK", "name": "John F. Kennedy Airport"}]} - - @tool( - name="get_airlines", - title="Get Airlines", - description="Get list of common airlines.", - input_schema=GetAirlinesInput - ) - @use_guards(OAuthGuard, create_scope_guard(["read"])) - async def get_airlines(self, input: GetAirlinesInput, context: ExecutionContext) -> dict: - context.logger.info("Fetching common airlines") - res = await self.service.get_airlines() - return {"airlines": res} - - -@injectable(deps=[DuffelService]) -class BookingTools: - def __init__(self, service: DuffelService): - self.service = service - - @tool( - name="create_order", - title="Create Order", - description="Create a flight order with hold (no payment required). Collect passenger details first.", - input_schema=CreateOrderInput - ) - @use_guards(OAuthGuard, create_scope_guard(["write"])) - @widget("order-summary") - async def create_order(self, input: CreateOrderInput, context: ExecutionContext) -> dict: - context.logger.info(f"Creating flight order for offer {input.offerId}") - try: - passengers_array = json.loads(input.passengers) - except Exception: - raise ValueError("Invalid passengers JSON format") - - passengers = [] - for p in passengers_array: - passengers.append({ - "title": p.get("title", "mr"), - "given_name": p.get("givenName"), - "family_name": p.get("familyName"), - "gender": p.get("gender", "M"), - "born_on": p.get("bornOn"), - "email": p.get("email"), - "phone_number": p.get("phoneNumber") - }) - - order_params = { - "selectedOffers": [input.offerId], - "passengers": passengers - } - return await self.service.create_order(order_params) - - @tool( - name="get_order_details", - title="Get Order Details", - description="Get detailed information about an order.", - input_schema=OrderDetailsInput - ) - @use_guards(OAuthGuard, create_scope_guard(["read"])) - @widget("order-summary") - async def get_order_details(self, input: OrderDetailsInput, context: ExecutionContext) -> dict: - context.logger.info(f"Fetching details for order {input.orderId}") - return await self.service.get_order(input.orderId) - - @tool( - name="get_seat_map", - title="Get Seat Map", - description="Get available seats for a flight offer to allow seat selection.", - input_schema=SeatMapInput - ) - @use_guards(OAuthGuard, create_scope_guard(["read"])) - @widget("seat-selection") - async def get_seat_map(self, input: SeatMapInput, context: ExecutionContext) -> dict: - context.logger.info(f"Fetching seat map for offer {input.offerId}") - res = await self.service.get_seats_for_offer(input.offerId) - return {"offerId": input.offerId, "cabins": res} - - @tool( - name="cancel_order", - title="Cancel Order", - description="Cancel a flight order and request refund if applicable.", - input_schema=CancelOrderInput - ) - @use_guards(OAuthGuard, create_scope_guard(["write"])) - @widget("order-cancellation") - async def cancel_order(self, input: CancelOrderInput, context: ExecutionContext) -> dict: - context.logger.info(f"Cancelling order {input.orderId}") - return await self.service.cancel_order(input.orderId) - - -# 5. Flight Prompts -@injectable(deps=[DuffelService]) -class FlightPrompts: - def __init__(self, service: DuffelService): - self.service = service - - @prompt( - name="flight_search_assistant", - description="An AI assistant specialized in helping users search for flights and make booking decisions." - ) - async def flight_search_assistant(self, args: dict, context: ExecutionContext) -> str: - return "You are a professional flight booking assistant. Help the user search for flights using search_flights, search_airports, and assist in booking holds." - - @prompt( - name="flight_comparison", - description="Compare multiple flight offers and provide recommendations." - ) - async def flight_comparison(self, args: dict, context: ExecutionContext) -> str: - return "Compare the provided flight offer details, check layover times, durations, and pricing, and give the user a summary of best options." - - -# 6. Flight Resources -@injectable(deps=[DuffelService]) -class FlightResources: - def __init__(self, service: DuffelService): - self.service = service - - @resource( - uri="flight://popular-routes", - name="Popular Flight Routes", - description="Information about popular routes and pricing", - mime_type="application/json" - ) - async def popular_routes(self, context: ExecutionContext) -> dict: - return { - "routes": [ - {"route": "JFK -> LAX", "price": "$200-400"}, - {"route": "LHR -> JFK", "price": "$400-800"} - ] - } - - @resource( - uri="flight://booking-guide", - name="Flight Booking Guide", - description="Guide on searching and booking flights", - mime_type="text/markdown" - ) - async def booking_guide(self, context: ExecutionContext) -> str: - return "# Flight Booking Guide\n\n1. Search flights.\n2. Collect passenger info.\n3. Create order hold." - - -# 7. Health Check -class SystemHealthCheck: - def __init__(self): - self.start_time = time.time() - - @health_check("system") - def check_system(self) -> bool: - uptime = time.time() - self.start_time - return uptime >= 0 - - -# 8. Modules -@module( - name="flights", - controllers=[FlightTools, BookingTools, FlightPrompts, FlightResources], - providers=[DuffelService], - exports=[DuffelService] +from examples.flight_booking.guards import ( + create_scope_guard, ) -class FlightsModule: - pass - -@module( - name="app", - imports=[ - # Configure OAuth resource protection - OAuthModule.for_root( - resource_uri="https://mcplocal", - authorization_servers=["https://dev-5dt0utuk315713tjm.us.auth0.com"], - scopes_supported=["read", "write", "admin"], - token_introspection_endpoint=os.environ.get("INTROSPECTION_ENDPOINT") - ), - FlightsModule - ], - controllers=[], - providers=[SystemHealthCheck], - exports=[] +from examples.flight_booking.service import ( + DuffelService, ) -class AppModule: - pass - - -# 9. Application Entrypoint -@mcp_app( - module=AppModule, - server=ServerConfig(name="airline-ticketing-server", version="1.0.0") +from examples.flight_booking.tools import ( + FlightTools, + BookingTools, +) +from examples.flight_booking.definitions import ( + FlightPrompts, + FlightResources, + SystemHealthCheck, ) -class App: - pass +from examples.flight_booking.application import ( + FlightsModule, + AppModule, + App, +) + async def main(): sys.stderr.write("🔐 Starting Airline Ticketing MCP Server with OAuth 2.1...\n") @@ -578,5 +62,6 @@ async def main(): app = await McpApplicationFactory.create(App) await app.start() + if __name__ == "__main__": asyncio.run(main()) From 7d22631d1a64f6e5005b266a2e86c4a769e5a648 Mon Sep 17 00:00:00 2001 From: Siddharth Date: Fri, 6 Nov 2026 23:36:58 +0530 Subject: [PATCH 112/146] style: remove whitespace inherited by extracted Python modules --- examples/flight_booking/service.py | 10 +++++----- examples/flight_booking/tools.py | 4 ++-- nitrostack/cli/_config.py | 1 - nitrostack/cli/_registration.py | 22 +++++++++++----------- nitrostack/cli/_servers.py | 10 +++++----- 5 files changed, 23 insertions(+), 24 deletions(-) diff --git a/examples/flight_booking/service.py b/examples/flight_booking/service.py index ec0c761..64433e9 100644 --- a/examples/flight_booking/service.py +++ b/examples/flight_booking/service.py @@ -18,7 +18,7 @@ def __init__(self): def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: if self.is_mock: raise ValueError("Duffel API key is not configured. Running in mock mode.") - + headers = { "Authorization": f"Bearer {self.api_key}", "Duffel-Version": "v1", @@ -26,7 +26,7 @@ def _request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None } url = f"https://api.duffel.com{path}" req_data = json.dumps({"data": data}).encode("utf-8") if data else None - + req = urllib.request.Request(url, data=req_data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=10) as response: @@ -69,11 +69,11 @@ async def search_flights(self, params: Dict[str, Any]) -> Dict[str, Any]: } ] } - + slices = [{"origin": params["origin"], "destination": params["destination"], "departure_date": params["departureDate"]}] if params.get("returnDate"): slices.append({"origin": params["destination"], "destination": params["origin"], "departure_date": params["returnDate"]}) - + duffel_params = { "slices": slices, "passengers": params.get("passengers", [{"type": "adult"}]), @@ -183,7 +183,7 @@ async def create_order(self, params: Dict[str, Any]) -> Dict[str, Any]: } ] } - + order_payload = { "selected_offers": params["selectedOffers"], "passengers": params["passengers"], diff --git a/examples/flight_booking/tools.py b/examples/flight_booking/tools.py index 3e49878..f15d343 100644 --- a/examples/flight_booking/tools.py +++ b/examples/flight_booking/tools.py @@ -80,7 +80,7 @@ async def create_order(self, input: CreateOrderInput, context: ExecutionContext) passengers_array = json.loads(input.passengers) except Exception: raise ValueError("Invalid passengers JSON format") - + passengers = [] for p in passengers_array: passengers.append({ @@ -92,7 +92,7 @@ async def create_order(self, input: CreateOrderInput, context: ExecutionContext) "email": p.get("email"), "phone_number": p.get("phoneNumber") }) - + order_params = { "selectedOffers": [input.offerId], "passengers": passengers diff --git a/nitrostack/cli/_config.py b/nitrostack/cli/_config.py index d4c8059..01bb257 100644 --- a/nitrostack/cli/_config.py +++ b/nitrostack/cli/_config.py @@ -13,4 +13,3 @@ "python-enterprise-search": "enterprise-search", "python-code-mode": "code-mode", } - diff --git a/nitrostack/cli/_registration.py b/nitrostack/cli/_registration.py index 229a7b9..08a21b4 100644 --- a/nitrostack/cli/_registration.py +++ b/nitrostack/cli/_registration.py @@ -7,7 +7,7 @@ def get_claude_config_paths(): paths = [] home = os.path.expanduser("~") - + # Windows if sys.platform == "win32": appdata = os.environ.get("APPDATA") @@ -30,24 +30,24 @@ def get_claude_config_paths(): # Linux else: paths.append(os.path.join(home, ".config", "Claude", "claude_desktop_config.json")) - + return [p for p in paths if os.path.exists(os.path.dirname(p))] def register_server(name: str, file_path: str, *, _build_server_entry, get_claude_config_paths): import json - + if not os.path.exists(file_path): print(f"Error: Script file '{file_path}' does not exist.") sys.exit(1) - + server_entry = _build_server_entry(file_path) - + config_paths = get_claude_config_paths() if not config_paths: print("Error: Could not find any Claude Desktop installation directories.") print("Please ensure Claude Desktop is installed on your machine.") sys.exit(1) - + registered_any = False for path in config_paths: try: @@ -60,22 +60,22 @@ def register_server(name: str, file_path: str, *, _build_server_entry, get_claud config = json.loads(content) except json.JSONDecodeError: print(f"Warning: Configuration file at '{path}' is not valid JSON. Resetting it.") - + if "mcpServers" not in config: config["mcpServers"] = {} - + config["mcpServers"][name] = server_entry - + # Create directory if needed os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8") as f: json.dump(config, f, indent=2) - + print(f"Successfully registered server '{name}' in: {path}") registered_any = True except Exception as e: print(f"Error writing to config at '{path}': {e}") - + if registered_any: print("\nAll done! Please fully restart Claude Desktop to load your new server.") else: diff --git a/nitrostack/cli/_servers.py b/nitrostack/cli/_servers.py index 97f1029..02d748f 100644 --- a/nitrostack/cli/_servers.py +++ b/nitrostack/cli/_servers.py @@ -65,9 +65,9 @@ def cleanup(): try: start_process() - + watched_extensions = {".py", ".env"} - + def get_mtimes(): mtimes = {} for root, dirs, files in os.walk("."): @@ -87,7 +87,7 @@ def get_mtimes(): try: from watchfiles import watch print("Using watchfiles for high-performance file monitoring.") - + while True: for changes in watch("."): should_restart = False @@ -101,11 +101,11 @@ def get_mtimes(): if should_restart: print("File changes detected! Restarting server...") start_process() - + time.sleep(0.5) if process and process.poll() is not None: print("Server process exited. Waiting for file changes to restart...") - + except ImportError: print("watchfiles library not found. Falling back to standard polling...") last_mtimes = get_mtimes() From b1f4dace8bfd2fdb98b61c805ab4f7bbe32988ab Mon Sep 17 00:00:00 2001 From: Siddharth Date: Sat, 7 Nov 2026 10:15:26 +0530 Subject: [PATCH 113/146] refactor(auth): split OAuth client types and follow-up tests --- docs/oauth-client-implementation.md | 7 +- nitrostack/auth/_client_types.py | 98 ++++++++++ nitrostack/auth/client.py | 99 +--------- tests/support/oauth_client.py | 39 ++++ tests/test_oauth_client.py | 265 +-------------------------- tests/test_oauth_client_followups.py | 242 ++++++++++++++++++++++++ 6 files changed, 393 insertions(+), 357 deletions(-) create mode 100644 nitrostack/auth/_client_types.py create mode 100644 tests/support/oauth_client.py create mode 100644 tests/test_oauth_client_followups.py diff --git a/docs/oauth-client-implementation.md b/docs/oauth-client-implementation.md index a3c6ce2..cab0cb4 100644 --- a/docs/oauth-client-implementation.md +++ b/docs/oauth-client-implementation.md @@ -66,9 +66,10 @@ multiple writer processes; Windows directory privacy depends on ACLs. ## Client configuration and transport -`auth/client.py` defines typed, redacted config, authorization-flow and -registration results. Constructor mappings use the same snake_case names as the -config model. The client creates a memory store unless the caller supplies one. +`auth/_client_types.py` defines typed, redacted config, authorization-flow and +registration results. `auth/client.py` owns the client lifecycle and transport, +and re-exports these types to preserve existing imports. Constructor mappings +use the same snake_case names as the config model. The client creates a memory store unless the caller supplies one. Request timeout and response limits are validated once at construction. Client secrets can remain wrapped in `SecretValue` until authentication calls `unwrap_secret()`; empty or unusable wrappers produce sanitized errors. diff --git a/nitrostack/auth/_client_types.py b/nitrostack/auth/_client_types.py new file mode 100644 index 0000000..19daa5e --- /dev/null +++ b/nitrostack/auth/_client_types.py @@ -0,0 +1,98 @@ +"""Secret-safe OAuth configuration, results, errors, and transport records.""" + +from __future__ import annotations + +from dataclasses import dataclass, field, fields +from types import MappingProxyType +from typing import Any, Mapping + +from nitrostack.auth.secret import SecretValue + + +_OAUTH_ERRORS = frozenset({ + "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", + "unsupported_grant_type", "invalid_scope", "access_denied", "server_error", + "temporarily_unavailable", "invalid_token", "unsupported_token_type", + "invalid_redirect_uri", "invalid_client_metadata", +}) + + +class OAuthClientError(ValueError): + """Only operation, status, and recognized OAuth error codes are exposed.""" + + def __init__(self, operation: str, *, status: int | None = None, error_code=None): + self.operation = operation + self.status = status + self.error_code = error_code if isinstance(error_code, str) and error_code in _OAUTH_ERRORS else None + suffix = f" (HTTP {status})" if status is not None else "" + if self.error_code: + suffix += f": {self.error_code}" + super().__init__(f"OAuth {operation} failed{suffix}") + + +@dataclass(frozen=True) +class OAuth2ClientConfig: + client_id: str | None = field(default=None, repr=False) + client_secret: str | SecretValue | None = field(default=None, repr=False) + issuer: str | None = field(default=None, repr=False) + redirect_uri: str | None = field(default=None, repr=False) + authorization_endpoint: str | None = field(default=None, repr=False) + token_endpoint: str | None = field(default=None, repr=False) + revocation_endpoint: str | None = field(default=None, repr=False) + registration_endpoint: str | None = field(default=None, repr=False) + protected_resource_metadata_url: str | None = field(default=None, repr=False) + authorization_server_metadata_url: str | None = field(default=None, repr=False) + + def __post_init__(self): + if any(value is not None and (not isinstance(value, str) or not value) + for value in (getattr(self, item.name) for item in fields(self) if item.name != "client_secret")): + raise OAuthClientError("configuration") + if self.client_secret is not None and not isinstance(self.client_secret, SecretValue): + if not isinstance(self.client_secret, str) or not self.client_secret: + raise OAuthClientError("configuration") + + +@dataclass(frozen=True) +class AuthorizationFlow: + authorization_url: str = field(repr=False) + state: str = field(repr=False) + code_verifier: str = field(repr=False) + code_challenge: str = field(repr=False) + code_challenge_method: str = "S256" + + +@dataclass(frozen=True) +class ClientRegistration: + client_id: str = field(repr=False) + client_secret: str | None = field(default=None, repr=False) + metadata: Mapping[str, Any] = field(default_factory=dict, repr=False) + + def __post_init__(self): + if (not isinstance(self.client_id, str) or not self.client_id + or (self.client_secret is not None and not isinstance(self.client_secret, str))): + raise OAuthClientError("registration response") + object.__setattr__(self, "metadata", MappingProxyType(dict(self.metadata))) + + def to_dict(self) -> dict[str, Any]: + """Explicit credential-bearing output; never log this mapping.""" + result = {**self.metadata, "client_id": self.client_id} + if self.client_secret is not None: + result["client_secret"] = self.client_secret + return result + + +@dataclass(frozen=True) +class _Request: + method: str + url: str = field(repr=False) + headers: Mapping[str, str] = field(repr=False) + body: bytes | None = field(repr=False) + timeout: float + pinned_ip: str | None = field(default=None, repr=False) + + +@dataclass(frozen=True) +class _Response: + status: int + headers: Mapping[str, str] = field(repr=False) + body: bytes = field(repr=False) diff --git a/nitrostack/auth/client.py b/nitrostack/auth/client.py index 8260d37..d458f55 100644 --- a/nitrostack/auth/client.py +++ b/nitrostack/auth/client.py @@ -12,107 +12,22 @@ import urllib.parse import urllib.request import weakref -from dataclasses import dataclass, field, fields -from types import MappingProxyType +from dataclasses import fields from typing import Any, Mapping from nitrostack.auth import cimd -from nitrostack.auth.secret import SecretValue, unwrap_secret +# Re-export the original import locations for callers and transport test seams. +from nitrostack.auth._client_types import ( + AuthorizationFlow, ClientRegistration, OAuth2ClientConfig, OAuthClientError, + _Request, _Response, +) +from nitrostack.auth.secret import unwrap_secret from nitrostack.auth.pkce import generate_pkce_params, is_valid_code_verifier, validate_pkce_support from nitrostack.auth.token_store import ( MemoryTokenStore, StoredToken, TokenStore, is_token_expired, token_response_to_stored, ) -_OAUTH_ERRORS = frozenset({ - "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", - "unsupported_grant_type", "invalid_scope", "access_denied", "server_error", - "temporarily_unavailable", "invalid_token", "unsupported_token_type", - "invalid_redirect_uri", "invalid_client_metadata", -}) - - -class OAuthClientError(ValueError): - """Only operation, status, and recognized OAuth error codes are exposed.""" - - def __init__(self, operation: str, *, status: int | None = None, error_code=None): - self.operation = operation - self.status = status - self.error_code = error_code if isinstance(error_code, str) and error_code in _OAUTH_ERRORS else None - suffix = f" (HTTP {status})" if status is not None else "" - if self.error_code: - suffix += f": {self.error_code}" - super().__init__(f"OAuth {operation} failed{suffix}") - - -@dataclass(frozen=True) -class OAuth2ClientConfig: - client_id: str | None = field(default=None, repr=False) - client_secret: str | SecretValue | None = field(default=None, repr=False) - issuer: str | None = field(default=None, repr=False) - redirect_uri: str | None = field(default=None, repr=False) - authorization_endpoint: str | None = field(default=None, repr=False) - token_endpoint: str | None = field(default=None, repr=False) - revocation_endpoint: str | None = field(default=None, repr=False) - registration_endpoint: str | None = field(default=None, repr=False) - protected_resource_metadata_url: str | None = field(default=None, repr=False) - authorization_server_metadata_url: str | None = field(default=None, repr=False) - - def __post_init__(self): - if any(value is not None and (not isinstance(value, str) or not value) - for value in (getattr(self, item.name) for item in fields(self) if item.name != "client_secret")): - raise OAuthClientError("configuration") - if self.client_secret is not None and not isinstance(self.client_secret, SecretValue): - if not isinstance(self.client_secret, str) or not self.client_secret: - raise OAuthClientError("configuration") - - -@dataclass(frozen=True) -class AuthorizationFlow: - authorization_url: str = field(repr=False) - state: str = field(repr=False) - code_verifier: str = field(repr=False) - code_challenge: str = field(repr=False) - code_challenge_method: str = "S256" - - -@dataclass(frozen=True) -class ClientRegistration: - client_id: str = field(repr=False) - client_secret: str | None = field(default=None, repr=False) - metadata: Mapping[str, Any] = field(default_factory=dict, repr=False) - - def __post_init__(self): - if (not isinstance(self.client_id, str) or not self.client_id - or (self.client_secret is not None and not isinstance(self.client_secret, str))): - raise OAuthClientError("registration response") - object.__setattr__(self, "metadata", MappingProxyType(dict(self.metadata))) - - def to_dict(self) -> dict[str, Any]: - """Explicit credential-bearing output; never log this mapping.""" - result = {**self.metadata, "client_id": self.client_id} - if self.client_secret is not None: - result["client_secret"] = self.client_secret - return result - - -@dataclass(frozen=True) -class _Request: - method: str - url: str = field(repr=False) - headers: Mapping[str, str] = field(repr=False) - body: bytes | None = field(repr=False) - timeout: float - pinned_ip: str | None = field(default=None, repr=False) - - -@dataclass(frozen=True) -class _Response: - status: int - headers: Mapping[str, str] = field(repr=False) - body: bytes = field(repr=False) - - def get_well_known_metadata_uris(resource_url: str) -> list[str]: parsed = urllib.parse.urlsplit(resource_url) origin = f"{parsed.scheme}://{parsed.netloc}" diff --git a/tests/support/oauth_client.py b/tests/support/oauth_client.py new file mode 100644 index 0000000..3cd949a --- /dev/null +++ b/tests/support/oauth_client.py @@ -0,0 +1,39 @@ +"""Shared OAuth client fixtures without network access.""" + +import json +from unittest.mock import AsyncMock + +from nitrostack import OAuth2Client, StoredToken +from nitrostack.auth.client import _Response + +ACCESS = "ACCESS_SENTINEL_NEVER_LOG" +REFRESH = "REFRESH_SENTINEL_NEVER_LOG" +SECRET = "CLIENT_SENTINEL_NEVER_LOG: with spaces" +ENDPOINT = "https://issuer.example/token" + + +def response(value=None, *, status=200, headers=None, raw=None): + body = raw if raw is not None else json.dumps(value if value is not None else {"access_token": ACCESS}).encode() + return _Response(status, headers or {}, body) + + +def client(**overrides): + return OAuth2Client({"client_id": "client:id", "client_secret": SECRET, + "issuer": "https://issuer.example", "redirect_uri": "http://127.0.0.1/callback", + "authorization_endpoint": "https://issuer.example/authorize?audience=api&state=old&scope=old", + "token_endpoint": ENDPOINT, "revocation_endpoint": "https://issuer.example/revoke", + "registration_endpoint": "https://issuer.example/register", **overrides}) + + +def install_transport(monkeypatch, oauth, *responses): + send = AsyncMock(side_effect=list(responses) if responses else None) + if not responses: + send.return_value = response() + monkeypatch.setattr(oauth, "_send", send) + return send + + +async def saved(oauth, key="alice", refresh=REFRESH): + token = StoredToken(ACCESS, "Bearer", 1, refresh, "read", "https://resource.example") + await oauth.store.save_token(key, token) + return token diff --git a/tests/test_oauth_client.py b/tests/test_oauth_client.py index 61d2bf1..0cd6344 100644 --- a/tests/test_oauth_client.py +++ b/tests/test_oauth_client.py @@ -18,40 +18,11 @@ parse_www_authenticate_header, ) from nitrostack.auth import cimd -from nitrostack.auth.client import _Response from nitrostack.auth.pkce import generate_code_challenge, is_valid_code_verifier -ACCESS = "ACCESS_SENTINEL_NEVER_LOG" -REFRESH = "REFRESH_SENTINEL_NEVER_LOG" -SECRET = "CLIENT_SENTINEL_NEVER_LOG: with spaces" -ENDPOINT = "https://issuer.example/token" - - -def response(value=None, *, status=200, headers=None, raw=None): - body = raw if raw is not None else json.dumps(value if value is not None else {"access_token": ACCESS}).encode() - return _Response(status, headers or {}, body) - - -def client(**overrides): - return OAuth2Client({"client_id": "client:id", "client_secret": SECRET, - "issuer": "https://issuer.example", "redirect_uri": "http://127.0.0.1/callback", - "authorization_endpoint": "https://issuer.example/authorize?audience=api&state=old&scope=old", - "token_endpoint": ENDPOINT, "revocation_endpoint": "https://issuer.example/revoke", - "registration_endpoint": "https://issuer.example/register", **overrides}) - - -def install_transport(monkeypatch, oauth, *responses): - send = AsyncMock(side_effect=list(responses) if responses else None) - if not responses: - send.return_value = response() - monkeypatch.setattr(oauth, "_send", send) - return send - - -async def saved(oauth, key="alice", refresh=REFRESH): - token = StoredToken(ACCESS, "Bearer", 1, refresh, "read", "https://resource.example") - await oauth.store.save_token(key, token) - return token +from tests.support.oauth_client import ( + ACCESS, REFRESH, SECRET, ENDPOINT, client, install_transport, response, saved, +) @pytest.mark.asyncio @@ -445,233 +416,3 @@ def test_invalid_client_limits(options): def test_invalid_operator_url_is_rejected(url): with pytest.raises(OAuthClientError): client(token_endpoint=url) - -@pytest.mark.asyncio -async def test_secret_wrapper_deferred_unwrap(monkeypatch, caplog, capsys): - import pickle - from nitrostack import SecretValue - secret = SecretValue(SECRET) - original = SecretValue.unwrap - calls = [] - def unwrap(self): - calls.append(1) - return original(self) - monkeypatch.setattr(SecretValue, "unwrap", unwrap) - oauth = client(client_secret=secret) - assert oauth.config.client_secret is secret and calls == [] - send = install_transport(monkeypatch, oauth) - await oauth.get_client_credentials_token("alice") - assert len(calls) == 1 - plain = client() - plain_send = install_transport(monkeypatch, plain) - await plain.get_client_credentials_token("alice") - assert send.call_args.args[0].headers == plain_send.call_args.args[0].headers - for unusable in (pickle.loads(pickle.dumps(secret)),): - broken = client(client_secret=unusable) - transport = install_transport(monkeypatch, broken) - with pytest.raises(OAuthClientError) as exc: - await broken.get_client_credentials_token("alice") - transport.assert_not_awaited() - assert SECRET not in str(exc.value) + repr(exc.value) - assert SECRET not in repr(oauth.config) + caplog.text + str(capsys.readouterr()) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("failure", ["missing", "http", "network"]) -@pytest.mark.parametrize("fallback", [False, True]) -async def test_local_revocation_fallback(monkeypatch, failure, fallback): - oauth = client(revocation_endpoint=None) if failure == "missing" else client() - previous = await saved(oauth) - send = install_transport(monkeypatch, oauth, response({"error": "server_error"}, status=500)) - if failure == "network": - send.side_effect = OSError(SECRET) - if fallback: - await oauth.revoke_token("alice", local_fallback=True) - assert await oauth.store.get_token("alice") is None - else: - with pytest.raises(OAuthClientError): - await oauth.revoke_token("alice") - assert await oauth.store.get_token("alice") == previous - assert send.await_count == (0 if failure == "missing" else 1) - - -@pytest.mark.asyncio -async def test_fallback_does_not_hide_validation_storage_or_cancellation(monkeypatch): - oauth = client(revocation_endpoint=None) - previous = await saved(oauth) - with pytest.raises(OAuthClientError): - await oauth.revoke_token("alice", token_type_hint="bad", local_fallback=True) - assert await oauth.store.get_token("alice") == previous - monkeypatch.setattr(oauth.store, "delete_token", AsyncMock(side_effect=OSError(SECRET))) - with pytest.raises(OAuthClientError) as exc: - await oauth.revoke_token("alice", local_fallback=True) - assert SECRET not in str(exc.value) - oauth = client() - previous = await saved(oauth) - send = install_transport(monkeypatch, oauth) - send.side_effect = asyncio.CancelledError() - with pytest.raises(asyncio.CancelledError): - await oauth.revoke_token("alice", local_fallback=True) - assert await oauth.store.get_token("alice") == previous - - -@pytest.mark.asyncio -async def test_get_access_token_boundaries_and_explicit_refresh(monkeypatch): - monkeypatch.setattr("nitrostack.auth.token_store.time.time", lambda: 1000) - oauth = client() - send = install_transport(monkeypatch, oauth) - await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 1030001, REFRESH)) - assert await oauth.get_access_token("alice") == ACCESS - send.assert_not_awaited() - await oauth.refresh_token("alice") - assert send.await_count == 1 - await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 1030000, REFRESH)) - await oauth.get_access_token("alice") - assert send.await_count == 2 - with pytest.raises(OAuthClientError): - await oauth.get_access_token("missing") - await saved(oauth, refresh=None) - with pytest.raises(OAuthClientError): - await oauth.get_access_token("alice") - - -@pytest.mark.asyncio -async def test_get_access_token_coalesces_cancellation_and_delayed_read(monkeypatch): - oauth = client() - await saved(oauth) - entered, release = asyncio.Event(), asyncio.Event() - calls = [] - async def send(request): - calls.append(request) - entered.set() - await release.wait() - return response({"access_token": "new", "refresh_token": "rotated"}) - monkeypatch.setattr(oauth, "_send", send) - tasks = [asyncio.create_task(oauth.get_access_token("alice")) for _ in range(50)] - await asyncio.wait_for(entered.wait(), 2) - tasks[0].cancel() - with pytest.raises(asyncio.CancelledError): - await tasks[0] - release.set() - assert await asyncio.gather(*tasks[1:]) == ["new"] * 49 - assert await oauth.get_access_token("alice") == "new" - assert len(calls) == 1 - assert oauth._refresh_tasks == {} and oauth._force_refresh == {} - assert (await oauth.store.get_token("alice")).refresh_token == "rotated" - - -@pytest.mark.asyncio -async def test_auto_refresh_rechecks_after_lock_and_explicit_call_forces(monkeypatch): - oauth = client() - send = install_transport(monkeypatch, oauth) - await saved(oauth) - lock = oauth._key_lock("alice") - async with lock: - pending = asyncio.create_task(oauth.get_access_token("alice")) - await asyncio.sleep(0) - await oauth.store.save_token("alice", StoredToken("fresh", "Bearer", 10**15, REFRESH)) - assert await pending == "fresh" - send.assert_not_awaited() - async with lock: - automatic = asyncio.create_task(oauth.get_access_token("alice")) - await asyncio.sleep(0) - explicit = asyncio.create_task(oauth.refresh_token("alice")) - await asyncio.sleep(0) - await asyncio.gather(automatic, explicit) - assert send.await_count == 1 - - -@pytest.mark.asyncio -async def test_get_access_token_failure_retry_and_persistence(monkeypatch): - oauth = client() - previous = await saved(oauth) - install_transport(monkeypatch, oauth, response({"error": "invalid_grant"}, status=400)) - with pytest.raises(OAuthClientError): - await oauth.get_access_token("alice") - assert await oauth.store.get_token("alice") == previous - send = install_transport(monkeypatch, oauth) - monkeypatch.setattr(oauth.store, "save_token", AsyncMock(side_effect=OSError(SECRET))) - with pytest.raises(OAuthClientError): - await oauth.get_access_token("alice") - assert send.await_count == 1 and await oauth.store.get_token("alice") == previous - -@pytest.mark.asyncio -async def test_explicit_refresh_during_slow_valid_token_read(monkeypatch): - oauth = client() - await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 10**15, REFRESH)) - entered, release = asyncio.Event(), asyncio.Event() - original = oauth.store.get_token - async def slow_read(key): - entered.set() - await release.wait() - return await original(key) - monkeypatch.setattr(oauth.store, "get_token", slow_read) - send = install_transport(monkeypatch, oauth) - automatic = asyncio.create_task(oauth.get_access_token("alice")) - await asyncio.wait_for(entered.wait(), 2) - explicit = asyncio.create_task(oauth.refresh_token("alice")) - await asyncio.sleep(0) - release.set() - await asyncio.gather(automatic, explicit) - assert send.await_count == 1 - - -@pytest.mark.asyncio -async def test_local_fallback_waits_for_active_refresh(monkeypatch): - oauth = client(revocation_endpoint=None) - await saved(oauth) - entered, release = asyncio.Event(), asyncio.Event() - async def send(request): - entered.set() - await release.wait() - return response({"access_token": "rotated-access", "refresh_token": "rotated-refresh"}) - monkeypatch.setattr(oauth, "_send", send) - pending = asyncio.create_task(oauth.get_access_token("alice")) - await asyncio.wait_for(entered.wait(), 2) - revoke = asyncio.create_task(oauth.revoke_token("alice", local_fallback=True)) - await asyncio.sleep(0) - assert not revoke.done() - release.set() - await asyncio.gather(pending, revoke) - assert await oauth.store.get_token("alice") is None - - -@pytest.mark.asyncio -async def test_helper_shared_failures_independent_keys_and_retry(monkeypatch): - oauth = client() - await saved(oauth) - await saved(oauth, "bob") - entered, release = asyncio.Event(), asyncio.Event() - count = 0 - async def send(request): - nonlocal count - count += 1 - if count == 2: - entered.set() - await release.wait() - return response({"error": "invalid_grant", "error_description": SECRET}, status=400) - monkeypatch.setattr(oauth, "_send", send) - tasks = [asyncio.create_task(oauth.get_access_token("alice")) for _ in range(20)] - tasks.append(asyncio.create_task(oauth.get_access_token("bob"))) - await asyncio.wait_for(entered.wait(), 2) - release.set() - results = await asyncio.gather(*tasks, return_exceptions=True) - assert count == 2 and all(isinstance(result, OAuthClientError) for result in results) - assert all(result is results[0] for result in results[:20]) - assert SECRET not in repr(results) - assert oauth._refresh_tasks == {} and oauth._force_refresh == {} - install_transport(monkeypatch, oauth) - assert await oauth.get_access_token("alice") == ACCESS - - -@pytest.mark.asyncio -async def test_helper_rejects_immediately_expired_replacement_and_storage_failure(monkeypatch): - oauth = client() - await saved(oauth) - install_transport(monkeypatch, oauth, response({"access_token": ACCESS, "expires_in": "0"})) - with pytest.raises(OAuthClientError, match="expiry"): - await oauth.get_access_token("alice") - monkeypatch.setattr(oauth.store, "get_token", AsyncMock(side_effect=OSError(SECRET))) - with pytest.raises(OAuthClientError) as exc: - await oauth.get_access_token("alice") - assert SECRET not in str(exc.value) diff --git a/tests/test_oauth_client_followups.py b/tests/test_oauth_client_followups.py new file mode 100644 index 0000000..187b7f4 --- /dev/null +++ b/tests/test_oauth_client_followups.py @@ -0,0 +1,242 @@ +"""OAuth usability, revocation fallback, and automatic refresh regressions.""" + +import asyncio +from unittest.mock import AsyncMock + +import pytest + +from nitrostack import OAuthClientError, StoredToken +from tests.support.oauth_client import ( + ACCESS, REFRESH, SECRET, client, install_transport, response, saved, +) + + +@pytest.mark.asyncio +async def test_secret_wrapper_deferred_unwrap(monkeypatch, caplog, capsys): + import pickle + from nitrostack import SecretValue + secret = SecretValue(SECRET) + original = SecretValue.unwrap + calls = [] + def unwrap(self): + calls.append(1) + return original(self) + monkeypatch.setattr(SecretValue, "unwrap", unwrap) + oauth = client(client_secret=secret) + assert oauth.config.client_secret is secret and calls == [] + send = install_transport(monkeypatch, oauth) + await oauth.get_client_credentials_token("alice") + assert len(calls) == 1 + plain = client() + plain_send = install_transport(monkeypatch, plain) + await plain.get_client_credentials_token("alice") + assert send.call_args.args[0].headers == plain_send.call_args.args[0].headers + for unusable in (pickle.loads(pickle.dumps(secret)),): + broken = client(client_secret=unusable) + transport = install_transport(monkeypatch, broken) + with pytest.raises(OAuthClientError) as exc: + await broken.get_client_credentials_token("alice") + transport.assert_not_awaited() + assert SECRET not in str(exc.value) + repr(exc.value) + assert SECRET not in repr(oauth.config) + caplog.text + str(capsys.readouterr()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["missing", "http", "network"]) +@pytest.mark.parametrize("fallback", [False, True]) +async def test_local_revocation_fallback(monkeypatch, failure, fallback): + oauth = client(revocation_endpoint=None) if failure == "missing" else client() + previous = await saved(oauth) + send = install_transport(monkeypatch, oauth, response({"error": "server_error"}, status=500)) + if failure == "network": + send.side_effect = OSError(SECRET) + if fallback: + await oauth.revoke_token("alice", local_fallback=True) + assert await oauth.store.get_token("alice") is None + else: + with pytest.raises(OAuthClientError): + await oauth.revoke_token("alice") + assert await oauth.store.get_token("alice") == previous + assert send.await_count == (0 if failure == "missing" else 1) + + +@pytest.mark.asyncio +async def test_fallback_does_not_hide_validation_storage_or_cancellation(monkeypatch): + oauth = client(revocation_endpoint=None) + previous = await saved(oauth) + with pytest.raises(OAuthClientError): + await oauth.revoke_token("alice", token_type_hint="bad", local_fallback=True) + assert await oauth.store.get_token("alice") == previous + monkeypatch.setattr(oauth.store, "delete_token", AsyncMock(side_effect=OSError(SECRET))) + with pytest.raises(OAuthClientError) as exc: + await oauth.revoke_token("alice", local_fallback=True) + assert SECRET not in str(exc.value) + oauth = client() + previous = await saved(oauth) + send = install_transport(monkeypatch, oauth) + send.side_effect = asyncio.CancelledError() + with pytest.raises(asyncio.CancelledError): + await oauth.revoke_token("alice", local_fallback=True) + assert await oauth.store.get_token("alice") == previous + + +@pytest.mark.asyncio +async def test_get_access_token_boundaries_and_explicit_refresh(monkeypatch): + monkeypatch.setattr("nitrostack.auth.token_store.time.time", lambda: 1000) + oauth = client() + send = install_transport(monkeypatch, oauth) + await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 1030001, REFRESH)) + assert await oauth.get_access_token("alice") == ACCESS + send.assert_not_awaited() + await oauth.refresh_token("alice") + assert send.await_count == 1 + await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 1030000, REFRESH)) + await oauth.get_access_token("alice") + assert send.await_count == 2 + with pytest.raises(OAuthClientError): + await oauth.get_access_token("missing") + await saved(oauth, refresh=None) + with pytest.raises(OAuthClientError): + await oauth.get_access_token("alice") + + +@pytest.mark.asyncio +async def test_get_access_token_coalesces_cancellation_and_delayed_read(monkeypatch): + oauth = client() + await saved(oauth) + entered, release = asyncio.Event(), asyncio.Event() + calls = [] + async def send(request): + calls.append(request) + entered.set() + await release.wait() + return response({"access_token": "new", "refresh_token": "rotated"}) + monkeypatch.setattr(oauth, "_send", send) + tasks = [asyncio.create_task(oauth.get_access_token("alice")) for _ in range(50)] + await asyncio.wait_for(entered.wait(), 2) + tasks[0].cancel() + with pytest.raises(asyncio.CancelledError): + await tasks[0] + release.set() + assert await asyncio.gather(*tasks[1:]) == ["new"] * 49 + assert await oauth.get_access_token("alice") == "new" + assert len(calls) == 1 + assert oauth._refresh_tasks == {} and oauth._force_refresh == {} + assert (await oauth.store.get_token("alice")).refresh_token == "rotated" + + +@pytest.mark.asyncio +async def test_auto_refresh_rechecks_after_lock_and_explicit_call_forces(monkeypatch): + oauth = client() + send = install_transport(monkeypatch, oauth) + await saved(oauth) + lock = oauth._key_lock("alice") + async with lock: + pending = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.sleep(0) + await oauth.store.save_token("alice", StoredToken("fresh", "Bearer", 10**15, REFRESH)) + assert await pending == "fresh" + send.assert_not_awaited() + async with lock: + automatic = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.sleep(0) + explicit = asyncio.create_task(oauth.refresh_token("alice")) + await asyncio.sleep(0) + await asyncio.gather(automatic, explicit) + assert send.await_count == 1 + + +@pytest.mark.asyncio +async def test_get_access_token_failure_retry_and_persistence(monkeypatch): + oauth = client() + previous = await saved(oauth) + install_transport(monkeypatch, oauth, response({"error": "invalid_grant"}, status=400)) + with pytest.raises(OAuthClientError): + await oauth.get_access_token("alice") + assert await oauth.store.get_token("alice") == previous + send = install_transport(monkeypatch, oauth) + monkeypatch.setattr(oauth.store, "save_token", AsyncMock(side_effect=OSError(SECRET))) + with pytest.raises(OAuthClientError): + await oauth.get_access_token("alice") + assert send.await_count == 1 and await oauth.store.get_token("alice") == previous + +@pytest.mark.asyncio +async def test_explicit_refresh_during_slow_valid_token_read(monkeypatch): + oauth = client() + await oauth.store.save_token("alice", StoredToken(ACCESS, "Bearer", 10**15, REFRESH)) + entered, release = asyncio.Event(), asyncio.Event() + original = oauth.store.get_token + async def slow_read(key): + entered.set() + await release.wait() + return await original(key) + monkeypatch.setattr(oauth.store, "get_token", slow_read) + send = install_transport(monkeypatch, oauth) + automatic = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.wait_for(entered.wait(), 2) + explicit = asyncio.create_task(oauth.refresh_token("alice")) + await asyncio.sleep(0) + release.set() + await asyncio.gather(automatic, explicit) + assert send.await_count == 1 + + +@pytest.mark.asyncio +async def test_local_fallback_waits_for_active_refresh(monkeypatch): + oauth = client(revocation_endpoint=None) + await saved(oauth) + entered, release = asyncio.Event(), asyncio.Event() + async def send(request): + entered.set() + await release.wait() + return response({"access_token": "rotated-access", "refresh_token": "rotated-refresh"}) + monkeypatch.setattr(oauth, "_send", send) + pending = asyncio.create_task(oauth.get_access_token("alice")) + await asyncio.wait_for(entered.wait(), 2) + revoke = asyncio.create_task(oauth.revoke_token("alice", local_fallback=True)) + await asyncio.sleep(0) + assert not revoke.done() + release.set() + await asyncio.gather(pending, revoke) + assert await oauth.store.get_token("alice") is None + + +@pytest.mark.asyncio +async def test_helper_shared_failures_independent_keys_and_retry(monkeypatch): + oauth = client() + await saved(oauth) + await saved(oauth, "bob") + entered, release = asyncio.Event(), asyncio.Event() + count = 0 + async def send(request): + nonlocal count + count += 1 + if count == 2: + entered.set() + await release.wait() + return response({"error": "invalid_grant", "error_description": SECRET}, status=400) + monkeypatch.setattr(oauth, "_send", send) + tasks = [asyncio.create_task(oauth.get_access_token("alice")) for _ in range(20)] + tasks.append(asyncio.create_task(oauth.get_access_token("bob"))) + await asyncio.wait_for(entered.wait(), 2) + release.set() + results = await asyncio.gather(*tasks, return_exceptions=True) + assert count == 2 and all(isinstance(result, OAuthClientError) for result in results) + assert all(result is results[0] for result in results[:20]) + assert SECRET not in repr(results) + assert oauth._refresh_tasks == {} and oauth._force_refresh == {} + install_transport(monkeypatch, oauth) + assert await oauth.get_access_token("alice") == ACCESS + + +@pytest.mark.asyncio +async def test_helper_rejects_immediately_expired_replacement_and_storage_failure(monkeypatch): + oauth = client() + await saved(oauth) + install_transport(monkeypatch, oauth, response({"access_token": ACCESS, "expires_in": "0"})) + with pytest.raises(OAuthClientError, match="expiry"): + await oauth.get_access_token("alice") + monkeypatch.setattr(oauth.store, "get_token", AsyncMock(side_effect=OSError(SECRET))) + with pytest.raises(OAuthClientError) as exc: + await oauth.get_access_token("alice") + assert SECRET not in str(exc.value) From 6d746c1174cf69aa8b59c1bc868937713a29959e Mon Sep 17 00:00:00 2001 From: Siddharth Date: Sat, 7 Nov 2026 16:05:23 +0530 Subject: [PATCH 114/146] refactor(cli): extract packaging file selection and metadata --- nitrostack/cli/_pack_files.py | 159 +++++++++++++++++ nitrostack/cli/_pack_metadata.py | 155 ++++++++++++++++ nitrostack/cli/pack.py | 298 ++----------------------------- 3 files changed, 328 insertions(+), 284 deletions(-) create mode 100644 nitrostack/cli/_pack_files.py create mode 100644 nitrostack/cli/_pack_metadata.py diff --git a/nitrostack/cli/_pack_files.py b/nitrostack/cli/_pack_files.py new file mode 100644 index 0000000..4ccc99f --- /dev/null +++ b/nitrostack/cli/_pack_files.py @@ -0,0 +1,159 @@ +"""File selection, staging, and cleanup for project packaging.""" + +from __future__ import annotations + +import os +import shutil +import stat +from fnmatch import fnmatch +from typing import List, Sequence, Tuple + +from nitrostack.cli._shared import EXCLUDE_DIR_NAMES + + +_EXCLUDE_DIR_NAMES = EXCLUDE_DIR_NAMES + + +_EXCLUDE_SUFFIXES = { + ".pyc", + ".pyo", + ".pyd", + ".so", + ".dll", + ".egg", +} + + +_EXCLUDE_NAME_GLOBS = { + "*.egg-info", +} + + +def _is_secret_env(name: str) -> bool: + if name == ".env.example": + return False + return name == ".env" or name.startswith(".env.") + + +def _load_gitignore_patterns(root: str) -> List[Tuple[str, bool]]: + """Return (pattern, is_negation) pairs from .gitignore if present.""" + path = os.path.join(root, ".gitignore") + patterns: List[Tuple[str, bool]] = [] + if not os.path.isfile(path): + return patterns + try: + with open(path, "r", encoding="utf-8") as handle: + for raw in handle: + line = raw.strip() + if not line or line.startswith("#"): + continue + negated = line.startswith("!") + if negated: + line = line[1:] + patterns.append((line.rstrip("/"), negated)) + except OSError: + return [] + return patterns + + +def _matches_gitignore(rel_posix: str, patterns: Sequence[Tuple[str, bool]]) -> bool: + ignored = False + basename = rel_posix.rsplit("/", 1)[-1] + for pattern, negated in patterns: + pat = pattern[2:] if pattern.startswith("./") else pattern + hit = ( + fnmatch(rel_posix, pat) + or fnmatch(rel_posix, pat.rstrip("/") + "/*") + or fnmatch(basename, pat) + or (pat.endswith("/") and (rel_posix.startswith(pat) or rel_posix.startswith(pat.rstrip("/")))) + ) + if hit: + ignored = not negated + return ignored + + +def _should_exclude(rel_posix: str, name: str, is_dir: bool, gitignore: Sequence[Tuple[str, bool]]) -> bool: + if name == ".env.example": + return False + if _is_secret_env(name): + return True + if name in _EXCLUDE_DIR_NAMES and is_dir: + return True + if any(fnmatch(name, glob) for glob in _EXCLUDE_NAME_GLOBS): + return True + if any(name.endswith(suffix) for suffix in _EXCLUDE_SUFFIXES): + return True + if name.endswith(".egg-info") or ".egg-info/" in rel_posix: + return True + if _matches_gitignore(rel_posix, gitignore): + return True + return False + + +def collect_pack_files(root: str) -> List[str]: + """Return posix-relative paths that would be included in a pack.""" + gitignore = _load_gitignore_patterns(root) + included: List[str] = [] + root = os.path.abspath(root) + + for dirpath, dirnames, filenames in os.walk(root): + rel_dir = os.path.relpath(dirpath, root) + rel_dir_posix = "" if rel_dir == "." else rel_dir.replace("\\", "/") + + kept_dirs = [] + for dirname in dirnames: + child_rel = f"{rel_dir_posix}/{dirname}" if rel_dir_posix else dirname + if _should_exclude(child_rel, dirname, True, gitignore): + 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): + continue + included.append(child_rel) + + if ".env.example" not in included: + included.append(".env.example") + included.sort() + return included + + +def _rmtree(path: str) -> None: + def _onerror(func, p, _exc): + try: + os.chmod(p, stat.S_IWRITE) + func(p) + except OSError: + pass + + shutil.rmtree(path, onerror=_onerror) + + +def _copy_selected(src_root: str, dest_root: str, files: Sequence[str]) -> None: + for rel in files: + if rel == ".env.example": + continue # handled separately so a stub can be created + src = os.path.join(src_root, rel.replace("/", os.sep)) + dest = os.path.join(dest_root, rel.replace("/", os.sep)) + if not os.path.isfile(src): + continue + os.makedirs(os.path.dirname(dest) or dest_root, exist_ok=True) + shutil.copy2(src, dest) + + +def _collect_staging_bytes(src_root: str) -> 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): + continue + full = os.path.join(dirpath, filename) + rel = os.path.relpath(full, src_root).replace("\\", "/") + with open(full, "rb") as handle: + contents[rel] = handle.read() + return contents diff --git a/nitrostack/cli/_pack_metadata.py b/nitrostack/cli/_pack_metadata.py new file mode 100644 index 0000000..868a68c --- /dev/null +++ b/nitrostack/cli/_pack_metadata.py @@ -0,0 +1,155 @@ +"""Project identity, dependency declarations, and generated packaging metadata.""" + +from __future__ import annotations + +import os +import re +from typing import Iterable, List, Optional, Sequence, Set, Tuple + +from nitrostack.cli._pack_files import _EXCLUDE_DIR_NAMES +from nitrostack.cli._shared import ( + parse_pyproject_dependencies, parse_requirements, read_text, requirement_name, +) + + +ENV_EXAMPLE_STUB = """PORT=8000 +NODE_ENV=development +""" + + +_PYPROJECT_TEMPLATE = """[build-system] +requires = ["setuptools>=61.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "{name}" +version = "{version}" +description = "Packed NitroStack MCP server" +requires-python = ">=3.10" +dependencies = {deps} + +[tool.setuptools] +py-modules = {py_modules} + +[tool.setuptools.packages.find] +where = ["."] +namespaces = true +exclude = ["tests*", "venv*", "node_modules*", "src.widgets*"] + +[tool.setuptools.package-data] +"*" = [".env.example", "requirements.txt", "*.md"] +""" + + +def _read_text(path: str) -> str: + return read_text(path) + + +def _parse_pyproject_field(text: str, field: str) -> Optional[str]: + match = re.search(rf'^{field}\s*=\s*["\']([^"\']+)["\']', text, re.MULTILINE) + return match.group(1) if match else None + + +def _parse_pyproject_dependencies(text: str) -> List[str]: + return parse_pyproject_dependencies(text) + + +def _parse_requirements(path: str) -> List[str]: + return parse_requirements(path) + + +def _project_name_and_version(root: str) -> Tuple[str, str]: + pyproject = os.path.join(root, "pyproject.toml") + if os.path.isfile(pyproject): + text = _read_text(pyproject) + name = _parse_pyproject_field(text, "name") + version = _parse_pyproject_field(text, "version") + if name and version: + return name, version + if name: + return name, version or "0.1.0" + return os.path.basename(os.path.abspath(root)) or "nitrostack-project", "0.1.0" + + +def _normalize_dist_name(name: str) -> str: + normalized = re.sub(r"[-_.]+", "-", name).strip("-").lower() + return normalized or "nitrostack-project" + + +def _pep503_wheel_name(name: str) -> str: + return re.sub(r"[-_.]+", "_", name) + + +def _requirement_name(req: str) -> str: + return requirement_name(req) + + +def requirements_from_project(root: str) -> List[str]: + pyproject = os.path.join(root, "pyproject.toml") + req_path = os.path.join(root, "requirements.txt") + deps: List[str] = [] + name, _ = _project_name_and_version(root) + if os.path.isfile(pyproject): + deps = _parse_pyproject_dependencies(_read_text(pyproject)) + if not deps and os.path.isfile(req_path): + deps = _parse_requirements(req_path) + deps = [item.lstrip("\ufeff").strip() for item in deps if item.lstrip("\ufeff").strip()] + has_nitrostack = any(_requirement_name(item) == "nitrostack" for item in deps) + if not has_nitrostack and name.lower() != "nitrostack": + deps = ["nitrostack", *deps] + return deps + + +def write_requirements_txt(root: str, deps: Sequence[str]) -> str: + path = os.path.join(root, "requirements.txt") + body = "".join(f"{dep}\n" for dep in deps) if deps else "nitrostack\n" + with open(path, "w", encoding="utf-8") as handle: + handle.write(body) + return path + + +def _ensure_env_example(root: str) -> str: + path = os.path.join(root, ".env.example") + if not os.path.isfile(path): + with open(path, "w", encoding="utf-8") as handle: + handle.write(ENV_EXAMPLE_STUB) + return path + + +def _discover_py_modules_and_packages(root: str) -> Tuple[List[str], List[str]]: + py_modules: List[str] = [] + packages: Set[str] = set() + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_DIR_NAMES and not d.endswith(".egg-info")] + rel_dir = os.path.relpath(dirpath, root) + if rel_dir == ".": + for filename in filenames: + if filename.endswith(".py") and filename != "setup.py": + py_modules.append(os.path.splitext(filename)[0]) + continue + parts = rel_dir.replace("\\", "/").split("/") + if any(part in _EXCLUDE_DIR_NAMES for part in parts): + continue + if any(filename.endswith(".py") for filename in filenames): + packages.add(".".join(parts)) + return sorted(py_modules), sorted(packages) + + +def _toml_list(values: Iterable[str]) -> str: + items = ", ".join(f'"{v}"' for v in values) + return f"[{items}]" + + +def _ensure_pyproject(root: str, name: str, version: str, deps: Sequence[str]) -> None: + path = os.path.join(root, "pyproject.toml") + if os.path.isfile(path): + return + py_modules, _packages = _discover_py_modules_and_packages(root) + content = _PYPROJECT_TEMPLATE.format( + name=_normalize_dist_name(name), + version=version, + deps=_toml_list(deps), + py_modules=_toml_list(py_modules), + ) + with open(path, "w", encoding="utf-8") as handle: + handle.write(content) diff --git a/nitrostack/cli/pack.py b/nitrostack/cli/pack.py index b2a805c..161b3a4 100644 --- a/nitrostack/cli/pack.py +++ b/nitrostack/cli/pack.py @@ -24,275 +24,21 @@ requirement_name, ) -_EXCLUDE_DIR_NAMES = EXCLUDE_DIR_NAMES - -_EXCLUDE_SUFFIXES = { - ".pyc", - ".pyo", - ".pyd", - ".so", - ".dll", - ".egg", -} - -_EXCLUDE_NAME_GLOBS = { - "*.egg-info", -} - -ENV_EXAMPLE_STUB = """PORT=8000 -NODE_ENV=development -""" - -_PYPROJECT_TEMPLATE = """[build-system] -requires = ["setuptools>=61.0.0"] -build-backend = "setuptools.build_meta" - -[project] -name = "{name}" -version = "{version}" -description = "Packed NitroStack MCP server" -requires-python = ">=3.10" -dependencies = {deps} - -[tool.setuptools] -py-modules = {py_modules} - -[tool.setuptools.packages.find] -where = ["."] -namespaces = true -exclude = ["tests*", "venv*", "node_modules*", "src.widgets*"] - -[tool.setuptools.package-data] -"*" = [".env.example", "requirements.txt", "*.md"] -""" - - -def _is_secret_env(name: str) -> bool: - if name == ".env.example": - return False - return name == ".env" or name.startswith(".env.") - - -def _load_gitignore_patterns(root: str) -> List[Tuple[str, bool]]: - """Return (pattern, is_negation) pairs from .gitignore if present.""" - path = os.path.join(root, ".gitignore") - patterns: List[Tuple[str, bool]] = [] - if not os.path.isfile(path): - return patterns - try: - with open(path, "r", encoding="utf-8") as handle: - for raw in handle: - line = raw.strip() - if not line or line.startswith("#"): - continue - negated = line.startswith("!") - if negated: - line = line[1:] - patterns.append((line.rstrip("/"), negated)) - except OSError: - return [] - return patterns - - -def _matches_gitignore(rel_posix: str, patterns: Sequence[Tuple[str, bool]]) -> bool: - ignored = False - basename = rel_posix.rsplit("/", 1)[-1] - for pattern, negated in patterns: - pat = pattern[2:] if pattern.startswith("./") else pattern - hit = ( - fnmatch(rel_posix, pat) - or fnmatch(rel_posix, pat.rstrip("/") + "/*") - or fnmatch(basename, pat) - or (pat.endswith("/") and (rel_posix.startswith(pat) or rel_posix.startswith(pat.rstrip("/")))) - ) - if hit: - ignored = not negated - return ignored - - -def _should_exclude(rel_posix: str, name: str, is_dir: bool, gitignore: Sequence[Tuple[str, bool]]) -> bool: - if name == ".env.example": - return False - if _is_secret_env(name): - return True - if name in _EXCLUDE_DIR_NAMES and is_dir: - return True - if any(fnmatch(name, glob) for glob in _EXCLUDE_NAME_GLOBS): - return True - if any(name.endswith(suffix) for suffix in _EXCLUDE_SUFFIXES): - return True - if name.endswith(".egg-info") or ".egg-info/" in rel_posix: - return True - if _matches_gitignore(rel_posix, gitignore): - return True - return False - - -def collect_pack_files(root: str) -> List[str]: - """Return posix-relative paths that would be included in a pack.""" - gitignore = _load_gitignore_patterns(root) - included: List[str] = [] - root = os.path.abspath(root) - - for dirpath, dirnames, filenames in os.walk(root): - rel_dir = os.path.relpath(dirpath, root) - rel_dir_posix = "" if rel_dir == "." else rel_dir.replace("\\", "/") - - kept_dirs = [] - for dirname in dirnames: - child_rel = f"{rel_dir_posix}/{dirname}" if rel_dir_posix else dirname - if _should_exclude(child_rel, dirname, True, gitignore): - 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): - continue - included.append(child_rel) - - if ".env.example" not in included: - included.append(".env.example") - included.sort() - return included - - -def _read_text(path: str) -> str: - return read_text(path) - - -def _parse_pyproject_field(text: str, field: str) -> Optional[str]: - match = re.search(rf'^{field}\s*=\s*["\']([^"\']+)["\']', text, re.MULTILINE) - return match.group(1) if match else None - - -def _parse_pyproject_dependencies(text: str) -> List[str]: - return parse_pyproject_dependencies(text) - - -def _parse_requirements(path: str) -> List[str]: - return parse_requirements(path) - - -def _project_name_and_version(root: str) -> Tuple[str, str]: - pyproject = os.path.join(root, "pyproject.toml") - if os.path.isfile(pyproject): - text = _read_text(pyproject) - name = _parse_pyproject_field(text, "name") - version = _parse_pyproject_field(text, "version") - if name and version: - return name, version - if name: - return name, version or "0.1.0" - return os.path.basename(os.path.abspath(root)) or "nitrostack-project", "0.1.0" - - -def _normalize_dist_name(name: str) -> str: - normalized = re.sub(r"[-_.]+", "-", name).strip("-").lower() - return normalized or "nitrostack-project" - -def _pep503_wheel_name(name: str) -> str: - return re.sub(r"[-_.]+", "_", name) - - -def _requirement_name(req: str) -> str: - return requirement_name(req) - - -def requirements_from_project(root: str) -> List[str]: - pyproject = os.path.join(root, "pyproject.toml") - req_path = os.path.join(root, "requirements.txt") - deps: List[str] = [] - name, _ = _project_name_and_version(root) - if os.path.isfile(pyproject): - deps = _parse_pyproject_dependencies(_read_text(pyproject)) - if not deps and os.path.isfile(req_path): - deps = _parse_requirements(req_path) - deps = [item.lstrip("\ufeff").strip() for item in deps if item.lstrip("\ufeff").strip()] - has_nitrostack = any(_requirement_name(item) == "nitrostack" for item in deps) - if not has_nitrostack and name.lower() != "nitrostack": - deps = ["nitrostack", *deps] - return deps - - -def write_requirements_txt(root: str, deps: Sequence[str]) -> str: - path = os.path.join(root, "requirements.txt") - body = "".join(f"{dep}\n" for dep in deps) if deps else "nitrostack\n" - with open(path, "w", encoding="utf-8") as handle: - handle.write(body) - return path - - -def _ensure_env_example(root: str) -> str: - path = os.path.join(root, ".env.example") - if not os.path.isfile(path): - with open(path, "w", encoding="utf-8") as handle: - handle.write(ENV_EXAMPLE_STUB) - return path - - -def _discover_py_modules_and_packages(root: str) -> Tuple[List[str], List[str]]: - py_modules: List[str] = [] - packages: Set[str] = set() - for dirpath, dirnames, filenames in os.walk(root): - dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_DIR_NAMES and not d.endswith(".egg-info")] - rel_dir = os.path.relpath(dirpath, root) - if rel_dir == ".": - for filename in filenames: - if filename.endswith(".py") and filename != "setup.py": - py_modules.append(os.path.splitext(filename)[0]) - continue - parts = rel_dir.replace("\\", "/").split("/") - if any(part in _EXCLUDE_DIR_NAMES for part in parts): - continue - if any(filename.endswith(".py") for filename in filenames): - packages.add(".".join(parts)) - return sorted(py_modules), sorted(packages) - - -def _toml_list(values: Iterable[str]) -> str: - items = ", ".join(f'"{v}"' for v in values) - return f"[{items}]" - - -def _ensure_pyproject(root: str, name: str, version: str, deps: Sequence[str]) -> None: - path = os.path.join(root, "pyproject.toml") - if os.path.isfile(path): - return - py_modules, _packages = _discover_py_modules_and_packages(root) - content = _PYPROJECT_TEMPLATE.format( - name=_normalize_dist_name(name), - version=version, - deps=_toml_list(deps), - py_modules=_toml_list(py_modules), - ) - with open(path, "w", encoding="utf-8") as handle: - handle.write(content) - - -def _rmtree(path: str) -> None: - def _onerror(func, p, _exc): - try: - os.chmod(p, stat.S_IWRITE) - func(p) - except OSError: - pass - - shutil.rmtree(path, onerror=_onerror) - - -def _copy_selected(src_root: str, dest_root: str, files: Sequence[str]) -> None: - for rel in files: - if rel == ".env.example": - continue # handled separately so a stub can be created - src = os.path.join(src_root, rel.replace("/", os.sep)) - dest = os.path.join(dest_root, rel.replace("/", os.sep)) - if not os.path.isfile(src): - continue - os.makedirs(os.path.dirname(dest) or dest_root, exist_ok=True) - shutil.copy2(src, dest) +# Keep the original import surface while implementations live by responsibility. +from nitrostack.cli._pack_files import ( + _EXCLUDE_DIR_NAMES, _EXCLUDE_NAME_GLOBS, _EXCLUDE_SUFFIXES, + _collect_staging_bytes, _copy_selected, _is_secret_env, + _load_gitignore_patterns, _matches_gitignore, _rmtree, _should_exclude, + collect_pack_files, +) +from nitrostack.cli._pack_metadata import ( + ENV_EXAMPLE_STUB, _PYPROJECT_TEMPLATE, _discover_py_modules_and_packages, + _ensure_env_example, _ensure_pyproject, _normalize_dist_name, + _parse_pyproject_dependencies, _parse_pyproject_field, _parse_requirements, + _pep503_wheel_name, _project_name_and_version, _read_text, _requirement_name, + _toml_list, requirements_from_project, write_requirements_txt, +) def _sha256_record(data: bytes) -> str: @@ -348,22 +94,6 @@ def _is_valid_wheel(path: str) -> bool: return "Wheel-Version:" in body -def _collect_staging_bytes(src_root: str) -> 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): - continue - full = os.path.join(dirpath, filename) - rel = os.path.relpath(full, src_root).replace("\\", "/") - with open(full, "rb") as handle: - contents[rel] = handle.read() - return contents - - def _write_purelib_wheel( src_root: str, wheel_dir: str, From 580124781f0663dfbd1c22b381986ef9df5da452 Mon Sep 17 00:00:00 2001 From: Siddharth Date: Sat, 7 Nov 2026 16:10:01 +0530 Subject: [PATCH 115/146] refactor(cli): extract wheel assembly with compatible build callbacks --- nitrostack/cli/_pack_wheel.py | 153 ++++++++++++++++++++++++++++++++++ nitrostack/cli/pack.py | 141 ++++--------------------------- 2 files changed, 167 insertions(+), 127 deletions(-) create mode 100644 nitrostack/cli/_pack_wheel.py diff --git a/nitrostack/cli/_pack_wheel.py b/nitrostack/cli/_pack_wheel.py new file mode 100644 index 0000000..0eb14da --- /dev/null +++ b/nitrostack/cli/_pack_wheel.py @@ -0,0 +1,153 @@ +"""Wheel assembly, backend fallback, and archive integrity for project packaging.""" + +from __future__ import annotations + +import os +import zipfile +from typing import Callable, Optional, Sequence, Tuple + +from nitrostack.cli._pack_files import _collect_staging_bytes +from nitrostack.cli._pack_metadata import _normalize_dist_name, _pep503_wheel_name + + +def _sha256_record(data: bytes) -> str: + import base64 + import hashlib + + digest = hashlib.sha256(data).digest() + return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + + +def _inject_into_wheel(wheel_path: str, files: Sequence[Tuple[str, str]]) -> None: + """Add extra files to a built wheel and rewrite RECORD so the wheel stays valid.""" + with zipfile.ZipFile(wheel_path, "r") as src: + contents = {name: src.read(name) for name in src.namelist()} + + for arcname, source in files: + posix = arcname.replace("\\", "/") + if posix in contents or not os.path.isfile(source): + continue + with open(source, "rb") as handle: + contents[posix] = handle.read() + + record_name = next((n for n in contents if n.endswith(".dist-info/RECORD")), None) + if record_name: + rows = [] + for name in sorted(contents): + if name == record_name: + continue + data = contents[name] + rows.append(f"{name},{_sha256_record(data)},{len(data)}") + rows.append(f"{record_name},,") + contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8") + + tmp_path = wheel_path + ".tmp" + with zipfile.ZipFile(tmp_path, "w", compression=zipfile.ZIP_DEFLATED) as dest: + for name, data in contents.items(): + dest.writestr(name, data) + os.replace(tmp_path, wheel_path) + + +def _is_valid_wheel(path: str) -> bool: + if not zipfile.is_zipfile(path): + return False + with zipfile.ZipFile(path, "r") as zf: + names = zf.namelist() + has_wheel = any(n.endswith(".dist-info/WHEEL") for n in names) + has_meta = any(n.endswith(".dist-info/METADATA") for n in names) + has_record = any(n.endswith(".dist-info/RECORD") for n in names) + if not (has_wheel and has_meta and has_record): + return False + wheel_name = next(n for n in names if n.endswith(".dist-info/WHEEL")) + body = zf.read(wheel_name).decode("utf-8", errors="replace") + return "Wheel-Version:" in body + + +def _write_purelib_wheel( + src_root: str, + wheel_dir: str, + name: str, + version: str, + deps: Sequence[str], +) -> str: + """Write a PEP 427 py3-none-any wheel from the staged project files.""" + os.makedirs(wheel_dir, exist_ok=True) + dist_name = _pep503_wheel_name(_normalize_dist_name(name)) + display_name = _normalize_dist_name(name) + wheel_filename = f"{dist_name}-{version}-py3-none-any.whl" + wheel_path = os.path.join(wheel_dir, wheel_filename) + dist_info = f"{dist_name}-{version}.dist-info" + + contents = _collect_staging_bytes(src_root) + metadata_lines = [ + "Metadata-Version: 2.1", + f"Name: {display_name}", + f"Version: {version}", + "Summary: Packed NitroStack MCP server", + "Requires-Python: >=3.10", + ] + for dep in deps: + metadata_lines.append(f"Requires-Dist: {dep}") + contents[f"{dist_info}/METADATA"] = ("\n".join(metadata_lines) + "\n").encode("utf-8") + contents[f"{dist_info}/WHEEL"] = ( + "Wheel-Version: 1.0\n" + "Generator: nitrostack-py pack\n" + "Root-Is-Purelib: true\n" + "Tag: py3-none-any\n" + ).encode("utf-8") + + record_name = f"{dist_info}/RECORD" + rows = [] + for arcname in sorted(contents): + data = contents[arcname] + rows.append(f"{arcname},{_sha256_record(data)},{len(data)}") + rows.append(f"{record_name},,") + contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8") + + with zipfile.ZipFile(wheel_path, "w", compression=zipfile.ZIP_DEFLATED) as zf: + for arcname, data in contents.items(): + zf.writestr(arcname, data) + return wheel_path + + +def _setuptools_build_wheel(wheel_dir: str) -> str: + from setuptools.build_meta import build_wheel as setuptools_build_wheel + return setuptools_build_wheel(wheel_dir) + + +def _build_wheel_with_setuptools( + src_root: str, wheel_dir: str, *, build_backend: Callable[[str], str], +) -> Optional[str]: + """Use the setuptools PEP 517 backend when it is importable.""" + os.makedirs(wheel_dir, exist_ok=True) + previous = os.getcwd() + try: + os.chdir(src_root) + filename = build_backend(wheel_dir) + except ImportError as exc: + print(f"Warning: setuptools build backend unavailable, falling back: {exc}") + return None + except Exception as exc: + print(f"Warning: setuptools build failed, falling back: {exc}") + return None + finally: + os.chdir(previous) + path = os.path.join(wheel_dir, filename) + return path if os.path.isfile(path) else None + + +def _build_wheel( + src_root: str, + wheel_dir: str, + name: str, + version: str, + deps: Sequence[str], + *, + build_with_setuptools: Callable[[str, str], Optional[str]], + write_purelib: Callable[[str, str, str, str, Sequence[str]], str], +) -> str: + os.makedirs(wheel_dir, exist_ok=True) + built = build_with_setuptools(src_root, wheel_dir) + if built: + return built + return write_purelib(src_root, wheel_dir, name, version, deps) diff --git a/nitrostack/cli/pack.py b/nitrostack/cli/pack.py index 161b3a4..3d9f815 100644 --- a/nitrostack/cli/pack.py +++ b/nitrostack/cli/pack.py @@ -24,7 +24,6 @@ requirement_name, ) - # Keep the original import surface while implementations live by responsibility. from nitrostack.cli._pack_files import ( _EXCLUDE_DIR_NAMES, _EXCLUDE_NAME_GLOBS, _EXCLUDE_SUFFIXES, @@ -39,130 +38,18 @@ _pep503_wheel_name, _project_name_and_version, _read_text, _requirement_name, _toml_list, requirements_from_project, write_requirements_txt, ) - - -def _sha256_record(data: bytes) -> str: - import base64 - import hashlib - - digest = hashlib.sha256(data).digest() - return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") - - -def _inject_into_wheel(wheel_path: str, files: Sequence[Tuple[str, str]]) -> None: - """Add extra files to a built wheel and rewrite RECORD so the wheel stays valid.""" - with zipfile.ZipFile(wheel_path, "r") as src: - contents = {name: src.read(name) for name in src.namelist()} - - for arcname, source in files: - posix = arcname.replace("\\", "/") - if posix in contents or not os.path.isfile(source): - continue - with open(source, "rb") as handle: - contents[posix] = handle.read() - - record_name = next((n for n in contents if n.endswith(".dist-info/RECORD")), None) - if record_name: - rows = [] - for name in sorted(contents): - if name == record_name: - continue - data = contents[name] - rows.append(f"{name},{_sha256_record(data)},{len(data)}") - rows.append(f"{record_name},,") - contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8") - - tmp_path = wheel_path + ".tmp" - with zipfile.ZipFile(tmp_path, "w", compression=zipfile.ZIP_DEFLATED) as dest: - for name, data in contents.items(): - dest.writestr(name, data) - os.replace(tmp_path, wheel_path) - - -def _is_valid_wheel(path: str) -> bool: - if not zipfile.is_zipfile(path): - return False - with zipfile.ZipFile(path, "r") as zf: - names = zf.namelist() - has_wheel = any(n.endswith(".dist-info/WHEEL") for n in names) - has_meta = any(n.endswith(".dist-info/METADATA") for n in names) - has_record = any(n.endswith(".dist-info/RECORD") for n in names) - if not (has_wheel and has_meta and has_record): - return False - wheel_name = next(n for n in names if n.endswith(".dist-info/WHEEL")) - body = zf.read(wheel_name).decode("utf-8", errors="replace") - return "Wheel-Version:" in body - - -def _write_purelib_wheel( - src_root: str, - wheel_dir: str, - name: str, - version: str, - deps: Sequence[str], -) -> str: - """Write a PEP 427 py3-none-any wheel from the staged project files.""" - os.makedirs(wheel_dir, exist_ok=True) - dist_name = _pep503_wheel_name(_normalize_dist_name(name)) - display_name = _normalize_dist_name(name) - wheel_filename = f"{dist_name}-{version}-py3-none-any.whl" - wheel_path = os.path.join(wheel_dir, wheel_filename) - dist_info = f"{dist_name}-{version}.dist-info" - - contents = _collect_staging_bytes(src_root) - metadata_lines = [ - "Metadata-Version: 2.1", - f"Name: {display_name}", - f"Version: {version}", - "Summary: Packed NitroStack MCP server", - "Requires-Python: >=3.10", - ] - for dep in deps: - metadata_lines.append(f"Requires-Dist: {dep}") - contents[f"{dist_info}/METADATA"] = ("\n".join(metadata_lines) + "\n").encode("utf-8") - contents[f"{dist_info}/WHEEL"] = ( - "Wheel-Version: 1.0\n" - "Generator: nitrostack-py pack\n" - "Root-Is-Purelib: true\n" - "Tag: py3-none-any\n" - ).encode("utf-8") - - record_name = f"{dist_info}/RECORD" - rows = [] - for arcname in sorted(contents): - data = contents[arcname] - rows.append(f"{arcname},{_sha256_record(data)},{len(data)}") - rows.append(f"{record_name},,") - contents[record_name] = ("\n".join(rows) + "\n").encode("utf-8") - - with zipfile.ZipFile(wheel_path, "w", compression=zipfile.ZIP_DEFLATED) as zf: - for arcname, data in contents.items(): - zf.writestr(arcname, data) - return wheel_path - - -def _setuptools_build_wheel(wheel_dir: str) -> str: - from setuptools.build_meta import build_wheel as setuptools_build_wheel - return setuptools_build_wheel(wheel_dir) +from nitrostack.cli import _pack_wheel +from nitrostack.cli._pack_wheel import ( + _inject_into_wheel, _is_valid_wheel, _setuptools_build_wheel, + _sha256_record, _write_purelib_wheel, +) def _build_wheel_with_setuptools(src_root: str, wheel_dir: str) -> Optional[str]: - """Use the setuptools PEP 517 backend when it is importable.""" - os.makedirs(wheel_dir, exist_ok=True) - previous = os.getcwd() - try: - os.chdir(src_root) - filename = _setuptools_build_wheel(wheel_dir) - except ImportError as exc: - print(f"Warning: setuptools build backend unavailable, falling back: {exc}") - return None - except Exception as exc: - print(f"Warning: setuptools build failed, falling back: {exc}") - return None - finally: - os.chdir(previous) - path = os.path.join(wheel_dir, filename) - return path if os.path.isfile(path) else None + """Resolve the backend callback here so existing facade patches still apply.""" + return _pack_wheel._build_wheel_with_setuptools( + src_root, wheel_dir, build_backend=_setuptools_build_wheel, + ) def _build_wheel( @@ -172,11 +59,11 @@ def _build_wheel( version: str, deps: Sequence[str], ) -> str: - os.makedirs(wheel_dir, exist_ok=True) - built = _build_wheel_with_setuptools(src_root, wheel_dir) - if built: - return built - return _write_purelib_wheel(src_root, wheel_dir, name, version, deps) + return _pack_wheel._build_wheel( + src_root, wheel_dir, name, version, deps, + build_with_setuptools=_build_wheel_with_setuptools, + write_purelib=_write_purelib_wheel, + ) def pack_project( From 7c3c9ddcc8f56da1fbc0f309db1e48f60bb684b8 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Sat, 7 Nov 2026 20:04:19 +0530 Subject: [PATCH 116/146] fix(cli): only treat helpers that build a WidgetOptions as widget routes (#116) An unrelated @widget(something("x")) call is no longer taken as a route, so it cannot cause a false 'missing HTML' warning. Helpers are found by parsing the project for functions that build a WidgetOptions (any file), plus WidgetOptions itself. The CLI test moves to tests/test_validate_widgets.py and runs the real command in a subprocess, so tests/test_cli.py stays at its 1589-line baseline. --- nitrostack/cli/validators.py | 36 +++++++++++++++++--- tests/test_cli.py | 16 --------- tests/test_validate_widgets.py | 60 ++++++++++++++++++++++++++++++++-- 3 files changed, 89 insertions(+), 23 deletions(-) diff --git a/nitrostack/cli/validators.py b/nitrostack/cli/validators.py index 469dbbe..a03a252 100644 --- a/nitrostack/cli/validators.py +++ b/nitrostack/cli/validators.py @@ -377,19 +377,39 @@ def validate_module_references(root: str) -> List[ValidationIssue]: _WIDGET_DECORATOR_RE = re.compile(r"""@widget\(\s*["']([^"']+)["']""") _WIDGET_OPTIONS_RE = re.compile(r"""WidgetOptions\(\s*route\s*=\s*["']([^"']+)["']""") # A helper that builds the options from one route: @widget(my_widget("route")) or -# @widget(my_widget(route="route", ...)). A call with other positional arguments is -# skipped, because its first string is not necessarily the route. +# @widget(my_widget(route="route", ...)). Only helpers defined in the project that +# build a WidgetOptions count (see _widget_helper_names), so an unrelated call such as +# @widget(something("x")) is not taken as a route. A call with other positional +# arguments is skipped, because its first string is not necessarily the route. _WIDGET_HELPER_RE = re.compile( - r"""@widget\(\s*[A-Za-z_][\w.]*\(\s*(?:["']([^"']+)["']\s*\)|route\s*=\s*["']([^"']+)["']\s*[,)])""" + r"""@widget\(\s*([A-Za-z_][\w.]*)\(\s*(?:["']([^"']+)["']\s*\)|route\s*=\s*["']([^"']+)["']\s*[,)])""" ) _WIDGET_ROUTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") +def _widget_helper_names(texts: Iterable[str]) -> Set[str]: + """Names of functions that build a ``WidgetOptions``, plus ``WidgetOptions`` itself.""" + names = {"WidgetOptions"} + for text in texts: + try: + tree = ast.parse(text) + except (SyntaxError, ValueError): + continue + for fn in ast.walk(tree): + if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) and any( + isinstance(call, ast.Call) + and getattr(call.func, "id", getattr(call.func, "attr", None)) == "WidgetOptions" + for call in ast.walk(fn) + ): + names.add(fn.name) + return names + def _collect_widget_routes(root: str) -> List[Tuple[str, str]]: found: List[Tuple[str, str]] = [] seen: Set[str] = set() root_abs = os.path.abspath(root) + sources: List[Tuple[str, str]] = [] for path in sorted(_iter_python_files(root)): rel_path = os.path.relpath(path, root_abs) @@ -400,11 +420,17 @@ def _collect_widget_routes(root: str) -> List[Tuple[str, str]]: continue try: - text = _read(path) + sources.append((rel_path, _read(path))) except OSError: continue - helper_routes = [a or b for a, b in _WIDGET_HELPER_RE.findall(text)] + helpers = _widget_helper_names(text for _, text in sources) + for rel_path, text in sources: + helper_routes = [ + positional or keyword + for name, positional, keyword in _WIDGET_HELPER_RE.findall(text) + if name.rsplit(".", 1)[-1] in helpers + ] for route in ( _WIDGET_DECORATOR_RE.findall(text) + _WIDGET_OPTIONS_RE.findall(text) diff --git a/tests/test_cli.py b/tests/test_cli.py index d9e25af..0a7fc3a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1587,19 +1587,3 @@ def test_pack_and_validate_agree_on_bom_dependencies(tmp_path: Path): test_main_dispatches_commands() test_official_templates_map_to_existing_dirs() print("\nAll CLI tests passed.") - - -def test_validate_checks_pizzaz_helper_wrapped_widgets(tmp_path: Path): - import shutil - - project = tmp_path / "pizzaz" - shutil.copytree(Path(__file__).resolve().parents[1] / "nitrostack" / "templates" / "pizzaz", project) - code, output = _invoke_cli(["validate"], project) - assert code == 0 - assert "widget route" not in output - - (project / "widgets" / "out" / "pizza-list.html").unlink() - code, output = _invoke_cli(["validate"], project) - assert "widget route 'pizza-list'" in output - assert "file is missing" in output - assert "pizza-map" not in output and "pizza-shop" not in output diff --git a/tests/test_validate_widgets.py b/tests/test_validate_widgets.py index d90c570..62d5a1c 100644 --- a/tests/test_validate_widgets.py +++ b/tests/test_validate_widgets.py @@ -1,4 +1,6 @@ +import os import shutil +import subprocess import sys from pathlib import Path @@ -91,6 +93,10 @@ def test_validate_project_reports_widget_warnings_only(tmp_path: Path, monkeypat "from nitrostack import WidgetOptions, widget\n\n" "def pizzaz_widget(route: str) -> WidgetOptions:\n" " return WidgetOptions(route=route, prefers_border=True)\n\n" + "class helpers:\n" + " @staticmethod\n" + " def make(route):\n" + " return WidgetOptions(route=route)\n\n" "class T:\n" " @widget(pizzaz_widget('pizza-map'))\n" " def a(self): ...\n\n" @@ -115,12 +121,41 @@ def test_helper_wrapped_route_with_html_passes(tmp_path: Path): def test_helper_call_with_other_positional_arguments_is_not_guessed(tmp_path: Path): - src = "@widget(helper('not-a-route', True))\ndef f(): ...\n" + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def helper(route, flag): return WidgetOptions(route=route)\n" + "@widget(helper('not-a-route', True))\ndef f(): ...\n" + ) assert validate_widgets(str(_project(tmp_path, src))) == [] +def test_unrelated_helper_call_is_not_taken_as_a_route(tmp_path: Path): + # Not defined in the project and never builds a WidgetOptions: no false warning. + src = "@widget(something('x'))\ndef f(): ...\n" + assert validate_widgets(str(_project(tmp_path, src))) == [] + src = "def something(name): return {'n': name}\n@widget(something('x'))\ndef f(): ...\n" + assert validate_widgets(str(_project(tmp_path, src))) == [] + + +def test_helper_defined_in_another_file_is_found(tmp_path: Path): + (tmp_path / "helpers.py").write_text( + "from nitrostack import WidgetOptions\ndef panel(route): return WidgetOptions(route=route)\n", + encoding="utf-8", + ) + src = "from helpers import panel\n@widget(panel('chart'))\ndef f(): ...\n" + issues = validate_widgets(str(_project(tmp_path, src))) + assert len(issues) == 1 and "'chart'" in issues[0].message + + +def test_widget_options_positional_route_is_collected(tmp_path: Path): + src = "from nitrostack import WidgetOptions, widget\n@widget(WidgetOptions('chart'))\ndef f(): ...\n" + issues = validate_widgets(str(_project(tmp_path, src))) + assert len(issues) == 1 and "'chart'" in issues[0].message + + def test_invalid_helper_route_is_reported(tmp_path: Path): - issues = validate_widgets(str(_project(tmp_path, "@widget(helper('../evil'))\ndef f(): ...\n"))) + src = "def helper(r): return WidgetOptions(route=r)\n@widget(helper('../evil'))\ndef f(): ...\n" + issues = validate_widgets(str(_project(tmp_path, src))) assert len(issues) == 1 assert "not a single alphanumeric path segment" in issues[0].message @@ -149,3 +184,24 @@ def test_pizzaz_template_warns_when_a_widget_html_is_removed(tmp_path: Path): issues = validate_widgets(str(project)) assert len(issues) == 1 assert "'pizza-list'" in issues[0].message and "file is missing" in issues[0].message + + +def test_cli_validate_checks_pizzaz_helper_wrapped_widgets(tmp_path: Path): + project = tmp_path / "pizzaz" + shutil.copytree(TEMPLATES / "pizzaz", project) + + def validate(): + return subprocess.run( + [sys.executable, "-m", "nitrostack.cli.main", "validate"], + cwd=project, env={**os.environ, "PYTHONPATH": str(TEMPLATES.parents[1])}, + capture_output=True, text=True, encoding="utf-8", timeout=60, + ) + + clean = validate() + assert clean.returncode == 0, clean.stdout + clean.stderr + assert "widget route" not in clean.stdout + + (project / "widgets" / "out" / "pizza-list.html").unlink() + broken = validate().stdout + assert "widget route 'pizza-list'" in broken and "file is missing" in broken + assert "pizza-map" not in broken and "pizza-shop" not in broken From d0acac8448502c33838e29e59e2bfd1540d90b83 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Sat, 7 Nov 2026 20:11:22 +0530 Subject: [PATCH 117/146] refactor(auth): split oauth.py into types, cache, token and discovery modules (#122) oauth.py was 516 lines. It is now a 280-line facade that keeps OAuthService, OAuthModule and the fail-open warning, and delegates to: - oauth_types: is_oauth_required, generate_www_authenticate_header, _has_secret - oauth_cache: token-result cache get/set - oauth_tokens: JWKS verification, RFC 7662 introspection, audience check - oauth_discovery: the background metadata / registration HTTP server Dependencies run one way (types <- cache/tokens, oauth_module <- discovery, all <- oauth), with no import cycles. Every name oauth.py defined or imported is still importable from it, and OAuthService keeps the same methods and signatures. No behavior change. --- nitrostack/auth/oauth.py | 322 ++++------------------------- nitrostack/auth/oauth_cache.py | 26 +++ nitrostack/auth/oauth_discovery.py | 165 +++++++++++++++ nitrostack/auth/oauth_tokens.py | 121 +++++++++++ nitrostack/auth/oauth_types.py | 44 ++++ 5 files changed, 399 insertions(+), 279 deletions(-) create mode 100644 nitrostack/auth/oauth_cache.py create mode 100644 nitrostack/auth/oauth_discovery.py create mode 100644 nitrostack/auth/oauth_tokens.py create mode 100644 nitrostack/auth/oauth_types.py diff --git a/nitrostack/auth/oauth.py b/nitrostack/auth/oauth.py index 619f51d..0c89073 100644 --- a/nitrostack/auth/oauth.py +++ b/nitrostack/auth/oauth.py @@ -1,57 +1,54 @@ import os import sys -import time -import json -import urllib.request -import urllib.parse +import urllib.parse # noqa: F401 (kept: callers patch nitrostack.auth.oauth.urllib.request) +import urllib.request # noqa: F401 from typing import List, Optional, Dict, Any, Tuple, Union -from http.server import HTTPServer, BaseHTTPRequestHandler +from http.server import HTTPServer import threading from nitrostack.core.module import module from nitrostack.core.di import DIContainer -from nitrostack.auth.secret import SecretValue, unwrap_secret -from nitrostack.auth.oauth_module import ( +from nitrostack.auth.secret import SecretValue +from nitrostack.auth.oauth_types import ( + TokenInfo, + _has_secret, + generate_www_authenticate_header, + is_oauth_required, +) +from nitrostack.auth.oauth_cache import cache_get, cache_set +from nitrostack.auth.oauth_tokens import ( + get_jwks_client, + introspect_via_endpoint, + introspect_via_jwks, + validate_audience, +) +from nitrostack.auth.oauth_discovery import start_discovery_server +# Re-exported only so existing ``from nitrostack.auth.oauth import ...`` lines keep working. +from nitrostack.auth.secret import unwrap_secret # noqa: F401 +from nitrostack.auth.cimd import CimdFetchError, CimdValidationError # noqa: F401 +from nitrostack.auth.oauth_module import ( # noqa: F401 apply_cimd_to_registration_body, build_authorization_server_metadata, build_protected_resource_metadata, build_registration_response, is_client_registration_enabled, ) -from nitrostack.auth.cimd import CimdFetchError, CimdValidationError from nitrostack.core.errors import AudienceMismatchError, ConfigurationError, TokenInactiveError - -def is_oauth_required() -> bool: - """TS ``OAuthModule.isAuthRequired()`` — Studio/local default is off. - - Set ``OAUTH_REQUIRED=true`` to enforce Bearer tokens. Unset/false lets - NitroStudio and Inspector call tools against mock Duffel data. - """ - return (os.environ.get("OAUTH_REQUIRED") or "").strip().lower() == "true" - +# Everything that used to live in this module is still importable from it. The +# implementation is split by responsibility: oauth_types (helpers), oauth_cache, +# oauth_tokens (validation), oauth_discovery (metadata server). This module keeps +# OAuthService, OAuthModule and the fail-open warning state. +__all__ = [ + "OAuthModule", + "OAuthService", + "generate_www_authenticate_header", + "is_oauth_required", + "warn_if_oauth_fail_open", +] _oauth_fail_open_warned = False -def generate_www_authenticate_header( - *, - realm: str = "mcp", - resource_metadata: Optional[str] = None, - error: Optional[str] = None, - error_description: Optional[str] = None, -) -> str: - """RFC 6750 / RFC 9728 WWW-Authenticate value for protected MCP resources.""" - parts = [f'Bearer realm="{realm}"'] - if resource_metadata: - parts.append(f'resource_metadata="{resource_metadata}"') - if error: - parts.append(f'error="{error}"') - if error_description: - escaped = error_description.replace('"', "'") - parts.append(f'error_description="{escaped}"') - return ", ".join(parts) - - def warn_if_oauth_fail_open() -> None: """Loud warning when OAuth is wired but tokens are not enforced.""" global _oauth_fail_open_warned @@ -65,12 +62,6 @@ def warn_if_oauth_fail_open() -> None: ) sys.stderr.flush() -def _has_secret(value: Any) -> bool: - """True when a secret was given. A SecretValue counts even if it holds no value (it is - falsy after pickling), so it is never silently replaced by an environment variable; - unwrapping it raises instead.""" - return isinstance(value, SecretValue) or bool(value) - class OAuthService: def __init__( @@ -154,143 +145,7 @@ def __init__( def start_discovery_server(self) -> None: """Starts a background HTTP discovery server for OAuth Protected Resource metadata.""" - if self._server is not None: - return - - service_instance = self - registration_path = "/oauth/v2/register" - - def _write_json(handler: BaseHTTPRequestHandler, status: int, payload: Dict[str, Any]) -> None: - raw = json.dumps(payload).encode("utf-8") - handler.send_response(status) - handler.send_header("Content-Type", "application/json") - handler.send_header("Content-Length", str(len(raw))) - handler.send_header("Connection", "close") - handler.end_headers() - handler.wfile.write(raw) - - def _write_empty(handler: BaseHTTPRequestHandler, status: int) -> None: - handler.send_response(status) - handler.send_header("Content-Length", "0") - handler.send_header("Connection", "close") - handler.end_headers() - - class DiscoveryHandler(BaseHTTPRequestHandler): - def log_message(self, format, *args): - # Suppress server logging to stdout/stderr to keep stdio clean - pass - - def do_OPTIONS(self): - # TS discovery handlers honor CORS preflight without leaking credentials. - self.send_response(200) - self.send_header("Access-Control-Allow-Origin", "*") - self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") - self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization") - self.send_header("Content-Length", "0") - self.send_header("Connection", "close") - self.end_headers() - - def _proxy_headers(self) -> Dict[str, str]: - return {key: value for key, value in self.headers.items()} - - def _proxy_peer(self) -> Optional[str]: - return self.client_address[0] if self.client_address else None - - def _trusted_public_origin(self) -> Optional[str]: - from nitrostack.transports.proxy import public_origin, trusted_forwarded_host - - headers = self._proxy_headers() - peer = self._proxy_peer() - if not trusted_forwarded_host(headers, peer): - return None - return public_origin( - headers, - peer, - fallback_host=f"localhost:{service_instance.discovery_port}", - fallback_proto="http", - ) - - def do_GET(self): - if self.path == "/.well-known/oauth-protected-resource": - _write_json(self, 200, build_protected_resource_metadata(service_instance)) - elif self.path == "/.well-known/oauth-authorization-server": - origin = self._trusted_public_origin() - registration_endpoint = ( - registration_path if is_client_registration_enabled(service_instance) else None - ) - _write_json( - self, - 200, - build_authorization_server_metadata( - service_instance, - registration_endpoint, - public_origin=origin, - ), - ) - else: - _write_empty(self, 404) - - def do_POST(self): - if self.path != registration_path: - _write_empty(self, 404) - return - - if not is_client_registration_enabled(service_instance): - _write_json( - self, - 404, - {"error": "not_found", "error_description": "Client registration is not enabled"}, - ) - return - - length = int(self.headers.get("Content-Length", 0)) - raw_body = self.rfile.read(length) if length else b"" - try: - body = json.loads(raw_body.decode("utf-8")) if raw_body else {} - except Exception: - body = {} - - try: - body = apply_cimd_to_registration_body( - body, - headers=self._proxy_headers(), - peer=self._proxy_peer(), - ) - except (CimdValidationError, CimdFetchError) as exc: - _write_json( - self, - 400, - { - "error": "invalid_client_metadata", - "error_description": str(exc), - }, - ) - return - - _write_json(self, 200, build_registration_response(service_instance, body)) - - def run_server(): - # Try binding to OAUTH_DISCOVERY_PORT - port = int(os.environ.get("OAUTH_DISCOVERY_PORT", self.discovery_port)) - try: - self._server = HTTPServer(("localhost", port), DiscoveryHandler) - # Notify client via stderr - oauth_metadata = { - "port": port, - "resource_uri": self.resource_uri, - "authorization_servers": self.authorization_servers - } - sys.stderr.write( - f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n" - ) - sys.stderr.flush() - self._server.serve_forever() - except Exception as e: - sys.stderr.write(f"Failed to start OAuth Discovery Server on port {port}: {e}\n") - sys.stderr.flush() - - self._thread = threading.Thread(target=run_server, daemon=True) - self._thread.start() + start_discovery_server(self) def raise_if_invalid(self, token_info: Dict[str, Any]) -> Dict[str, Any]: """Raise ``TokenInactiveError`` / ``AudienceMismatchError`` for an introspection result.""" @@ -352,118 +207,27 @@ async def introspect_token(self, token: str) -> Dict[str, Any]: def _introspect_via_jwks(self, token: str) -> Dict[str, Any]: """JWT signature verification using a cached JWKS client (RFC 7517/7519).""" - try: - import jwt - jwks_client = self._get_jwks_client(self.jwks_uri) - signing_key = jwks_client.get_signing_key_from_jwt(token) - - data = jwt.decode( - token, - signing_key.key, - algorithms=["RS256"], - audience=self.audience, - issuer=self.issuer, - ) - return { - "active": True, - "scope": data.get("scope", ""), - "sub": data.get("sub"), - "client_id": data.get("client_id"), - "aud": data.get("aud"), - "exp": data.get("exp"), - "iat": data.get("iat"), - "iss": data.get("iss"), - } - except Exception as e: - sys.stderr.write(f"OAuth JWKS verification failed: {e}\n") - sys.stderr.flush() - return {"active": False} + return introspect_via_jwks(self, token) async def _introspect_via_endpoint(self, token: str) -> Dict[str, Any]: """RFC 7662 token introspection: POST the token to the authorization server and ask whether it's active.""" - data = urllib.parse.urlencode({"token": token}).encode("utf-8") - req = urllib.request.Request(self.token_introspection_endpoint, data=data, method="POST") - req.add_header("Content-Type", "application/x-www-form-urlencoded") - - # Add basic auth if client credentials provided - if self.token_introspection_client_id and _has_secret(self.token_introspection_client_secret): - import base64 - client_secret = unwrap_secret(self.token_introspection_client_secret) - auth_str = f"{self.token_introspection_client_id}:{client_secret}" - encoded_auth = base64.b64encode(auth_str.encode("utf-8")).decode("utf-8") - req.add_header("Authorization", f"Basic {encoded_auth}") - - try: - # urllib.request is synchronous; run it on a thread so it doesn't block - # the event loop this async method is running on. - import asyncio - loop = asyncio.get_event_loop() - - def do_request(): - with urllib.request.urlopen(req, timeout=5) as response: - return json.loads(response.read().decode("utf-8")) - - return await loop.run_in_executor(None, do_request) - except Exception as e: - sys.stderr.write(f"OAuth Introspection Request Failed: {e}\n") - sys.stderr.flush() - return {"active": False} + return await introspect_via_endpoint(self, token) def _get_jwks_client(self, jwks_uri: str): - """Return a cached PyJWKClient for this URI, creating it on first use. - - PyJWKClient already caches individual signing keys internally; this cache - is one level up — it avoids reconstructing the client object itself (and - re-fetching the whole key set) on every single token check. - """ - import jwt - client = self._jwks_clients.get(jwks_uri) - if client is None: - client = jwt.PyJWKClient(jwks_uri) - self._jwks_clients[jwks_uri] = client - return client + """Return a cached PyJWKClient for this URI, creating it on first use.""" + return get_jwks_client(self, jwks_uri) def _validate_audience(self, introspection: Dict[str, Any]) -> bool: - """ - RFC 8707 resource-indicator check: does this token's `aud` claim include - the resource it's being presented to? Without this, a token minted for a - *different* service could be replayed here and accepted — the token is - legitimately signed/active, just not meant for this resource. - - `aud` is legal as either a single string or a list of strings per JWT - conventions, so it's normalized to a list before comparing. - """ - expected = self.audience or self.resource_uri - if not expected: - # Nothing configured to check against — permissive, matching the - # TypeScript SDK's default when no audience is configured. - return True - - raw_aud = introspection.get("aud") - if raw_aud is None: - # No audience claim on the token at all — nothing to validate against. - # Treat as permissive rather than rejecting tokens from authorization - # servers that don't emit `aud`. - return True - - token_audiences = raw_aud if isinstance(raw_aud, list) else [raw_aud] - return expected in token_audiences + """RFC 8707 resource-indicator check on the token's ``aud`` claim.""" + return validate_audience(self, introspection) def _cache_get(self, token: str) -> Optional[Dict[str, Any]]: - cached = self._token_cache.get(token) - if cached is None: - return None - result, expires_at = cached - if time.monotonic() >= expires_at: - del self._token_cache[token] - return None - return result + return cache_get(self._token_cache, token) def _cache_set(self, token: str, result: Dict[str, Any]) -> None: - if self.token_cache_seconds <= 0: - return - self._token_cache[token] = (result, time.monotonic() + self.token_cache_seconds) + cache_set(self._token_cache, token, result, self.token_cache_seconds) + @module(name="OAuthModule") class OAuthModule: diff --git a/nitrostack/auth/oauth_cache.py b/nitrostack/auth/oauth_cache.py new file mode 100644 index 0000000..f8d5981 --- /dev/null +++ b/nitrostack/auth/oauth_cache.py @@ -0,0 +1,26 @@ +"""Token-result cache operations. Depends only on ``oauth_types``.""" + +import time +from typing import Dict, Optional, Tuple + +from nitrostack.auth.oauth_types import TokenInfo + +# token -> (introspection result, monotonic expiry) +TokenCacheStore = Dict[str, Tuple[TokenInfo, float]] + + +def cache_get(store: TokenCacheStore, token: str) -> Optional[TokenInfo]: + cached = store.get(token) + if cached is None: + return None + result, expires_at = cached + if time.monotonic() >= expires_at: + del store[token] + return None + return result + + +def cache_set(store: TokenCacheStore, token: str, result: TokenInfo, ttl_seconds: int) -> None: + if ttl_seconds <= 0: + return + store[token] = (result, time.monotonic() + ttl_seconds) diff --git a/nitrostack/auth/oauth_discovery.py b/nitrostack/auth/oauth_discovery.py new file mode 100644 index 0000000..1d56f0b --- /dev/null +++ b/nitrostack/auth/oauth_discovery.py @@ -0,0 +1,165 @@ +"""Background HTTP discovery server (OAuth protected-resource and authorization-server +metadata, plus the simplified dynamic client registration endpoint). + +Depends on ``oauth_module`` and ``cimd`` for the payloads; it never imports ``oauth``. +""" + +import json +import os +import sys +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import TYPE_CHECKING, Any, Dict, Optional + +from nitrostack.auth.cimd import CimdFetchError, CimdValidationError +from nitrostack.auth.oauth_module import ( + apply_cimd_to_registration_body, + build_authorization_server_metadata, + build_protected_resource_metadata, + build_registration_response, + is_client_registration_enabled, +) + +if TYPE_CHECKING: + from nitrostack.auth.oauth import OAuthService + + +def start_discovery_server(service: "OAuthService") -> None: + """Starts a background HTTP discovery server for OAuth Protected Resource metadata.""" + if service._server is not None: + return + + service_instance = service + registration_path = "/oauth/v2/register" + + def _write_json(handler: BaseHTTPRequestHandler, status: int, payload: Dict[str, Any]) -> None: + raw = json.dumps(payload).encode("utf-8") + handler.send_response(status) + handler.send_header("Content-Type", "application/json") + handler.send_header("Content-Length", str(len(raw))) + handler.send_header("Connection", "close") + handler.end_headers() + handler.wfile.write(raw) + + def _write_empty(handler: BaseHTTPRequestHandler, status: int) -> None: + handler.send_response(status) + handler.send_header("Content-Length", "0") + handler.send_header("Connection", "close") + handler.end_headers() + + class DiscoveryHandler(BaseHTTPRequestHandler): + def log_message(self, format, *args): + # Suppress server logging to stdout/stderr to keep stdio clean + pass + + def do_OPTIONS(self): + # TS discovery handlers honor CORS preflight without leaking credentials. + self.send_response(200) + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization") + self.send_header("Content-Length", "0") + self.send_header("Connection", "close") + self.end_headers() + + def _proxy_headers(self) -> Dict[str, str]: + return {key: value for key, value in self.headers.items()} + + def _proxy_peer(self) -> Optional[str]: + return self.client_address[0] if self.client_address else None + + def _trusted_public_origin(self) -> Optional[str]: + from nitrostack.transports.proxy import public_origin, trusted_forwarded_host + + headers = self._proxy_headers() + peer = self._proxy_peer() + if not trusted_forwarded_host(headers, peer): + return None + return public_origin( + headers, + peer, + fallback_host=f"localhost:{service_instance.discovery_port}", + fallback_proto="http", + ) + + def do_GET(self): + if self.path == "/.well-known/oauth-protected-resource": + _write_json(self, 200, build_protected_resource_metadata(service_instance)) + elif self.path == "/.well-known/oauth-authorization-server": + origin = self._trusted_public_origin() + registration_endpoint = ( + registration_path if is_client_registration_enabled(service_instance) else None + ) + _write_json( + self, + 200, + build_authorization_server_metadata( + service_instance, + registration_endpoint, + public_origin=origin, + ), + ) + else: + _write_empty(self, 404) + + def do_POST(self): + if self.path != registration_path: + _write_empty(self, 404) + return + + if not is_client_registration_enabled(service_instance): + _write_json( + self, + 404, + {"error": "not_found", "error_description": "Client registration is not enabled"}, + ) + return + + length = int(self.headers.get("Content-Length", 0)) + raw_body = self.rfile.read(length) if length else b"" + try: + body = json.loads(raw_body.decode("utf-8")) if raw_body else {} + except Exception: + body = {} + + try: + body = apply_cimd_to_registration_body( + body, + headers=self._proxy_headers(), + peer=self._proxy_peer(), + ) + except (CimdValidationError, CimdFetchError) as exc: + _write_json( + self, + 400, + { + "error": "invalid_client_metadata", + "error_description": str(exc), + }, + ) + return + + _write_json(self, 200, build_registration_response(service_instance, body)) + + def run_server(): + # Try binding to OAUTH_DISCOVERY_PORT + port = int(os.environ.get("OAUTH_DISCOVERY_PORT", service.discovery_port)) + try: + service._server = HTTPServer(("localhost", port), DiscoveryHandler) + # Notify client via stderr + oauth_metadata = { + "port": port, + "resource_uri": service.resource_uri, + "authorization_servers": service.authorization_servers + } + sys.stderr.write( + f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n" + ) + sys.stderr.flush() + service._server.serve_forever() + except Exception as e: + sys.stderr.write(f"Failed to start OAuth Discovery Server on port {port}: {e}\n") + sys.stderr.flush() + + service._thread = threading.Thread(target=run_server, daemon=True) + service._thread.start() diff --git a/nitrostack/auth/oauth_tokens.py b/nitrostack/auth/oauth_tokens.py new file mode 100644 index 0000000..c7d50cc --- /dev/null +++ b/nitrostack/auth/oauth_tokens.py @@ -0,0 +1,121 @@ +"""Token validation: JWKS verification, RFC 7662 introspection and audience checks. + +Each function takes the ``OAuthService`` whose settings it uses. Depends only on +``oauth_types`` (and ``secret``); it never imports ``oauth``. +""" + +import json +import sys +import urllib.parse +import urllib.request +from typing import TYPE_CHECKING, Any + +from nitrostack.auth.oauth_types import TokenInfo, _has_secret +from nitrostack.auth.secret import unwrap_secret + +if TYPE_CHECKING: + from nitrostack.auth.oauth import OAuthService + + +def get_jwks_client(service: "OAuthService", jwks_uri: str) -> Any: + """Return a cached PyJWKClient for this URI, creating it on first use. + + PyJWKClient already caches individual signing keys internally; this cache + is one level up — it avoids reconstructing the client object itself (and + re-fetching the whole key set) on every single token check. + """ + import jwt + client = service._jwks_clients.get(jwks_uri) + if client is None: + client = jwt.PyJWKClient(jwks_uri) + service._jwks_clients[jwks_uri] = client + return client + + +def introspect_via_jwks(service: "OAuthService", token: str) -> TokenInfo: + """JWT signature verification using a cached JWKS client (RFC 7517/7519).""" + try: + import jwt + jwks_client = service._get_jwks_client(service.jwks_uri) + signing_key = jwks_client.get_signing_key_from_jwt(token) + + data = jwt.decode( + token, + signing_key.key, + algorithms=["RS256"], + audience=service.audience, + issuer=service.issuer, + ) + return { + "active": True, + "scope": data.get("scope", ""), + "sub": data.get("sub"), + "client_id": data.get("client_id"), + "aud": data.get("aud"), + "exp": data.get("exp"), + "iat": data.get("iat"), + "iss": data.get("iss"), + } + except Exception as e: + sys.stderr.write(f"OAuth JWKS verification failed: {e}\n") + sys.stderr.flush() + return {"active": False} + + +async def introspect_via_endpoint(service: "OAuthService", token: str) -> TokenInfo: + """RFC 7662 token introspection: POST the token to the authorization server + and ask whether it's active.""" + data = urllib.parse.urlencode({"token": token}).encode("utf-8") + req = urllib.request.Request(service.token_introspection_endpoint, data=data, method="POST") + req.add_header("Content-Type", "application/x-www-form-urlencoded") + + # Add basic auth if client credentials provided + if service.token_introspection_client_id and _has_secret(service.token_introspection_client_secret): + import base64 + client_secret = unwrap_secret(service.token_introspection_client_secret) + auth_str = f"{service.token_introspection_client_id}:{client_secret}" + encoded_auth = base64.b64encode(auth_str.encode("utf-8")).decode("utf-8") + req.add_header("Authorization", f"Basic {encoded_auth}") + + try: + # urllib.request is synchronous; run it on a thread so it doesn't block + # the event loop this async method is running on. + import asyncio + loop = asyncio.get_event_loop() + + def do_request(): + with urllib.request.urlopen(req, timeout=5) as response: + return json.loads(response.read().decode("utf-8")) + + return await loop.run_in_executor(None, do_request) + except Exception as e: + sys.stderr.write(f"OAuth Introspection Request Failed: {e}\n") + sys.stderr.flush() + return {"active": False} + + +def validate_audience(service: "OAuthService", introspection: TokenInfo) -> bool: + """ + RFC 8707 resource-indicator check: does this token's `aud` claim include + the resource it's being presented to? Without this, a token minted for a + *different* service could be replayed here and accepted — the token is + legitimately signed/active, just not meant for this resource. + + `aud` is legal as either a single string or a list of strings per JWT + conventions, so it's normalized to a list before comparing. + """ + expected = service.audience or service.resource_uri + if not expected: + # Nothing configured to check against — permissive, matching the + # TypeScript SDK's default when no audience is configured. + return True + + raw_aud = introspection.get("aud") + if raw_aud is None: + # No audience claim on the token at all — nothing to validate against. + # Treat as permissive rather than rejecting tokens from authorization + # servers that don't emit `aud`. + return True + + token_audiences = raw_aud if isinstance(raw_aud, list) else [raw_aud] + return expected in token_audiences diff --git a/nitrostack/auth/oauth_types.py b/nitrostack/auth/oauth_types.py new file mode 100644 index 0000000..0b91076 --- /dev/null +++ b/nitrostack/auth/oauth_types.py @@ -0,0 +1,44 @@ +"""Shared OAuth helpers and types. A leaf module: it imports no other OAuth module.""" + +import os +from typing import Any, Dict, Optional + +from nitrostack.auth.secret import SecretValue + +# RFC 7662 introspection result: ``{"active": bool, ...claims}``. +TokenInfo = Dict[str, Any] + + +def is_oauth_required() -> bool: + """TS ``OAuthModule.isAuthRequired()`` — Studio/local default is off. + + Set ``OAUTH_REQUIRED=true`` to enforce Bearer tokens. Unset/false lets + NitroStudio and Inspector call tools against mock Duffel data. + """ + return (os.environ.get("OAUTH_REQUIRED") or "").strip().lower() == "true" + + +def generate_www_authenticate_header( + *, + realm: str = "mcp", + resource_metadata: Optional[str] = None, + error: Optional[str] = None, + error_description: Optional[str] = None, +) -> str: + """RFC 6750 / RFC 9728 WWW-Authenticate value for protected MCP resources.""" + parts = [f'Bearer realm="{realm}"'] + if resource_metadata: + parts.append(f'resource_metadata="{resource_metadata}"') + if error: + parts.append(f'error="{error}"') + if error_description: + escaped = error_description.replace('"', "'") + parts.append(f'error_description="{escaped}"') + return ", ".join(parts) + + +def _has_secret(value: Any) -> bool: + """True when a secret was given. A SecretValue counts even if it holds no value (it is + falsy after pickling), so it is never silently replaced by an environment variable; + unwrapping it raises instead.""" + return isinstance(value, SecretValue) or bool(value) From 2abfea0053e4bbb95c1eec89898230776ab93b69 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Sat, 7 Nov 2026 20:18:32 +0530 Subject: [PATCH 118/146] refactor(widgets): split route templates and views by widget family (#121) route_templates.py (870 lines) and views.py (569 lines) are now small route dispatchers. The per-widget code moved, unchanged, into: - views_common / views_pizza / views_flight: widget bodies - route_templates_generic / _pizza / _flight: CSS, render JS and page builders Dependencies run one way (views_common <- views_pizza, views_* <- views <- route_templates_* <- route_templates), with no import cycles. Every name the two old modules defined or imported is still importable from them, and the rendered HTML is byte-for-byte identical. --- nitrostack/widgets/route_templates.py | 881 ++---------------- nitrostack/widgets/route_templates_flight.py | 357 +++++++ nitrostack/widgets/route_templates_generic.py | 206 ++++ nitrostack/widgets/route_templates_pizza.py | 303 ++++++ nitrostack/widgets/views.py | 557 +---------- nitrostack/widgets/views_common.py | 131 +++ nitrostack/widgets/views_flight.py | 273 ++++++ nitrostack/widgets/views_pizza.py | 155 +++ 8 files changed, 1514 insertions(+), 1349 deletions(-) create mode 100644 nitrostack/widgets/route_templates_flight.py create mode 100644 nitrostack/widgets/route_templates_generic.py create mode 100644 nitrostack/widgets/route_templates_pizza.py create mode 100644 nitrostack/widgets/views_common.py create mode 100644 nitrostack/widgets/views_flight.py create mode 100644 nitrostack/widgets/views_pizza.py diff --git a/nitrostack/widgets/route_templates.py b/nitrostack/widgets/route_templates.py index 6b36120..b8fb7cd 100644 --- a/nitrostack/widgets/route_templates.py +++ b/nitrostack/widgets/route_templates.py @@ -1,833 +1,64 @@ -"""Built-in per-route widget HTML generated by Python (no npm/React build).""" +"""Built-in per-route widget HTML generated by Python (no npm/React build). -from __future__ import annotations - -from typing import Any, Callable, Dict, Optional - -from nitrostack.widgets.host_bridge import wrap_widget_page -from nitrostack.widgets.views import missing_body, render_body - - -def _generic_render_js() -> str: - return """ -window.__nitroWidgetRender = function(data) { - const root = document.getElementById("root"); - const meta = document.getElementById("meta"); - if (!root) return; - if (!data) { - if (meta) meta.textContent = "Waiting for tool result (host injects tool output)."; - return; - } - if (meta) meta.textContent = "Tool output"; - root.innerHTML = ""; - const pre = document.createElement("pre"); - pre.textContent = JSON.stringify(data, null, 2); - root.appendChild(pre); -}; -""".strip() - - -_PIZZA_LIST_CSS = """ - :root { --ns-accent: #ea580c; --ns-accent-soft: #ffedd5; } - .shop { min-width: 260px; max-width: 260px; scroll-snap-align: start; flex-shrink: 0; } - .img { width: 100%; height: 120px; object-fit: cover; border-radius: 10px; margin-bottom: 8px; background: var(--ns-accent-soft); } - .row { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; } - .name { font-weight: 700; } - .addr { color: var(--ns-muted); font-size: 0.85rem; margin-top: 4px; } -""" - -_PIZZA_MAP_CSS = """ - :root { --ns-accent: #ea580c; } - html, body { width: 100%; height: 560px; } - body { position: relative; min-height: 560px; background: #e5e7eb; } - .meta { position: absolute; top: 12px; left: 12px; z-index: 3; margin: 0; - background: color-mix(in srgb, var(--ns-surface) 92%, transparent); border-radius: 8px; padding: 6px 10px; - box-shadow: var(--ns-shadow); } - .map { position: absolute; inset: 0; width: 100%; height: 560px; min-height: 560px; } - .map-live { position: absolute; inset: 0; } - .static-map { position: absolute; inset: 0; z-index: 1; width: 100%; height: 560px; - object-fit: cover; transition: opacity .4s ease; } - .static-map.is-ready { opacity: 0; pointer-events: none; } - .mapboxgl-map { width: 100%; height: 100%; } - .cards { position: absolute; left: 16px; right: 16px; bottom: 8px; z-index: 3; } - .map-card { min-width: 220px; max-width: 220px; flex-shrink: 0; scroll-snap-align: start; } - .map-card .name { font-weight: 700; } - .map-card .muted { margin-top: 4px; } - .map-card .rating { margin-top: 4px; } -""" - -_PIZZA_SHOP_CSS = """ - :root { --ns-accent: #e11d48; --ns-accent-soft: #ffe4e6; } - .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 16px; border: 1px solid var(--ns-border); } - .hero { width: 100%; max-height: 180px; object-fit: cover; border-radius: 10px; margin-bottom: 12px; } - .chips { margin-top: 10px; } - .chip { margin: 0 4px 4px 0; } -""" - -_CALC_CSS = """ - :root { --ns-accent: #15803d; } - .card { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 20px; text-align: center; } - .expr { font-size: 0.95rem; color: var(--ns-muted); margin-bottom: 8px; } - .result { font-size: 2rem; font-weight: 800; color: var(--ns-accent); } -""" - -_CARD_CSS = """ - .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 20px; box-shadow: var(--ns-shadow); max-width: 320px; border: 1px solid var(--ns-border); } - .card h2 { margin: 0 0 8px; font-size: 1.25rem; } - .price { font-size: 1.5rem; } - .desc { color: var(--ns-muted); margin-top: 8px; } -""" - -_TABLE_CSS = """ - table { border-collapse: collapse; width: 100%; max-width: 480px; background: var(--ns-surface); border-radius: 10px; overflow: hidden; } - th, td { border: 1px solid var(--ns-border); padding: 8px 12px; text-align: left; } - th { background: var(--ns-accent-soft); } -""" - -_CHART_CSS = """ - .chart { display: flex; align-items: flex-end; gap: 8px; height: 160px; } - .bar-wrap { flex: 1; display: flex; flex-direction: column; align-items: center; } - .bar { width: 100%; background: var(--ns-accent, #3b82f6); border-radius: 4px 4px 0 0; min-height: 4px; } - .label { font-size: 12px; margin-top: 4px; color: var(--ns-muted); } +This module is the route dispatcher. The templates live in route_templates_generic, +route_templates_pizza and route_templates_flight and are re-exported here, so existing +imports keep working. """ -_FLIGHT_CSS = """ - :root { --ns-accent: #0369a1; --ns-accent-soft: #e0f2fe; } - .offer, .card, #list .row { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 12px; margin-bottom: 10px; } - .row { display: flex; gap: 12px; align-items: center; } - .id { font-size: 0.8rem; color: var(--ns-muted); } - .code { font-size: 1.1rem; font-weight: 800; min-width: 3rem; } - .slice { margin-top: 8px; } - .seat-row { display: flex; gap: 6px; align-items: center; margin: 4px 0; } - .rn { width: 2rem; font-size: 0.8rem; color: var(--ns-muted); } - .seat { display: inline-block; min-width: 2.4rem; text-align: center; padding: 4px; border-radius: 6px; font-size: 0.75rem; } -""" - -_GENERIC_CSS = """ - pre { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: 8px; padding: 12px; overflow: auto; } -""" - -_MISSING_CSS = """ - :root { --ns-bg: #fef2f2; --ns-text: #7f1d1d; } - .meta { font-size: 0.9rem; line-height: 1.5; } -""" - -_PIZZA_LIST_JS = """ -window.__nitroWidgetRender = function(data) { - const list = document.getElementById("list"); - const meta = document.getElementById("meta"); - if (!list || !meta) return; - list.innerHTML = ""; - if (!data || !Array.isArray(data.shops)) { - meta.textContent = "Waiting for show_pizza_list result."; - return; - } - const state = (window.openai && window.openai.widgetState) || {}; - const sort = state.sort || "rating"; - const shops = data.shops.slice().sort(function(a, b) { - if (sort === "name") return String(a.name || "").localeCompare(String(b.name || "")); - return (b.rating || 0) - (a.rating || 0); - }); - document.querySelectorAll("#sorts [data-sort]").forEach(function(btn) { - btn.classList.toggle("is-on", btn.getAttribute("data-sort") === sort); - }); - const total = data.totalShops ?? data.shops.length; - meta.textContent = total + " shop" + (total === 1 ? "" : "s"); - if (!shops.length) { - list.innerHTML = '
No shops match these filters.
'; - return; - } - shops.forEach(function(shop) { - const el = document.createElement("article"); - el.className = "shop ns-card"; - el.setAttribute("data-call-tool", "show_pizza_shop"); - el.setAttribute("data-args", JSON.stringify({ shopId: shop.id || "" })); - el.setAttribute("role", "button"); - el.tabIndex = 0; - const open = shop.openNow - ? 'Open' - : 'Closed'; - const price = "$".repeat(shop.priceLevel || 1); - let img = ""; - if (shop.image) { - img = ''; - } - el.innerHTML = - img + - '
' + - '
' + open + '
'; - el.querySelector(".name").textContent = shop.name || shop.id || "Shop"; - el.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : ""; - el.querySelector(".addr").textContent = shop.address || ""; - el.querySelector(".price").textContent = price; - list.appendChild(el); - }); -}; -document.addEventListener("click", function(ev) { - const btn = ev.target.closest("#sorts [data-sort]"); - if (!btn || !window.nitrostack) return; - const next = Object.assign({}, (window.openai && window.openai.widgetState) || {}, { - sort: btn.getAttribute("data-sort") - }); - window.nitrostack.setWidgetState(next); - if (typeof window.__nitroWidgetRender === "function" && window.nitrostack.readHostData) { - window.__nitroWidgetRender(window.nitrostack.readHostData()); - } -}); -""".strip() - -_MAPBOX_HEAD = """ - - -""".strip() - - -def _pizza_map_js() -> str: - import json - - from nitrostack.widgets.html_util import get_mapbox_token - - token = json.dumps(get_mapbox_token()) - return f""" -window.__NITRO_MAPBOX_TOKEN = {token}; -window.__nitroWidgetRender = function(data) {{ - const meta = document.getElementById("meta"); - const mapEl = document.getElementById("map-live") || document.getElementById("map"); - const cards = document.getElementById("cards"); - const staticEl = document.getElementById("static-map"); - if (!mapEl) return; - if (!data || !Array.isArray(data.shops) || !data.shops.length) {{ - if (meta) meta.textContent = "Waiting for show_pizza_map result."; - return; - }} - const shops = data.shops.filter(function(s) {{ return Array.isArray(s.coords) && s.coords.length === 2; }}); - const sig = (data.filter || "all") + "|" + shops.map(function(s) {{ - return (s.id || "") + ":" + s.coords[0] + "," + s.coords[1]; - }}).join(";"); - if (window.__nitroMapSig === sig && window.__nitroMap) return; - if (meta) meta.textContent = (data.totalShops ?? data.shops.length) + " shops · filter: " + (data.filter || "all"); - if (cards && !cards.querySelector(".map-card")) {{ - data.shops.forEach(function(shop) {{ - const card = document.createElement("article"); - card.className = "map-card ns-card"; - card.setAttribute("data-shop-id", shop.id || ""); - card.setAttribute("data-call-tool", "show_pizza_shop"); - card.setAttribute("data-args", JSON.stringify({{ shopId: shop.id || "" }})); - card.setAttribute("role", "button"); - card.tabIndex = 0; - card.innerHTML = '
'; - card.querySelector(".name").textContent = shop.name || shop.id || "Shop"; - card.querySelector(".muted").textContent = shop.address || ""; - card.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : ""; - cards.appendChild(card); - }}); - }} - function revealLive() {{ - if (staticEl) staticEl.classList.add("is-ready"); - }} - function mountMap(attempt) {{ - if (window.__nitroMapSig === sig && window.__nitroMap) return; - if (!window.__NITRO_MAPBOX_TOKEN) {{ - if (meta) meta.textContent = "Set MAPBOX_TOKEN in .env to load the map."; - if (mapEl) {{ - mapEl.innerHTML = '
Set MAPBOX_TOKEN in .env (Mapbox public pk. token) to load the map.
'; - }} - return; - }} - if (typeof mapboxgl === "undefined") {{ - if ((attempt || 0) < 80) {{ - setTimeout(function() {{ mountMap((attempt || 0) + 1); }}, 50); - }} - return; - }} - window.__nitroMapSig = sig; - if (window.__nitroMap) {{ - window.__nitroMap.remove(); - window.__nitroMap = null; - }} - mapboxgl.accessToken = window.__NITRO_MAPBOX_TOKEN; - const first = (shops[0] && shops[0].coords) || [-122.4194, 37.7749]; - const map = new mapboxgl.Map({{ - container: mapEl, - style: "mapbox://styles/mapbox/streets-v12", - center: first, - zoom: 12, - cooperativeGestures: false, - fadeDuration: 0 - }}); - map.addControl(new mapboxgl.NavigationControl({{ showCompass: false }}), "top-right"); - map.addControl(new mapboxgl.FullscreenControl(), "top-right"); - shops.forEach(function(shop) {{ - const el = document.createElement("div"); - el.style.backgroundImage = "url(https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png)"; - el.style.width = "30px"; - el.style.height = "40px"; - el.style.backgroundSize = "100%"; - el.style.cursor = "pointer"; - el.title = shop.name || shop.id || ""; - el.addEventListener("click", function() {{ - if (window.nitrostack) window.nitrostack.callTool("show_pizza_shop", {{ shopId: shop.id || "" }}); - }}); - new mapboxgl.Marker(el).setLngLat(shop.coords).addTo(map); - }}); - if (shops.length > 1) {{ - const bounds = new mapboxgl.LngLatBounds(); - shops.forEach(function(s) {{ bounds.extend(s.coords); }}); - map.fitBounds(bounds, {{ padding: 60, maxZoom: 14, duration: 0 }}); - }} - map.once("idle", function() {{ - try {{ map.resize(); }} catch (e) {{}} - revealLive(); - }}); - window.__nitroMap = map; - }} - mountMap(0); -}}; -""".strip() - -_PIZZA_SHOP_JS = """ -window.__nitroWidgetRender = function(data) { - const shop = data && (data.shop || data); - const hero = document.getElementById("hero"); - if (!shop || !shop.name) { - const desc = document.getElementById("desc"); - if (desc) desc.textContent = "Waiting for show_pizza_shop result."; - return; - } - if (shop.image && hero) { - hero.src = shop.image; - hero.style.display = "block"; - } else if (hero) { - hero.style.display = "none"; - } - document.getElementById("name").textContent = shop.name; - document.getElementById("rating").textContent = - shop.rating != null ? "★ " + shop.rating + " (" + (shop.reviews || 0) + " reviews)" : ""; - document.getElementById("desc").textContent = shop.description || ""; - document.getElementById("addr").textContent = shop.address || ""; - const hours = shop.hours ? (shop.hours.open + " – " + shop.hours.close) : ""; - document.getElementById("hours").textContent = hours ? "Hours: " + hours : ""; - document.getElementById("phone").textContent = shop.phone || ""; - const chips = document.getElementById("chips"); - chips.innerHTML = ""; - (shop.specialties || []).forEach(function(item) { - const chip = document.createElement("span"); - chip.className = "chip"; - chip.textContent = item; - chips.appendChild(chip); - }); - const actions = document.getElementById("actions"); - if (actions) { - actions.innerHTML = ""; - function addLink(label, url, primary) { - if (!url) return; - const a = document.createElement("a"); - a.className = primary ? "ns-btn ns-btn-primary" : "ns-btn"; - a.setAttribute("data-open-link", url); - a.href = url; - a.textContent = label; - actions.appendChild(a); - } - let maps = ""; - if (Array.isArray(shop.coords) && shop.coords.length === 2) { - maps = "https://www.google.com/maps/search/?api=1&query=" + shop.coords[1] + "," + shop.coords[0]; - } else if (shop.address) { - maps = "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(shop.address); - } - addLink("Maps", maps, false); - if (shop.phone) { - const tel = String(shop.phone).replace(/[^0-9+]/g, ""); - if (tel) addLink("Call", "tel:" + tel, false); - } - addLink("Website", shop.website || "", true); - } -}; -""".strip() - -_CALC_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data) return; - const expr = document.getElementById("expr"); - const result = document.getElementById("result"); - if (data.expression) expr.textContent = data.expression; - if (data.result != null) result.textContent = String(data.result); - else if (data.value != null) result.textContent = String(data.value); -}; -""".strip() - -_CARD_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data) return; - const name = document.getElementById("name"); - const price = document.getElementById("price"); - const desc = document.getElementById("desc"); - if (name) name.textContent = data.name || "—"; - if (price) price.textContent = data.price != null ? "$" + Number(data.price).toFixed(2) : "—"; - if (desc) desc.textContent = data.description || ""; -}; -""".strip() - -_TABLE_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data || !Array.isArray(data.rows)) return; - const cols = data.columns || Object.keys(data.rows[0] || {}); - const header = document.getElementById("header"); - const body = document.getElementById("body"); - if (!header || !body) return; - header.innerHTML = ""; - body.innerHTML = ""; - cols.forEach(function(c) { - const th = document.createElement("th"); - th.textContent = c; - header.appendChild(th); - }); - data.rows.forEach(function(row) { - const tr = document.createElement("tr"); - cols.forEach(function(c) { - const td = document.createElement("td"); - td.textContent = row[c] ?? ""; - tr.appendChild(td); - }); - body.appendChild(tr); - }); -}; -""".strip() - -_CHART_JS = """ -window.__nitroWidgetRender = function(data) { - if (!data) return; - const title = document.getElementById("title"); - const chart = document.getElementById("chart"); - if (title) title.textContent = data.title || "Chart"; - if (!chart) return; - chart.innerHTML = ""; - const items = data.items || []; - const max = Math.max.apply(null, items.map(function(i) { return i.value || 0; }).concat([1])); - items.forEach(function(item) { - const wrap = document.createElement("div"); - wrap.className = "bar-wrap"; - const bar = document.createElement("div"); - bar.className = "bar"; - bar.style.height = (((item.value || 0) / max) * 140) + "px"; - const label = document.createElement("div"); - label.className = "label"; - label.textContent = item.label || ""; - wrap.appendChild(bar); - wrap.appendChild(label); - chart.appendChild(wrap); - }); -}; -""".strip() - - -_FLIGHT_SEARCH_JS = """ -window.__nitroWidgetRender = function(data) { - const list = document.getElementById("list"); - const meta = document.getElementById("meta"); - if (!list) return; - const offers = (data && (data.offers || data.results)) || []; - const params = (data && data.searchParams) || {}; - const total = (data && data.totalOffers != null) ? data.totalOffers : offers.length; - if (meta) { - meta.textContent = (params.origin && params.destination) - ? (params.origin + " → " + params.destination + " · " + total + " offer" + (total === 1 ? "" : "s")) - : (total + " offer" + (total === 1 ? "" : "s")); - } - list.innerHTML = ""; - if (!offers.length) { - list.innerHTML = '
No flight offers.
'; - return; - } - function code(p) { - if (!p) return ""; - if (typeof p === "string") return p; - return p.iata_code || p.iataCode || p.code || ""; - } - function legs(offer) { - if (offer.slices && offer.slices.length) return offer.slices; - const out = []; - if (offer.outbound) out.push(offer.outbound); - if (offer.return) out.push(offer.return); - return out; - } - offers.forEach(function(offer) { - const el = document.createElement("article"); - el.className = "offer ns-card"; - el.setAttribute("data-call-tool", "get_flight_details"); - el.setAttribute("data-args", JSON.stringify({ offerId: offer.id || "" })); - el.setAttribute("role", "button"); - el.tabIndex = 0; - const amount = offer.total_amount || offer.totalAmount || ""; - const currency = offer.total_currency || offer.totalCurrency || ""; - el.innerHTML = '
'; - el.querySelector(".price").textContent = amount + (currency ? " " + currency : ""); - el.querySelector(".id").textContent = offer.id || ""; - legs(offer).forEach(function(sl) { - const s = document.createElement("div"); - s.className = "slice"; - s.textContent = code(sl.origin) + " → " + code(sl.destination) + " · " + (sl.duration || ""); - el.appendChild(s); - }); - list.appendChild(el); - }); -}; -""".strip() - -_AIRPORT_JS = """ -window.__nitroWidgetRender = function(data) { - const list = document.getElementById("list"); - const meta = document.getElementById("meta"); - if (!list) return; - const results = (data && (data.results || data.airports || data.places)) || []; - if (meta) meta.textContent = "Query: " + ((data && data.query) || "") + " · " + results.length + " result(s)"; - list.innerHTML = ""; - if (!results.length) { - list.innerHTML = '
No airports found.
'; - return; - } - results.forEach(function(item) { - const el = document.createElement("div"); - el.className = "row"; - el.innerHTML = '
'; - el.querySelector(".code").textContent = item.iata_code || item.iataCode || ""; - el.querySelector(".name").textContent = item.name || ""; - el.querySelector(".muted").textContent = (item.city_name || item.cityName || item.city || "") + " · " + (item.type || "airport"); - list.appendChild(el); - }); -}; -""".strip() - - -def _place_code_js() -> str: - return """ - function code(p) { - if (!p) return ""; - if (typeof p === "string") return p; - return p.iata_code || p.iataCode || p.code || ""; - } - function money(amount, currency) { - if (amount == null || amount === "") return ""; - return String(amount) + (currency ? " " + currency : ""); - } - function sliceHtml(sl) { - const origin = code(sl.origin); - const dest = code(sl.destination); - const wrap = document.createElement("div"); - wrap.className = "slice"; - const title = document.createElement("strong"); - title.textContent = origin + " → " + dest; - const times = document.createElement("div"); - times.className = "muted"; - times.textContent = (sl.departing_at || sl.departingAt || sl.departureTime || "") + - " – " + (sl.arriving_at || sl.arrivingAt || sl.arrivalTime || "") + - " · " + (sl.duration || ""); - wrap.appendChild(title); - wrap.appendChild(times); - return wrap; - } -""".strip() - - -_FLIGHT_DETAILS_JS = f""" -window.__nitroWidgetRender = function(data) {{ - const meta = document.getElementById("meta"); - const root = document.getElementById("root"); - if (!root) return; - if (!data) {{ - if (meta) meta.textContent = "Waiting for get_flight_details result."; - return; - }} -{_place_code_js()} - const amount = data.total_amount || data.totalAmount || ""; - const currency = data.total_currency || data.totalCurrency || ""; - if (meta) meta.textContent = "Offer " + (data.id || "") + " · " + money(amount, currency); - root.innerHTML = ""; - (data.slices || []).forEach(function(sl) {{ root.appendChild(sliceHtml(sl)); }}); - if (data.id) {{ - const actions = document.createElement("div"); - actions.className = "ns-actions"; - const btn = document.createElement("button"); - btn.type = "button"; - btn.className = "ns-btn ns-btn-primary"; - btn.setAttribute("data-call-tool", "get_seat_map"); - btn.setAttribute("data-args", JSON.stringify({{ offerId: data.id }})); - btn.textContent = "Seat map"; - actions.appendChild(btn); - root.appendChild(actions); - }} -}}; -""".strip() - -_ORDER_SUMMARY_JS = f""" -window.__nitroWidgetRender = function(data) {{ - const root = document.getElementById("root"); - const card = document.querySelector(".card"); - if (!data) return; -{_place_code_js()} - const status = data.status || "held"; - const ref = data.booking_reference || data.bookingReference || ""; - const orderId = data.id || data.orderId || ""; - const amount = data.total_amount || data.totalAmount || ""; - const currency = data.total_currency || data.totalCurrency || ""; - const host = card || root; - if (!host) return; - host.innerHTML = ""; - const h1 = document.createElement("h1"); - h1.textContent = "Order " + status; - const meta = document.createElement("div"); - meta.className = "meta"; - meta.textContent = "Ref " + ref + " · " + orderId; - const price = document.createElement("div"); - price.className = "price"; - price.textContent = money(amount, currency); - host.appendChild(h1); - host.appendChild(meta); - host.appendChild(price); - const paxTitle = document.createElement("h2"); - paxTitle.textContent = "Passengers"; - host.appendChild(paxTitle); - const passengers = data.passengers || []; - if (!passengers.length) {{ - const empty = document.createElement("div"); - empty.className = "muted"; - empty.textContent = "None listed"; - host.appendChild(empty); - }} - passengers.forEach(function(p) {{ - const line = document.createElement("div"); - line.className = "muted"; - line.textContent = p.name || [p.given_name || p.givenName, p.family_name || p.familyName].filter(Boolean).join(" ") || p.id || ""; - host.appendChild(line); - }}); - const itin = document.createElement("h2"); - itin.textContent = "Itinerary"; - host.appendChild(itin); - (data.slices || []).forEach(function(sl) {{ host.appendChild(sliceHtml(sl)); }}); - if (orderId && String(status).toLowerCase().indexOf("cancel") < 0) {{ - const actions = document.createElement("div"); - actions.className = "ns-actions"; - const btn = document.createElement("button"); - btn.type = "button"; - btn.className = "ns-btn"; - btn.setAttribute("data-call-tool", "cancel_order"); - btn.setAttribute("data-args", JSON.stringify({{ orderId: orderId }})); - btn.textContent = "Cancel order"; - actions.appendChild(btn); - host.appendChild(actions); - }} -}}; -""".strip() - -_SEAT_JS = """ -window.__nitroWidgetRender = function(data) { - const meta = document.getElementById("meta"); - const root = document.getElementById("root"); - if (!root) return; - if (!data) { - if (meta) meta.textContent = "Waiting for get_seat_map result."; - return; - } - if (meta) meta.textContent = "Offer " + (data.offerId || data.offer_id || ""); - root.innerHTML = ""; - const cabins = data.cabins || []; - if (!cabins.length) { - root.innerHTML = '
No seat map data.
'; - return; - } - cabins.forEach(function(cabin) { - const h2 = document.createElement("h2"); - h2.textContent = cabin.cabin_class || cabin.cabinClass || "cabin"; - root.appendChild(h2); - (cabin.rows || []).forEach(function(row) { - const line = document.createElement("div"); - line.className = "seat-row"; - const rn = document.createElement("span"); - rn.className = "rn"; - rn.textContent = row.row_number || row.rowNumber || ""; - line.appendChild(rn); - let seats = row.seats || row.elements || []; - if (!seats.length) { - (row.sections || []).forEach(function(section) { - seats = seats.concat(section.elements || []); - }); - } - seats.forEach(function(seat) { - if (seat.type && seat.type !== "seat") return; - const cell = document.createElement("span"); - const available = seat.available != null ? seat.available : (seat.available_services != null); - cell.className = available ? "seat ok" : "seat no"; - cell.textContent = seat.designator || seat.id || seat.column || ""; - line.appendChild(cell); - }); - root.appendChild(line); - }); - }); -}; -""".strip() - -_CANCEL_JS = """ -window.__nitroWidgetRender = function(data) { - const card = document.querySelector(".card"); - if (!card || !data) return; - const status = data.status || "cancelled"; - const cid = data.id || data.cancellationId || ""; - const refund = data.refund_amount || data.refundAmount || ""; - const currency = data.refund_currency || data.refundCurrency || ""; - card.innerHTML = ""; - const h1 = document.createElement("h1"); - h1.textContent = "Booking cancelled"; - const meta = document.createElement("div"); - meta.className = "meta"; - meta.textContent = status + " · " + cid; - const p = document.createElement("p"); - p.textContent = data.message || "Booking cancelled."; - const price = document.createElement("div"); - price.className = "price"; - price.textContent = "Refund " + (refund ? (refund + (currency ? " " + currency : "")) : "n/a"); - card.appendChild(h1); - card.appendChild(meta); - card.appendChild(p); - card.appendChild(price); -}; -""".strip() - - -def _page( - title: str, - styles: str, - body: str, - render_js: str, - data: Any | None, - extra_head: str = "", - flush: bool = False, - chrome: bool = True, -) -> str: - return wrap_widget_page( - title=title, - styles=styles, - body=body, - render_js=render_js, - data=data, - extra_head=extra_head, - flush=flush, - chrome=chrome, - ) - - -def build_generic_widget(route: str, data: Any | None = None) -> str: - return _page(route, _GENERIC_CSS, render_body(route, data), _generic_render_js(), data) - - -def build_missing_widget(route: str, data: Any | None = None) -> str: - return _page( - f"Missing widget: {route}", - _MISSING_CSS, - missing_body(route), - _generic_render_js(), - data, - ) - - -def build_pizza_list_widget(data: Any | None = None) -> str: - return _page("Pizza shops", _PIZZA_LIST_CSS, render_body("pizza-list", data), _PIZZA_LIST_JS, data) - - -def build_pizza_map_widget(data: Any | None = None) -> str: - return _page( - "Pizza map", - _PIZZA_MAP_CSS, - render_body("pizza-map", data), - _pizza_map_js(), - data, - extra_head=_MAPBOX_HEAD, - flush=True, - ) - - -def build_pizza_shop_widget(data: Any | None = None) -> str: - return _page("Pizza shop", _PIZZA_SHOP_CSS, render_body("pizza-shop", data), _PIZZA_SHOP_JS, data) - - -def build_calculator_result_widget(data: Any | None = None) -> str: - return _page( - "Calculator result", - _CALC_CSS, - render_body("calculator-result", data), - _CALC_JS, - data, - ) - - -def build_card_widget(data: Any | None = None) -> str: - return _page("Product Card", _CARD_CSS, render_body("card", data), _CARD_JS, data) - - -def build_table_widget(data: Any | None = None) -> str: - return _page("Data Table", _TABLE_CSS, render_body("table", data), _TABLE_JS, data) - - -def build_chart_widget(data: Any | None = None) -> str: - return _page("Bar Chart", _CHART_CSS, render_body("chart", data), _CHART_JS, data) - - -def build_flight_search_results_widget(data: Any | None = None) -> str: - return _page( - "Flight search", - _FLIGHT_CSS, - render_body("flight-search-results", data), - _FLIGHT_SEARCH_JS, - data, - ) - - -def build_flight_details_widget(data: Any | None = None) -> str: - return _page( - "Flight details", - _FLIGHT_CSS, - render_body("flight-details", data), - _FLIGHT_DETAILS_JS, - data, - ) - - -def build_airport_search_widget(data: Any | None = None) -> str: - return _page( - "Airport search", - _FLIGHT_CSS, - render_body("airport-search", data), - _AIRPORT_JS, - data, - ) - - -def build_order_summary_widget(data: Any | None = None) -> str: - return _page( - "Order summary", - _FLIGHT_CSS, - render_body("order-summary", data), - _ORDER_SUMMARY_JS, - data, - ) - - -def build_seat_selection_widget(data: Any | None = None) -> str: - return _page( - "Seat map", - _FLIGHT_CSS, - render_body("seat-selection", data), - _SEAT_JS, - data, - ) +from __future__ import annotations +from typing import Any, Callable, Dict, Optional -def build_order_cancellation_widget(data: Any | None = None) -> str: - return _page( - "Cancellation", - _FLIGHT_CSS, - render_body("order-cancellation", data), - _CANCEL_JS, - data, - ) +from nitrostack.widgets.host_bridge import wrap_widget_page # noqa: F401 +from nitrostack.widgets.views import missing_body, render_body # noqa: F401 +from nitrostack.widgets.route_templates_generic import ( # noqa: F401 + _generic_render_js, + _CALC_CSS, + _CARD_CSS, + _TABLE_CSS, + _CHART_CSS, + _GENERIC_CSS, + _MISSING_CSS, + _CALC_JS, + _CARD_JS, + _TABLE_JS, + _CHART_JS, + _page, + build_generic_widget, + build_missing_widget, + build_calculator_result_widget, + build_card_widget, + build_table_widget, + build_chart_widget, +) +from nitrostack.widgets.route_templates_pizza import ( # noqa: F401 + _PIZZA_LIST_CSS, + _PIZZA_MAP_CSS, + _PIZZA_SHOP_CSS, + _PIZZA_LIST_JS, + _MAPBOX_HEAD, + _pizza_map_js, + _PIZZA_SHOP_JS, + build_pizza_list_widget, + build_pizza_map_widget, + build_pizza_shop_widget, +) +from nitrostack.widgets.route_templates_flight import ( # noqa: F401 + _FLIGHT_CSS, + _FLIGHT_SEARCH_JS, + _AIRPORT_JS, + _place_code_js, + _FLIGHT_DETAILS_JS, + _ORDER_SUMMARY_JS, + _SEAT_JS, + _CANCEL_JS, + build_flight_search_results_widget, + build_flight_details_widget, + build_airport_search_widget, + build_order_summary_widget, + build_seat_selection_widget, + build_order_cancellation_widget, +) _ROUTE_BUILDERS: Dict[str, Callable[[Any | None], str]] = { diff --git a/nitrostack/widgets/route_templates_flight.py b/nitrostack/widgets/route_templates_flight.py new file mode 100644 index 0000000..8736783 --- /dev/null +++ b/nitrostack/widgets/route_templates_flight.py @@ -0,0 +1,357 @@ +"""Flight and order widget templates (CSS and render JS).""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.route_templates_generic import _page +from nitrostack.widgets.views import render_body + + +_FLIGHT_CSS = """ + :root { --ns-accent: #0369a1; --ns-accent-soft: #e0f2fe; } + .offer, .card, #list .row { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 12px; margin-bottom: 10px; } + .row { display: flex; gap: 12px; align-items: center; } + .id { font-size: 0.8rem; color: var(--ns-muted); } + .code { font-size: 1.1rem; font-weight: 800; min-width: 3rem; } + .slice { margin-top: 8px; } + .seat-row { display: flex; gap: 6px; align-items: center; margin: 4px 0; } + .rn { width: 2rem; font-size: 0.8rem; color: var(--ns-muted); } + .seat { display: inline-block; min-width: 2.4rem; text-align: center; padding: 4px; border-radius: 6px; font-size: 0.75rem; } +""" + + +_FLIGHT_SEARCH_JS = """ +window.__nitroWidgetRender = function(data) { + const list = document.getElementById("list"); + const meta = document.getElementById("meta"); + if (!list) return; + const offers = (data && (data.offers || data.results)) || []; + const params = (data && data.searchParams) || {}; + const total = (data && data.totalOffers != null) ? data.totalOffers : offers.length; + if (meta) { + meta.textContent = (params.origin && params.destination) + ? (params.origin + " → " + params.destination + " · " + total + " offer" + (total === 1 ? "" : "s")) + : (total + " offer" + (total === 1 ? "" : "s")); + } + list.innerHTML = ""; + if (!offers.length) { + list.innerHTML = '
No flight offers.
'; + return; + } + function code(p) { + if (!p) return ""; + if (typeof p === "string") return p; + return p.iata_code || p.iataCode || p.code || ""; + } + function legs(offer) { + if (offer.slices && offer.slices.length) return offer.slices; + const out = []; + if (offer.outbound) out.push(offer.outbound); + if (offer.return) out.push(offer.return); + return out; + } + offers.forEach(function(offer) { + const el = document.createElement("article"); + el.className = "offer ns-card"; + el.setAttribute("data-call-tool", "get_flight_details"); + el.setAttribute("data-args", JSON.stringify({ offerId: offer.id || "" })); + el.setAttribute("role", "button"); + el.tabIndex = 0; + const amount = offer.total_amount || offer.totalAmount || ""; + const currency = offer.total_currency || offer.totalCurrency || ""; + el.innerHTML = '
'; + el.querySelector(".price").textContent = amount + (currency ? " " + currency : ""); + el.querySelector(".id").textContent = offer.id || ""; + legs(offer).forEach(function(sl) { + const s = document.createElement("div"); + s.className = "slice"; + s.textContent = code(sl.origin) + " → " + code(sl.destination) + " · " + (sl.duration || ""); + el.appendChild(s); + }); + list.appendChild(el); + }); +}; +""".strip() + + +_AIRPORT_JS = """ +window.__nitroWidgetRender = function(data) { + const list = document.getElementById("list"); + const meta = document.getElementById("meta"); + if (!list) return; + const results = (data && (data.results || data.airports || data.places)) || []; + if (meta) meta.textContent = "Query: " + ((data && data.query) || "") + " · " + results.length + " result(s)"; + list.innerHTML = ""; + if (!results.length) { + list.innerHTML = '
No airports found.
'; + return; + } + results.forEach(function(item) { + const el = document.createElement("div"); + el.className = "row"; + el.innerHTML = '
'; + el.querySelector(".code").textContent = item.iata_code || item.iataCode || ""; + el.querySelector(".name").textContent = item.name || ""; + el.querySelector(".muted").textContent = (item.city_name || item.cityName || item.city || "") + " · " + (item.type || "airport"); + list.appendChild(el); + }); +}; +""".strip() + + +def _place_code_js() -> str: + return """ + function code(p) { + if (!p) return ""; + if (typeof p === "string") return p; + return p.iata_code || p.iataCode || p.code || ""; + } + function money(amount, currency) { + if (amount == null || amount === "") return ""; + return String(amount) + (currency ? " " + currency : ""); + } + function sliceHtml(sl) { + const origin = code(sl.origin); + const dest = code(sl.destination); + const wrap = document.createElement("div"); + wrap.className = "slice"; + const title = document.createElement("strong"); + title.textContent = origin + " → " + dest; + const times = document.createElement("div"); + times.className = "muted"; + times.textContent = (sl.departing_at || sl.departingAt || sl.departureTime || "") + + " – " + (sl.arriving_at || sl.arrivingAt || sl.arrivalTime || "") + + " · " + (sl.duration || ""); + wrap.appendChild(title); + wrap.appendChild(times); + return wrap; + } +""".strip() + + +_FLIGHT_DETAILS_JS = f""" +window.__nitroWidgetRender = function(data) {{ + const meta = document.getElementById("meta"); + const root = document.getElementById("root"); + if (!root) return; + if (!data) {{ + if (meta) meta.textContent = "Waiting for get_flight_details result."; + return; + }} +{_place_code_js()} + const amount = data.total_amount || data.totalAmount || ""; + const currency = data.total_currency || data.totalCurrency || ""; + if (meta) meta.textContent = "Offer " + (data.id || "") + " · " + money(amount, currency); + root.innerHTML = ""; + (data.slices || []).forEach(function(sl) {{ root.appendChild(sliceHtml(sl)); }}); + if (data.id) {{ + const actions = document.createElement("div"); + actions.className = "ns-actions"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "ns-btn ns-btn-primary"; + btn.setAttribute("data-call-tool", "get_seat_map"); + btn.setAttribute("data-args", JSON.stringify({{ offerId: data.id }})); + btn.textContent = "Seat map"; + actions.appendChild(btn); + root.appendChild(actions); + }} +}}; +""".strip() + + +_ORDER_SUMMARY_JS = f""" +window.__nitroWidgetRender = function(data) {{ + const root = document.getElementById("root"); + const card = document.querySelector(".card"); + if (!data) return; +{_place_code_js()} + const status = data.status || "held"; + const ref = data.booking_reference || data.bookingReference || ""; + const orderId = data.id || data.orderId || ""; + const amount = data.total_amount || data.totalAmount || ""; + const currency = data.total_currency || data.totalCurrency || ""; + const host = card || root; + if (!host) return; + host.innerHTML = ""; + const h1 = document.createElement("h1"); + h1.textContent = "Order " + status; + const meta = document.createElement("div"); + meta.className = "meta"; + meta.textContent = "Ref " + ref + " · " + orderId; + const price = document.createElement("div"); + price.className = "price"; + price.textContent = money(amount, currency); + host.appendChild(h1); + host.appendChild(meta); + host.appendChild(price); + const paxTitle = document.createElement("h2"); + paxTitle.textContent = "Passengers"; + host.appendChild(paxTitle); + const passengers = data.passengers || []; + if (!passengers.length) {{ + const empty = document.createElement("div"); + empty.className = "muted"; + empty.textContent = "None listed"; + host.appendChild(empty); + }} + passengers.forEach(function(p) {{ + const line = document.createElement("div"); + line.className = "muted"; + line.textContent = p.name || [p.given_name || p.givenName, p.family_name || p.familyName].filter(Boolean).join(" ") || p.id || ""; + host.appendChild(line); + }}); + const itin = document.createElement("h2"); + itin.textContent = "Itinerary"; + host.appendChild(itin); + (data.slices || []).forEach(function(sl) {{ host.appendChild(sliceHtml(sl)); }}); + if (orderId && String(status).toLowerCase().indexOf("cancel") < 0) {{ + const actions = document.createElement("div"); + actions.className = "ns-actions"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "ns-btn"; + btn.setAttribute("data-call-tool", "cancel_order"); + btn.setAttribute("data-args", JSON.stringify({{ orderId: orderId }})); + btn.textContent = "Cancel order"; + actions.appendChild(btn); + host.appendChild(actions); + }} +}}; +""".strip() + + +_SEAT_JS = """ +window.__nitroWidgetRender = function(data) { + const meta = document.getElementById("meta"); + const root = document.getElementById("root"); + if (!root) return; + if (!data) { + if (meta) meta.textContent = "Waiting for get_seat_map result."; + return; + } + if (meta) meta.textContent = "Offer " + (data.offerId || data.offer_id || ""); + root.innerHTML = ""; + const cabins = data.cabins || []; + if (!cabins.length) { + root.innerHTML = '
No seat map data.
'; + return; + } + cabins.forEach(function(cabin) { + const h2 = document.createElement("h2"); + h2.textContent = cabin.cabin_class || cabin.cabinClass || "cabin"; + root.appendChild(h2); + (cabin.rows || []).forEach(function(row) { + const line = document.createElement("div"); + line.className = "seat-row"; + const rn = document.createElement("span"); + rn.className = "rn"; + rn.textContent = row.row_number || row.rowNumber || ""; + line.appendChild(rn); + let seats = row.seats || row.elements || []; + if (!seats.length) { + (row.sections || []).forEach(function(section) { + seats = seats.concat(section.elements || []); + }); + } + seats.forEach(function(seat) { + if (seat.type && seat.type !== "seat") return; + const cell = document.createElement("span"); + const available = seat.available != null ? seat.available : (seat.available_services != null); + cell.className = available ? "seat ok" : "seat no"; + cell.textContent = seat.designator || seat.id || seat.column || ""; + line.appendChild(cell); + }); + root.appendChild(line); + }); + }); +}; +""".strip() + + +_CANCEL_JS = """ +window.__nitroWidgetRender = function(data) { + const card = document.querySelector(".card"); + if (!card || !data) return; + const status = data.status || "cancelled"; + const cid = data.id || data.cancellationId || ""; + const refund = data.refund_amount || data.refundAmount || ""; + const currency = data.refund_currency || data.refundCurrency || ""; + card.innerHTML = ""; + const h1 = document.createElement("h1"); + h1.textContent = "Booking cancelled"; + const meta = document.createElement("div"); + meta.className = "meta"; + meta.textContent = status + " · " + cid; + const p = document.createElement("p"); + p.textContent = data.message || "Booking cancelled."; + const price = document.createElement("div"); + price.className = "price"; + price.textContent = "Refund " + (refund ? (refund + (currency ? " " + currency : "")) : "n/a"); + card.appendChild(h1); + card.appendChild(meta); + card.appendChild(p); + card.appendChild(price); +}; +""".strip() + + +def build_flight_search_results_widget(data: Any | None = None) -> str: + return _page( + "Flight search", + _FLIGHT_CSS, + render_body("flight-search-results", data), + _FLIGHT_SEARCH_JS, + data, + ) + + +def build_flight_details_widget(data: Any | None = None) -> str: + return _page( + "Flight details", + _FLIGHT_CSS, + render_body("flight-details", data), + _FLIGHT_DETAILS_JS, + data, + ) + + +def build_airport_search_widget(data: Any | None = None) -> str: + return _page( + "Airport search", + _FLIGHT_CSS, + render_body("airport-search", data), + _AIRPORT_JS, + data, + ) + + +def build_order_summary_widget(data: Any | None = None) -> str: + return _page( + "Order summary", + _FLIGHT_CSS, + render_body("order-summary", data), + _ORDER_SUMMARY_JS, + data, + ) + + +def build_seat_selection_widget(data: Any | None = None) -> str: + return _page( + "Seat map", + _FLIGHT_CSS, + render_body("seat-selection", data), + _SEAT_JS, + data, + ) + + +def build_order_cancellation_widget(data: Any | None = None) -> str: + return _page( + "Cancellation", + _FLIGHT_CSS, + render_body("order-cancellation", data), + _CANCEL_JS, + data, + ) diff --git a/nitrostack/widgets/route_templates_generic.py b/nitrostack/widgets/route_templates_generic.py new file mode 100644 index 0000000..13deefc --- /dev/null +++ b/nitrostack/widgets/route_templates_generic.py @@ -0,0 +1,206 @@ +"""Page wrapper plus the generic, missing, calculator, card, table and chart widget templates.""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.host_bridge import wrap_widget_page +from nitrostack.widgets.views import missing_body, render_body + + +def _generic_render_js() -> str: + return """ +window.__nitroWidgetRender = function(data) { + const root = document.getElementById("root"); + const meta = document.getElementById("meta"); + if (!root) return; + if (!data) { + if (meta) meta.textContent = "Waiting for tool result (host injects tool output)."; + return; + } + if (meta) meta.textContent = "Tool output"; + root.innerHTML = ""; + const pre = document.createElement("pre"); + pre.textContent = JSON.stringify(data, null, 2); + root.appendChild(pre); +}; +""".strip() + + +_CALC_CSS = """ + :root { --ns-accent: #15803d; } + .card { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 20px; text-align: center; } + .expr { font-size: 0.95rem; color: var(--ns-muted); margin-bottom: 8px; } + .result { font-size: 2rem; font-weight: 800; color: var(--ns-accent); } +""" + + +_CARD_CSS = """ + .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 20px; box-shadow: var(--ns-shadow); max-width: 320px; border: 1px solid var(--ns-border); } + .card h2 { margin: 0 0 8px; font-size: 1.25rem; } + .price { font-size: 1.5rem; } + .desc { color: var(--ns-muted); margin-top: 8px; } +""" + + +_TABLE_CSS = """ + table { border-collapse: collapse; width: 100%; max-width: 480px; background: var(--ns-surface); border-radius: 10px; overflow: hidden; } + th, td { border: 1px solid var(--ns-border); padding: 8px 12px; text-align: left; } + th { background: var(--ns-accent-soft); } +""" + + +_CHART_CSS = """ + .chart { display: flex; align-items: flex-end; gap: 8px; height: 160px; } + .bar-wrap { flex: 1; display: flex; flex-direction: column; align-items: center; } + .bar { width: 100%; background: var(--ns-accent, #3b82f6); border-radius: 4px 4px 0 0; min-height: 4px; } + .label { font-size: 12px; margin-top: 4px; color: var(--ns-muted); } +""" + + +_GENERIC_CSS = """ + pre { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: 8px; padding: 12px; overflow: auto; } +""" + + +_MISSING_CSS = """ + :root { --ns-bg: #fef2f2; --ns-text: #7f1d1d; } + .meta { font-size: 0.9rem; line-height: 1.5; } +""" + + +_CALC_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data) return; + const expr = document.getElementById("expr"); + const result = document.getElementById("result"); + if (data.expression) expr.textContent = data.expression; + if (data.result != null) result.textContent = String(data.result); + else if (data.value != null) result.textContent = String(data.value); +}; +""".strip() + + +_CARD_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data) return; + const name = document.getElementById("name"); + const price = document.getElementById("price"); + const desc = document.getElementById("desc"); + if (name) name.textContent = data.name || "—"; + if (price) price.textContent = data.price != null ? "$" + Number(data.price).toFixed(2) : "—"; + if (desc) desc.textContent = data.description || ""; +}; +""".strip() + + +_TABLE_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data || !Array.isArray(data.rows)) return; + const cols = data.columns || Object.keys(data.rows[0] || {}); + const header = document.getElementById("header"); + const body = document.getElementById("body"); + if (!header || !body) return; + header.innerHTML = ""; + body.innerHTML = ""; + cols.forEach(function(c) { + const th = document.createElement("th"); + th.textContent = c; + header.appendChild(th); + }); + data.rows.forEach(function(row) { + const tr = document.createElement("tr"); + cols.forEach(function(c) { + const td = document.createElement("td"); + td.textContent = row[c] ?? ""; + tr.appendChild(td); + }); + body.appendChild(tr); + }); +}; +""".strip() + + +_CHART_JS = """ +window.__nitroWidgetRender = function(data) { + if (!data) return; + const title = document.getElementById("title"); + const chart = document.getElementById("chart"); + if (title) title.textContent = data.title || "Chart"; + if (!chart) return; + chart.innerHTML = ""; + const items = data.items || []; + const max = Math.max.apply(null, items.map(function(i) { return i.value || 0; }).concat([1])); + items.forEach(function(item) { + const wrap = document.createElement("div"); + wrap.className = "bar-wrap"; + const bar = document.createElement("div"); + bar.className = "bar"; + bar.style.height = (((item.value || 0) / max) * 140) + "px"; + const label = document.createElement("div"); + label.className = "label"; + label.textContent = item.label || ""; + wrap.appendChild(bar); + wrap.appendChild(label); + chart.appendChild(wrap); + }); +}; +""".strip() + + +def _page( + title: str, + styles: str, + body: str, + render_js: str, + data: Any | None, + extra_head: str = "", + flush: bool = False, + chrome: bool = True, +) -> str: + return wrap_widget_page( + title=title, + styles=styles, + body=body, + render_js=render_js, + data=data, + extra_head=extra_head, + flush=flush, + chrome=chrome, + ) + + +def build_generic_widget(route: str, data: Any | None = None) -> str: + return _page(route, _GENERIC_CSS, render_body(route, data), _generic_render_js(), data) + + +def build_missing_widget(route: str, data: Any | None = None) -> str: + return _page( + f"Missing widget: {route}", + _MISSING_CSS, + missing_body(route), + _generic_render_js(), + data, + ) + + +def build_calculator_result_widget(data: Any | None = None) -> str: + return _page( + "Calculator result", + _CALC_CSS, + render_body("calculator-result", data), + _CALC_JS, + data, + ) + + +def build_card_widget(data: Any | None = None) -> str: + return _page("Product Card", _CARD_CSS, render_body("card", data), _CARD_JS, data) + + +def build_table_widget(data: Any | None = None) -> str: + return _page("Data Table", _TABLE_CSS, render_body("table", data), _TABLE_JS, data) + + +def build_chart_widget(data: Any | None = None) -> str: + return _page("Bar Chart", _CHART_CSS, render_body("chart", data), _CHART_JS, data) diff --git a/nitrostack/widgets/route_templates_pizza.py b/nitrostack/widgets/route_templates_pizza.py new file mode 100644 index 0000000..fa440fb --- /dev/null +++ b/nitrostack/widgets/route_templates_pizza.py @@ -0,0 +1,303 @@ +"""Pizza list, map and shop widget templates (CSS and render JS).""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.route_templates_generic import _page +from nitrostack.widgets.views import render_body + + +_PIZZA_LIST_CSS = """ + :root { --ns-accent: #ea580c; --ns-accent-soft: #ffedd5; } + .shop { min-width: 260px; max-width: 260px; scroll-snap-align: start; flex-shrink: 0; } + .img { width: 100%; height: 120px; object-fit: cover; border-radius: 10px; margin-bottom: 8px; background: var(--ns-accent-soft); } + .row { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; } + .name { font-weight: 700; } + .addr { color: var(--ns-muted); font-size: 0.85rem; margin-top: 4px; } +""" + + +_PIZZA_MAP_CSS = """ + :root { --ns-accent: #ea580c; } + html, body { width: 100%; height: 560px; } + body { position: relative; min-height: 560px; background: #e5e7eb; } + .meta { position: absolute; top: 12px; left: 12px; z-index: 3; margin: 0; + background: color-mix(in srgb, var(--ns-surface) 92%, transparent); border-radius: 8px; padding: 6px 10px; + box-shadow: var(--ns-shadow); } + .map { position: absolute; inset: 0; width: 100%; height: 560px; min-height: 560px; } + .map-live { position: absolute; inset: 0; } + .static-map { position: absolute; inset: 0; z-index: 1; width: 100%; height: 560px; + object-fit: cover; transition: opacity .4s ease; } + .static-map.is-ready { opacity: 0; pointer-events: none; } + .mapboxgl-map { width: 100%; height: 100%; } + .cards { position: absolute; left: 16px; right: 16px; bottom: 8px; z-index: 3; } + .map-card { min-width: 220px; max-width: 220px; flex-shrink: 0; scroll-snap-align: start; } + .map-card .name { font-weight: 700; } + .map-card .muted { margin-top: 4px; } + .map-card .rating { margin-top: 4px; } +""" + + +_PIZZA_SHOP_CSS = """ + :root { --ns-accent: #e11d48; --ns-accent-soft: #ffe4e6; } + .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 16px; border: 1px solid var(--ns-border); } + .hero { width: 100%; max-height: 180px; object-fit: cover; border-radius: 10px; margin-bottom: 12px; } + .chips { margin-top: 10px; } + .chip { margin: 0 4px 4px 0; } +""" + + +_PIZZA_LIST_JS = """ +window.__nitroWidgetRender = function(data) { + const list = document.getElementById("list"); + const meta = document.getElementById("meta"); + if (!list || !meta) return; + list.innerHTML = ""; + if (!data || !Array.isArray(data.shops)) { + meta.textContent = "Waiting for show_pizza_list result."; + return; + } + const state = (window.openai && window.openai.widgetState) || {}; + const sort = state.sort || "rating"; + const shops = data.shops.slice().sort(function(a, b) { + if (sort === "name") return String(a.name || "").localeCompare(String(b.name || "")); + return (b.rating || 0) - (a.rating || 0); + }); + document.querySelectorAll("#sorts [data-sort]").forEach(function(btn) { + btn.classList.toggle("is-on", btn.getAttribute("data-sort") === sort); + }); + const total = data.totalShops ?? data.shops.length; + meta.textContent = total + " shop" + (total === 1 ? "" : "s"); + if (!shops.length) { + list.innerHTML = '
No shops match these filters.
'; + return; + } + shops.forEach(function(shop) { + const el = document.createElement("article"); + el.className = "shop ns-card"; + el.setAttribute("data-call-tool", "show_pizza_shop"); + el.setAttribute("data-args", JSON.stringify({ shopId: shop.id || "" })); + el.setAttribute("role", "button"); + el.tabIndex = 0; + const open = shop.openNow + ? 'Open' + : 'Closed'; + const price = "$".repeat(shop.priceLevel || 1); + let img = ""; + if (shop.image) { + img = ''; + } + el.innerHTML = + img + + '
' + + '
' + open + '
'; + el.querySelector(".name").textContent = shop.name || shop.id || "Shop"; + el.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : ""; + el.querySelector(".addr").textContent = shop.address || ""; + el.querySelector(".price").textContent = price; + list.appendChild(el); + }); +}; +document.addEventListener("click", function(ev) { + const btn = ev.target.closest("#sorts [data-sort]"); + if (!btn || !window.nitrostack) return; + const next = Object.assign({}, (window.openai && window.openai.widgetState) || {}, { + sort: btn.getAttribute("data-sort") + }); + window.nitrostack.setWidgetState(next); + if (typeof window.__nitroWidgetRender === "function" && window.nitrostack.readHostData) { + window.__nitroWidgetRender(window.nitrostack.readHostData()); + } +}); +""".strip() + + +_MAPBOX_HEAD = """ + + +""".strip() + + +def _pizza_map_js() -> str: + import json + + from nitrostack.widgets.html_util import get_mapbox_token + + token = json.dumps(get_mapbox_token()) + return f""" +window.__NITRO_MAPBOX_TOKEN = {token}; +window.__nitroWidgetRender = function(data) {{ + const meta = document.getElementById("meta"); + const mapEl = document.getElementById("map-live") || document.getElementById("map"); + const cards = document.getElementById("cards"); + const staticEl = document.getElementById("static-map"); + if (!mapEl) return; + if (!data || !Array.isArray(data.shops) || !data.shops.length) {{ + if (meta) meta.textContent = "Waiting for show_pizza_map result."; + return; + }} + const shops = data.shops.filter(function(s) {{ return Array.isArray(s.coords) && s.coords.length === 2; }}); + const sig = (data.filter || "all") + "|" + shops.map(function(s) {{ + return (s.id || "") + ":" + s.coords[0] + "," + s.coords[1]; + }}).join(";"); + if (window.__nitroMapSig === sig && window.__nitroMap) return; + if (meta) meta.textContent = (data.totalShops ?? data.shops.length) + " shops · filter: " + (data.filter || "all"); + if (cards && !cards.querySelector(".map-card")) {{ + data.shops.forEach(function(shop) {{ + const card = document.createElement("article"); + card.className = "map-card ns-card"; + card.setAttribute("data-shop-id", shop.id || ""); + card.setAttribute("data-call-tool", "show_pizza_shop"); + card.setAttribute("data-args", JSON.stringify({{ shopId: shop.id || "" }})); + card.setAttribute("role", "button"); + card.tabIndex = 0; + card.innerHTML = '
'; + card.querySelector(".name").textContent = shop.name || shop.id || "Shop"; + card.querySelector(".muted").textContent = shop.address || ""; + card.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : ""; + cards.appendChild(card); + }}); + }} + function revealLive() {{ + if (staticEl) staticEl.classList.add("is-ready"); + }} + function mountMap(attempt) {{ + if (window.__nitroMapSig === sig && window.__nitroMap) return; + if (!window.__NITRO_MAPBOX_TOKEN) {{ + if (meta) meta.textContent = "Set MAPBOX_TOKEN in .env to load the map."; + if (mapEl) {{ + mapEl.innerHTML = '
Set MAPBOX_TOKEN in .env (Mapbox public pk. token) to load the map.
'; + }} + return; + }} + if (typeof mapboxgl === "undefined") {{ + if ((attempt || 0) < 80) {{ + setTimeout(function() {{ mountMap((attempt || 0) + 1); }}, 50); + }} + return; + }} + window.__nitroMapSig = sig; + if (window.__nitroMap) {{ + window.__nitroMap.remove(); + window.__nitroMap = null; + }} + mapboxgl.accessToken = window.__NITRO_MAPBOX_TOKEN; + const first = (shops[0] && shops[0].coords) || [-122.4194, 37.7749]; + const map = new mapboxgl.Map({{ + container: mapEl, + style: "mapbox://styles/mapbox/streets-v12", + center: first, + zoom: 12, + cooperativeGestures: false, + fadeDuration: 0 + }}); + map.addControl(new mapboxgl.NavigationControl({{ showCompass: false }}), "top-right"); + map.addControl(new mapboxgl.FullscreenControl(), "top-right"); + shops.forEach(function(shop) {{ + const el = document.createElement("div"); + el.style.backgroundImage = "url(https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png)"; + el.style.width = "30px"; + el.style.height = "40px"; + el.style.backgroundSize = "100%"; + el.style.cursor = "pointer"; + el.title = shop.name || shop.id || ""; + el.addEventListener("click", function() {{ + if (window.nitrostack) window.nitrostack.callTool("show_pizza_shop", {{ shopId: shop.id || "" }}); + }}); + new mapboxgl.Marker(el).setLngLat(shop.coords).addTo(map); + }}); + if (shops.length > 1) {{ + const bounds = new mapboxgl.LngLatBounds(); + shops.forEach(function(s) {{ bounds.extend(s.coords); }}); + map.fitBounds(bounds, {{ padding: 60, maxZoom: 14, duration: 0 }}); + }} + map.once("idle", function() {{ + try {{ map.resize(); }} catch (e) {{}} + revealLive(); + }}); + window.__nitroMap = map; + }} + mountMap(0); +}}; +""".strip() + + +_PIZZA_SHOP_JS = """ +window.__nitroWidgetRender = function(data) { + const shop = data && (data.shop || data); + const hero = document.getElementById("hero"); + if (!shop || !shop.name) { + const desc = document.getElementById("desc"); + if (desc) desc.textContent = "Waiting for show_pizza_shop result."; + return; + } + if (shop.image && hero) { + hero.src = shop.image; + hero.style.display = "block"; + } else if (hero) { + hero.style.display = "none"; + } + document.getElementById("name").textContent = shop.name; + document.getElementById("rating").textContent = + shop.rating != null ? "★ " + shop.rating + " (" + (shop.reviews || 0) + " reviews)" : ""; + document.getElementById("desc").textContent = shop.description || ""; + document.getElementById("addr").textContent = shop.address || ""; + const hours = shop.hours ? (shop.hours.open + " – " + shop.hours.close) : ""; + document.getElementById("hours").textContent = hours ? "Hours: " + hours : ""; + document.getElementById("phone").textContent = shop.phone || ""; + const chips = document.getElementById("chips"); + chips.innerHTML = ""; + (shop.specialties || []).forEach(function(item) { + const chip = document.createElement("span"); + chip.className = "chip"; + chip.textContent = item; + chips.appendChild(chip); + }); + const actions = document.getElementById("actions"); + if (actions) { + actions.innerHTML = ""; + function addLink(label, url, primary) { + if (!url) return; + const a = document.createElement("a"); + a.className = primary ? "ns-btn ns-btn-primary" : "ns-btn"; + a.setAttribute("data-open-link", url); + a.href = url; + a.textContent = label; + actions.appendChild(a); + } + let maps = ""; + if (Array.isArray(shop.coords) && shop.coords.length === 2) { + maps = "https://www.google.com/maps/search/?api=1&query=" + shop.coords[1] + "," + shop.coords[0]; + } else if (shop.address) { + maps = "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(shop.address); + } + addLink("Maps", maps, false); + if (shop.phone) { + const tel = String(shop.phone).replace(/[^0-9+]/g, ""); + if (tel) addLink("Call", "tel:" + tel, false); + } + addLink("Website", shop.website || "", true); + } +}; +""".strip() + + +def build_pizza_list_widget(data: Any | None = None) -> str: + return _page("Pizza shops", _PIZZA_LIST_CSS, render_body("pizza-list", data), _PIZZA_LIST_JS, data) + + +def build_pizza_map_widget(data: Any | None = None) -> str: + return _page( + "Pizza map", + _PIZZA_MAP_CSS, + render_body("pizza-map", data), + _pizza_map_js(), + data, + extra_head=_MAPBOX_HEAD, + flush=True, + ) + + +def build_pizza_shop_widget(data: Any | None = None) -> str: + return _page("Pizza shop", _PIZZA_SHOP_CSS, render_body("pizza-shop", data), _PIZZA_SHOP_JS, data) diff --git a/nitrostack/widgets/views.py b/nitrostack/widgets/views.py index 9822cbf..9e84807 100644 --- a/nitrostack/widgets/views.py +++ b/nitrostack/widgets/views.py @@ -3,13 +3,17 @@ Hosts that inject data later still use the HTML document's small host-bridge script. First paint (Inspector ``tools/call`` HTML, live preview) uses these builders so the iframe matches the actual tool output — not sample JSON. + +This module is the route -> body dispatcher. The bodies live in views_common, +views_pizza and views_flight and are re-exported here, so existing imports keep working. """ from __future__ import annotations from typing import Any, Callable, Dict -from nitrostack.widgets.html_util import ( +# Re-exported only so existing ``from nitrostack.widgets.views import ...`` lines keep working. +from nitrostack.widgets.html_util import ( # noqa: F401 as_dict, as_list, esc, @@ -20,529 +24,34 @@ place_code, place_name, ) -from nitrostack.widgets.ui import action_row, call_attrs, maps_url - - -def _safe_int( - value: Any, - default: int = 0, - *, - minimum: int | None = None, - maximum: int | None = None, -) -> int: - try: - # OverflowError covers infinities: `json.loads("1e400")` yields `inf`, and - # `int(float("inf"))` raises. NaN already surfaces as ValueError. - n = int(float(value)) - except (TypeError, ValueError, OverflowError): - n = default - if minimum is not None: - n = max(minimum, n) - if maximum is not None: - n = min(maximum, n) - return n - - -def _safe_float(value: Any, default: float = 0.0) -> float: - try: - n = float(value) - except (TypeError, ValueError): - return default - if n != n or n in (float("inf"), float("-inf")): - return default - return n - - -def pizza_list_body(data: Any | None) -> str: - payload = as_dict(data) - shops = as_list(payload.get("shops")) - total = payload.get("totalShops") - if total is None: - total = len(shops) - if data is None: - meta = "Waiting for show_pizza_list result." - cards = "" - elif not shops: - meta = f"{total} shops" - cards = '
No shops match these filters.
' - else: - meta = f"{total} shop" + ("" if total == 1 else "s") - parts = [] - for shop in shops: - shop = as_dict(shop) - open_cls = "open" if shop.get("openNow") else "closed" - open_label = "Open" if shop.get("openNow") else "Closed" - price = "$" * _safe_int(shop.get("priceLevel"), 1, minimum=1, maximum=4) - img = "" - if shop.get("image"): - img = f'' - rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else "" - shop_id = shop.get("id") or "" - parts.append( - f'
' - f"{img}" - f'
{esc(shop.get("name") or shop_id or "Shop")}' - f'{rating}
' - f'
{esc(shop.get("address"))}
' - f'
{open_label} ' - f'{esc(price)}
' - "
" - ) - cards = "".join(parts) - return ( - "

Pizza shops

" - f'
{esc(meta)}
' - '
' - '' - '' - "
" - f'
{cards}
' - '
' - ) - - -def _pizza_map_card(shop: dict) -> str: - name = shop.get("name") or shop.get("id") or "Shop" - shop_id = shop.get("id") or "" - rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else "" - return ( - f'
' - f'
{esc(name)}
' - f'
{esc(shop.get("address"))}
' - f'
{rating}
' - ) - - -def pizza_map_body(data: Any | None) -> str: - payload = as_dict(data) - shops = as_list(payload.get("shops")) - static = "" - if data is None or not shops: - meta = "Waiting for show_pizza_map result." - cards = "" - else: - filt = payload.get("filter") or "all" - total = payload.get("totalShops") - if total is None: - total = len(shops) - meta = f"{total} shops · filter: {filt}" - cards = "".join(_pizza_map_card(as_dict(shop)) for shop in shops) - static_src = mapbox_static_url(shops) - static = ( - f'Pizza shop map' - if static_src - else "" - ) - return ( - f'
{esc(meta)}
' - f'
' - f'
{static}
' - f'
{cards}
' - '
' - ) - - -def pizza_shop_body(data: Any | None) -> str: - payload = as_dict(data) - shop = as_dict(payload.get("shop") or payload if data is not None else {}) - if data is None or not shop.get("name"): - return ( - '
' - '' - '

Pizza shop

' - '
' - '

Waiting for show_pizza_shop result.

' - '

' - '

' - '

' - '
' - '
' - "
" - '
' - ) - img = "" - if shop.get("image"): - img = f'' - else: - img = '' - rating = "" - if shop.get("rating") is not None: - rating = f"★ {esc(shop.get('rating'))} ({esc(shop.get('reviews') or 0)} reviews)" - hours = as_dict(shop.get("hours")) - hours_text = "" - if hours.get("open") or hours.get("close"): - hours_text = f"Hours: {esc(hours.get('open'))} – {esc(hours.get('close'))}" - chips = "".join( - f'{esc(item)}' for item in as_list(shop.get("specialties")) - ) - actions = action_row(maps=maps_url(shop), phone=str(shop.get("phone") or ""), website=str(shop.get("website") or "")) - return ( - '
' - f"{img}" - f'

{esc(shop.get("name"))}

' - f'
{rating}
' - f'

{esc(shop.get("description"))}

' - f'

{esc(shop.get("address"))}

' - f'

{hours_text}

' - f'

{esc(shop.get("phone"))}

' - f'
{chips}
' - f"{actions}" - "
" - '
' - ) - - -def calculator_result_body(data: Any | None) -> str: - payload = as_dict(data) - expr = payload.get("expression") or "—" - result = payload.get("result") - if result is None: - result = payload.get("value") - result_text = "—" if result is None else str(result) - return ( - '
' - f'
{esc(expr)}
' - f'
{esc(result_text)}
' - "
" - '
' - '
' - ) - - -def card_body(data: Any | None) -> str: - payload = as_dict(data) - name = payload.get("name") or "—" - price = payload.get("price") - price_text = f"${float(price):.2f}" if isinstance(price, (int, float)) else (str(price) if price else "—") - desc = payload.get("description") or "" - return ( - '
' - f'

{esc(name)}

' - f'
{esc(price_text)}
' - f'

{esc(desc)}

' - "
" - ) - - -def table_body(data: Any | None) -> str: - payload = as_dict(data) - rows = as_list(payload.get("rows")) - cols = as_list(payload.get("columns")) - if not cols and rows: - cols = list(as_dict(rows[0]).keys()) - header = "".join(f"{esc(c)}" for c in cols) - body_rows = [] - for row in rows: - row = as_dict(row) - cells = "".join(f"{esc(row.get(c, ''))}" for c in cols) - body_rows.append(f"{cells}") - return ( - "" - f'{header}' - f'{"".join(body_rows)}' - "
" - ) - - -def chart_body(data: Any | None) -> str: - payload = as_dict(data) - title = payload.get("title") or "Chart" - items = as_list(payload.get("items")) - values = [_safe_float(as_dict(i).get("value"), 0.0) for i in items] - max_v = max(values or [1], default=1) or 1 - bars = [] - for item, value in zip(items, values): - item = as_dict(item) - height = (value / max_v) * 140 - bars.append( - '
' - f'
' - f'
{esc(item.get("label"))}
' - "
" - ) - return f'

{esc(title)}

{"".join(bars)}
' - - -def _offer_slice_html(sl: dict) -> str: - origin = place_code(sl.get("origin")) - dest = place_code(sl.get("destination")) - duration = format_duration(sl.get("duration")) - segs = as_list(sl.get("segments")) - first = as_dict(segs[0] if segs else {}) - last = as_dict(segs[-1] if segs else first) - dep = pick(first, "departing_at", "departingAt", "departureTime", default="") or pick( - sl, "departing_at", "departingAt", "departureTime", default="" - ) - arr = pick(last, "arriving_at", "arrivingAt", "arrivalTime", default="") or pick( - sl, "arriving_at", "arrivingAt", "arrivalTime", default="" - ) - carrier = first.get("marketing_carrier") or first.get("airline") or sl.get("airline") - if isinstance(carrier, str): - airline = carrier - flight_no = pick(first, "marketing_carrier_flight_number", "flightNumber", default="") or pick( - sl, "flightNumber", "marketing_carrier_flight_number", default="" - ) - else: - carrier = as_dict(carrier) - airline = pick(carrier, "name", default="") or pick(first, "airline", default="") or pick(sl, "airline", default="") - flight_no = pick(carrier, "flight_number", "flightNumber", default="") or pick( - first, "marketing_carrier_flight_number", "flightNumber", default="" - ) or pick(sl, "flightNumber", default="") - return ( - f'
{esc(origin)} → {esc(dest)}' - f'
{esc(dep)} – {esc(arr)} · {esc(duration)}
' - f'
{esc(airline)} {esc(flight_no)}
' - ) - - -def _offer_itinerary_html(offer: dict) -> str: - slices = as_list(offer.get("slices")) - if slices: - return "".join(_offer_slice_html(as_dict(s)) for s in slices) - parts = [] - outbound = offer.get("outbound") - if outbound: - parts.append(_offer_slice_html(as_dict(outbound))) - ret = offer.get("return") - if ret: - parts.append(_offer_slice_html(as_dict(ret))) - return "".join(parts) or _offer_slice_html(offer) - - -def flight_search_results_body(data: Any | None) -> str: - payload = as_dict(data) - offers = as_list(payload.get("offers") or payload.get("results")) - if data is None: - return ( - "

Flight search

" - '
Waiting for search_flights result.
' - '
' - ) - params = as_dict(payload.get("searchParams")) - total = payload.get("totalOffers") - if total is None: - total = len(offers) - if params.get("origin") and params.get("destination"): - meta = f"{params.get('origin')} → {params.get('destination')} · {total} offer" + ("" if total == 1 else "s") - else: - meta = f"{total} offer" + ("" if total == 1 else "s") - cards = [] - for offer in offers: - offer = as_dict(offer) - amount = pick(offer, "total_amount", "totalAmount", default="") - currency = pick(offer, "total_currency", "totalCurrency", default="") - slice_html = _offer_itinerary_html(offer) - offer_id = offer.get("id") or "" - cards.append( - f'
' - f'
{esc(money(amount, currency))}' - f'{esc(offer_id)}
{slice_html}
' - ) - if not cards: - cards.append('
No flight offers.
') - return ( - "

Flight search

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

Flight details

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

Flight details

" - f'
Offer {esc(offer_id)} · {esc(money(amount, currency))}
' - f'
{slice_html}{seats}
' - ) - - -def airport_search_body(data: Any | None) -> str: - payload = as_dict(data) - results = as_list(payload.get("results") or payload.get("airports") or payload.get("places")) - query = payload.get("query") or "" - if data is None: - return ( - "

Airport search

" - '
Waiting for search_airports result.
' - '
' - ) - rows = [] - for item in results: - item = as_dict(item) - code = pick(item, "iata_code", "iataCode", default="") - name = pick(item, "name", default="") - city = pick(item, "city_name", "cityName", "city", default="") - kind = pick(item, "type", default="airport") - rows.append( - f'
{esc(code)}' - f'
{esc(name)}
' - f'
{esc(city)} · {esc(kind)}
' - ) - if not rows: - rows.append('
No airports found.
') - return ( - "

Airport search

" - f'
Query: {esc(query)} · {len(results)} result(s)
' - f'
{"".join(rows)}
' - ) - - -def order_summary_body(data: Any | None) -> str: - payload = as_dict(data) - if data is None or not payload: - return ( - "

Order summary

" - '
Waiting for order result.
' - '
' - ) - status = str(pick(payload, "status", default="held")) - ref = pick(payload, "booking_reference", "bookingReference", default="") - amount = pick(payload, "total_amount", "totalAmount", default="") - currency = pick(payload, "total_currency", "totalCurrency", default="") - passengers = as_list(payload.get("passengers")) - pax = [] - for p in passengers: - p = as_dict(p) - name = pick(p, "name", default="") or " ".join( - str(x) for x in (p.get("given_name") or p.get("givenName"), p.get("family_name") or p.get("familyName")) if x - ) - pax.append(f'
{esc(name or p.get("id"))}
') - slices = "".join(_offer_slice_html(as_dict(s)) for s in as_list(payload.get("slices"))) - order_id = payload.get("id") or payload.get("orderId") or "" - cancel = "" - if order_id and status.lower() not in {"cancelled", "canceled"}: - cancel = ( - f'
' - ) - return ( - '
' - f'

Order {esc(status)}

' - f'
Ref {esc(ref)} · {esc(order_id)}
' - f'
{esc(money(amount, currency))}
' - f'

Passengers

{"".join(pax) or "
None listed
"}' - f'

Itinerary

{slices}' - f"{cancel}" - "
" - '
' - ) - - -def _seat_cells(cabin: dict) -> str: - rows_html = [] - rows = as_list(cabin.get("rows")) - if rows: - for row in rows: - row = as_dict(row) - seats = as_list(row.get("seats") or row.get("elements")) - if not seats: - for section in as_list(row.get("sections")): - seats.extend(as_list(as_dict(section).get("elements"))) - cells = [] - for seat in seats: - seat = as_dict(seat) - if seat.get("type") and seat.get("type") != "seat": - continue - designator = pick(seat, "designator", "id", "column", default="") - available = seat.get("available") - if available is None: - available = bool(seat.get("available_services") is not None) - cls = "seat ok" if available else "seat no" - cells.append(f'{esc(designator)}') - rows_html.append( - f'
{esc(row.get("row_number") or row.get("rowNumber") or "")}' - f"{''.join(cells)}
" - ) - return "".join(rows_html) - - -def seat_selection_body(data: Any | None) -> str: - payload = as_dict(data) - cabins = as_list(payload.get("cabins")) - if data is None: - return ( - "

Seat map

" - '
Waiting for get_seat_map result.
' - '
' - ) - blocks = [] - for cabin in cabins: - cabin = as_dict(cabin) - klass = pick(cabin, "cabin_class", "cabinClass", default="cabin") - blocks.append(f'

{esc(klass)}

{_seat_cells(cabin)}') - if not blocks: - blocks.append('
No seat map data.
') - return ( - "

Seat map

" - f'
Offer {esc(payload.get("offerId") or payload.get("offer_id"))}
' - f'
{"".join(blocks)}
' - ) - - -def order_cancellation_body(data: Any | None) -> str: - payload = as_dict(data) - if data is None or not payload: - return ( - "

Cancellation

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

Booking cancelled

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

{esc(msg)}

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

{esc(route)}

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

Widget template missing

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

{esc(name)}

' + f'
{esc(price_text)}
' + f'

{esc(desc)}

' + "
" + ) + + +def table_body(data: Any | None) -> str: + payload = as_dict(data) + rows = as_list(payload.get("rows")) + cols = as_list(payload.get("columns")) + if not cols and rows: + cols = list(as_dict(rows[0]).keys()) + header = "".join(f"{esc(c)}" for c in cols) + body_rows = [] + for row in rows: + row = as_dict(row) + cells = "".join(f"{esc(row.get(c, ''))}" for c in cols) + body_rows.append(f"{cells}") + return ( + "" + f'{header}' + f'{"".join(body_rows)}' + "
" + ) + + +def chart_body(data: Any | None) -> str: + payload = as_dict(data) + title = payload.get("title") or "Chart" + items = as_list(payload.get("items")) + values = [_safe_float(as_dict(i).get("value"), 0.0) for i in items] + max_v = max(values or [1], default=1) or 1 + bars = [] + for item, value in zip(items, values): + item = as_dict(item) + height = (value / max_v) * 140 + bars.append( + '
' + f'
' + f'
{esc(item.get("label"))}
' + "
" + ) + return f'

{esc(title)}

{"".join(bars)}
' + + +def generic_body(route: str, data: Any | None) -> str: + import json + + if data is None: + preview = "Waiting for host to send tool output…" + else: + preview = json.dumps(data, indent=2, default=str) + return ( + f"

{esc(route)}

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

Widget template missing

" + f'
No HTML found for route {esc(route)}. ' + f"Create widgets/out/{esc(route)}.html or run nitrostack-py init again.
" + '
' + ) diff --git a/nitrostack/widgets/views_flight.py b/nitrostack/widgets/views_flight.py new file mode 100644 index 0000000..6b72c62 --- /dev/null +++ b/nitrostack/widgets/views_flight.py @@ -0,0 +1,273 @@ +"""Flight search, details, airport, order, seat and cancellation widget bodies.""" + +from __future__ import annotations + +from typing import Any + +from nitrostack.widgets.html_util import ( + as_dict, + as_list, + esc, + format_duration, + money, + pick, + place_code, +) +from nitrostack.widgets.ui import call_attrs + + +def _offer_slice_html(sl: dict) -> str: + origin = place_code(sl.get("origin")) + dest = place_code(sl.get("destination")) + duration = format_duration(sl.get("duration")) + segs = as_list(sl.get("segments")) + first = as_dict(segs[0] if segs else {}) + last = as_dict(segs[-1] if segs else first) + dep = pick(first, "departing_at", "departingAt", "departureTime", default="") or pick( + sl, "departing_at", "departingAt", "departureTime", default="" + ) + arr = pick(last, "arriving_at", "arrivingAt", "arrivalTime", default="") or pick( + sl, "arriving_at", "arrivingAt", "arrivalTime", default="" + ) + carrier = first.get("marketing_carrier") or first.get("airline") or sl.get("airline") + if isinstance(carrier, str): + airline = carrier + flight_no = pick(first, "marketing_carrier_flight_number", "flightNumber", default="") or pick( + sl, "flightNumber", "marketing_carrier_flight_number", default="" + ) + else: + carrier = as_dict(carrier) + airline = pick(carrier, "name", default="") or pick(first, "airline", default="") or pick(sl, "airline", default="") + flight_no = pick(carrier, "flight_number", "flightNumber", default="") or pick( + first, "marketing_carrier_flight_number", "flightNumber", default="" + ) or pick(sl, "flightNumber", default="") + return ( + f'
{esc(origin)} → {esc(dest)}' + f'
{esc(dep)} – {esc(arr)} · {esc(duration)}
' + f'
{esc(airline)} {esc(flight_no)}
' + ) + + +def _offer_itinerary_html(offer: dict) -> str: + slices = as_list(offer.get("slices")) + if slices: + return "".join(_offer_slice_html(as_dict(s)) for s in slices) + parts = [] + outbound = offer.get("outbound") + if outbound: + parts.append(_offer_slice_html(as_dict(outbound))) + ret = offer.get("return") + if ret: + parts.append(_offer_slice_html(as_dict(ret))) + return "".join(parts) or _offer_slice_html(offer) + + +def flight_search_results_body(data: Any | None) -> str: + payload = as_dict(data) + offers = as_list(payload.get("offers") or payload.get("results")) + if data is None: + return ( + "

Flight search

" + '
Waiting for search_flights result.
' + '
' + ) + params = as_dict(payload.get("searchParams")) + total = payload.get("totalOffers") + if total is None: + total = len(offers) + if params.get("origin") and params.get("destination"): + meta = f"{params.get('origin')} → {params.get('destination')} · {total} offer" + ("" if total == 1 else "s") + else: + meta = f"{total} offer" + ("" if total == 1 else "s") + cards = [] + for offer in offers: + offer = as_dict(offer) + amount = pick(offer, "total_amount", "totalAmount", default="") + currency = pick(offer, "total_currency", "totalCurrency", default="") + slice_html = _offer_itinerary_html(offer) + offer_id = offer.get("id") or "" + cards.append( + f'
' + f'
{esc(money(amount, currency))}' + f'{esc(offer_id)}
{slice_html}
' + ) + if not cards: + cards.append('
No flight offers.
') + return ( + "

Flight search

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

Flight details

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

Flight details

" + f'
Offer {esc(offer_id)} · {esc(money(amount, currency))}
' + f'
{slice_html}{seats}
' + ) + + +def airport_search_body(data: Any | None) -> str: + payload = as_dict(data) + results = as_list(payload.get("results") or payload.get("airports") or payload.get("places")) + query = payload.get("query") or "" + if data is None: + return ( + "

Airport search

" + '
Waiting for search_airports result.
' + '
' + ) + rows = [] + for item in results: + item = as_dict(item) + code = pick(item, "iata_code", "iataCode", default="") + name = pick(item, "name", default="") + city = pick(item, "city_name", "cityName", "city", default="") + kind = pick(item, "type", default="airport") + rows.append( + f'
{esc(code)}' + f'
{esc(name)}
' + f'
{esc(city)} · {esc(kind)}
' + ) + if not rows: + rows.append('
No airports found.
') + return ( + "

Airport search

" + f'
Query: {esc(query)} · {len(results)} result(s)
' + f'
{"".join(rows)}
' + ) + + +def order_summary_body(data: Any | None) -> str: + payload = as_dict(data) + if data is None or not payload: + return ( + "

Order summary

" + '
Waiting for order result.
' + '
' + ) + status = str(pick(payload, "status", default="held")) + ref = pick(payload, "booking_reference", "bookingReference", default="") + amount = pick(payload, "total_amount", "totalAmount", default="") + currency = pick(payload, "total_currency", "totalCurrency", default="") + passengers = as_list(payload.get("passengers")) + pax = [] + for p in passengers: + p = as_dict(p) + name = pick(p, "name", default="") or " ".join( + str(x) for x in (p.get("given_name") or p.get("givenName"), p.get("family_name") or p.get("familyName")) if x + ) + pax.append(f'
{esc(name or p.get("id"))}
') + slices = "".join(_offer_slice_html(as_dict(s)) for s in as_list(payload.get("slices"))) + order_id = payload.get("id") or payload.get("orderId") or "" + cancel = "" + if order_id and status.lower() not in {"cancelled", "canceled"}: + cancel = ( + f'
' + ) + return ( + '
' + f'

Order {esc(status)}

' + f'
Ref {esc(ref)} · {esc(order_id)}
' + f'
{esc(money(amount, currency))}
' + f'

Passengers

{"".join(pax) or "
None listed
"}' + f'

Itinerary

{slices}' + f"{cancel}" + "
" + '
' + ) + + +def _seat_cells(cabin: dict) -> str: + rows_html = [] + rows = as_list(cabin.get("rows")) + if rows: + for row in rows: + row = as_dict(row) + seats = as_list(row.get("seats") or row.get("elements")) + if not seats: + for section in as_list(row.get("sections")): + seats.extend(as_list(as_dict(section).get("elements"))) + cells = [] + for seat in seats: + seat = as_dict(seat) + if seat.get("type") and seat.get("type") != "seat": + continue + designator = pick(seat, "designator", "id", "column", default="") + available = seat.get("available") + if available is None: + available = bool(seat.get("available_services") is not None) + cls = "seat ok" if available else "seat no" + cells.append(f'{esc(designator)}') + rows_html.append( + f'
{esc(row.get("row_number") or row.get("rowNumber") or "")}' + f"{''.join(cells)}
" + ) + return "".join(rows_html) + + +def seat_selection_body(data: Any | None) -> str: + payload = as_dict(data) + cabins = as_list(payload.get("cabins")) + if data is None: + return ( + "

Seat map

" + '
Waiting for get_seat_map result.
' + '
' + ) + blocks = [] + for cabin in cabins: + cabin = as_dict(cabin) + klass = pick(cabin, "cabin_class", "cabinClass", default="cabin") + blocks.append(f'

{esc(klass)}

{_seat_cells(cabin)}') + if not blocks: + blocks.append('
No seat map data.
') + return ( + "

Seat map

" + f'
Offer {esc(payload.get("offerId") or payload.get("offer_id"))}
' + f'
{"".join(blocks)}
' + ) + + +def order_cancellation_body(data: Any | None) -> str: + payload = as_dict(data) + if data is None or not payload: + return ( + "

Cancellation

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

Booking cancelled

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

{esc(msg)}

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

Pizza shops

" + f'
{esc(meta)}
' + '
' + '' + '' + "
" + f'
{cards}
' + '
' + ) + + +def _pizza_map_card(shop: dict) -> str: + name = shop.get("name") or shop.get("id") or "Shop" + shop_id = shop.get("id") or "" + rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else "" + return ( + f'
' + f'
{esc(name)}
' + f'
{esc(shop.get("address"))}
' + f'
{rating}
' + ) + + +def pizza_map_body(data: Any | None) -> str: + payload = as_dict(data) + shops = as_list(payload.get("shops")) + static = "" + if data is None or not shops: + meta = "Waiting for show_pizza_map result." + cards = "" + else: + filt = payload.get("filter") or "all" + total = payload.get("totalShops") + if total is None: + total = len(shops) + meta = f"{total} shops · filter: {filt}" + cards = "".join(_pizza_map_card(as_dict(shop)) for shop in shops) + static_src = mapbox_static_url(shops) + static = ( + f'Pizza shop map' + if static_src + else "" + ) + return ( + f'
{esc(meta)}
' + f'
' + f'
{static}
' + f'
{cards}
' + '
' + ) + + +def pizza_shop_body(data: Any | None) -> str: + payload = as_dict(data) + shop = as_dict(payload.get("shop") or payload if data is not None else {}) + if data is None or not shop.get("name"): + return ( + '
' + '' + '

Pizza shop

' + '
' + '

Waiting for show_pizza_shop result.

' + '

' + '

' + '

' + '
' + '
' + "
" + '
' + ) + img = "" + if shop.get("image"): + img = f'' + else: + img = '' + rating = "" + if shop.get("rating") is not None: + rating = f"★ {esc(shop.get('rating'))} ({esc(shop.get('reviews') or 0)} reviews)" + hours = as_dict(shop.get("hours")) + hours_text = "" + if hours.get("open") or hours.get("close"): + hours_text = f"Hours: {esc(hours.get('open'))} – {esc(hours.get('close'))}" + chips = "".join( + f'{esc(item)}' for item in as_list(shop.get("specialties")) + ) + actions = action_row(maps=maps_url(shop), phone=str(shop.get("phone") or ""), website=str(shop.get("website") or "")) + return ( + '
' + f"{img}" + f'

{esc(shop.get("name"))}

' + f'
{rating}
' + f'

{esc(shop.get("description"))}

' + f'

{esc(shop.get("address"))}

' + f'

{hours_text}

' + f'

{esc(shop.get("phone"))}

' + f'
{chips}
' + f"{actions}" + "
" + '
' + ) From e26a077af9c5df30588d8807f5b05dd0f753942b Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Sun, 8 Nov 2026 12:21:12 +0530 Subject: [PATCH 119/146] fix(cli): resolve widget helpers by data flow and import binding (#116) validate used a project-wide name match, so panel('dashboard') was checked for dashboard.html even when panel never passed that argument to WidgetOptions.route, and an unrelated panel in another module could be taken for a widget factory. Route discovery moves to nitrostack/cli/widget_routes.py and parses each file: - a function is a factory only if one of its parameters reaches WidgetOptions(route=...) (directly, or through another factory) and is not reassigned - the string is read from the argument at that parameter's position or keyword - a call counts only if its name resolves through the calling module's own definitions and imports (local def, from-import, alias, import module, relative import, class staticmethod/classmethod) to a real factory - a file that does not parse still yields its literal routes validators.py keeps only the file walk, so it drops from 499 to 454 lines. --- nitrostack/cli/validators.py | 49 +----- nitrostack/cli/widget_routes.py | 272 ++++++++++++++++++++++++++++++++ tests/test_validate_widgets.py | 111 ++++++++++++- 3 files changed, 381 insertions(+), 51 deletions(-) create mode 100644 nitrostack/cli/widget_routes.py diff --git a/nitrostack/cli/validators.py b/nitrostack/cli/validators.py index a03a252..2154299 100644 --- a/nitrostack/cli/validators.py +++ b/nitrostack/cli/validators.py @@ -11,6 +11,7 @@ from dataclasses import dataclass from typing import Any, Iterable, List, Optional, Sequence, Set, Tuple +from nitrostack.cli.widget_routes import collect_widget_routes from packaging.specifiers import InvalidSpecifier, SpecifierSet from packaging.version import InvalidVersion, Version @@ -374,40 +375,10 @@ def validate_module_references(root: str) -> List[ValidationIssue]: return issues -_WIDGET_DECORATOR_RE = re.compile(r"""@widget\(\s*["']([^"']+)["']""") -_WIDGET_OPTIONS_RE = re.compile(r"""WidgetOptions\(\s*route\s*=\s*["']([^"']+)["']""") -# A helper that builds the options from one route: @widget(my_widget("route")) or -# @widget(my_widget(route="route", ...)). Only helpers defined in the project that -# build a WidgetOptions count (see _widget_helper_names), so an unrelated call such as -# @widget(something("x")) is not taken as a route. A call with other positional -# arguments is skipped, because its first string is not necessarily the route. -_WIDGET_HELPER_RE = re.compile( - r"""@widget\(\s*([A-Za-z_][\w.]*)\(\s*(?:["']([^"']+)["']\s*\)|route\s*=\s*["']([^"']+)["']\s*[,)])""" -) _WIDGET_ROUTE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") -def _widget_helper_names(texts: Iterable[str]) -> Set[str]: - """Names of functions that build a ``WidgetOptions``, plus ``WidgetOptions`` itself.""" - names = {"WidgetOptions"} - for text in texts: - try: - tree = ast.parse(text) - except (SyntaxError, ValueError): - continue - for fn in ast.walk(tree): - if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) and any( - isinstance(call, ast.Call) - and getattr(call.func, "id", getattr(call.func, "attr", None)) == "WidgetOptions" - for call in ast.walk(fn) - ): - names.add(fn.name) - return names - - def _collect_widget_routes(root: str) -> List[Tuple[str, str]]: - found: List[Tuple[str, str]] = [] - seen: Set[str] = set() root_abs = os.path.abspath(root) sources: List[Tuple[str, str]] = [] @@ -424,23 +395,7 @@ def _collect_widget_routes(root: str) -> List[Tuple[str, str]]: except OSError: continue - helpers = _widget_helper_names(text for _, text in sources) - for rel_path, text in sources: - helper_routes = [ - positional or keyword - for name, positional, keyword in _WIDGET_HELPER_RE.findall(text) - if name.rsplit(".", 1)[-1] in helpers - ] - for route in ( - _WIDGET_DECORATOR_RE.findall(text) - + _WIDGET_OPTIONS_RE.findall(text) - + helper_routes - ): - if route not in seen: - seen.add(route) - found.append((route, rel_path)) - - return found + return collect_widget_routes(sources) diff --git a/nitrostack/cli/widget_routes.py b/nitrostack/cli/widget_routes.py new file mode 100644 index 0000000..eb29626 --- /dev/null +++ b/nitrostack/cli/widget_routes.py @@ -0,0 +1,272 @@ +"""Static discovery of ``@widget`` routes for ``nitrostack-py validate``. + +Nothing is imported or run. Each project file is parsed and routes are found in three +ways: a string literal (``@widget("card")``), a ``WidgetOptions`` call with a literal +route, and a call to a *factory*, meaning a function whose parameter reaches +``WidgetOptions(route=...)`` (``@widget(my_widget("pizza-map"))``). + +A factory call only counts when the name resolves, through the calling module's own +definitions and imports, to a real factory, and the string sits in the argument that +feeds ``route``. So ``panel("x")`` is ignored when ``panel`` never passes that argument +to ``route``, or when it is an unrelated ``panel`` from another module. +""" + +from __future__ import annotations + +import ast +import os +import re +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Optional, Tuple + +# Only used for a file that does not parse, so a broken file still gets its literal routes. +_LEGACY_DECORATOR_RE = re.compile(r"""@widget\(\s*["']([^"']+)["']""") +_LEGACY_OPTIONS_RE = re.compile(r"""WidgetOptions\(\s*route\s*=\s*["']([^"']+)["']""") + +_WIDGET_OPTIONS = object() # the SDK's WidgetOptions class +_NITROSTACK = object() # the nitrostack package or one of its submodules +_PLAIN = object() # a project function or class that is not a factory + + +@dataclass(frozen=True) +class _Factory: + param: str # the parameter that feeds WidgetOptions.route + index: int # its position among the positional parameters, -1 if keyword-only + + +@dataclass +class _Namespace: + """A project module or a class, with the names it defines.""" + + name: str + defs: Dict[str, object] = field(default_factory=dict) + + +@dataclass +class _Module: + name: str + package: Tuple[str, ...] + tree: Optional[ast.Module] + text: str + ns: _Namespace + imports: Dict[str, Tuple[str, str]] = field(default_factory=dict) # local -> (module, attr) + funcs: List[Tuple[ast.AST, str, _Namespace]] = field(default_factory=list) # node, kind, owner + + +def _dotted(rel_path: str) -> Tuple[str, Tuple[str, ...]]: + parts = os.path.normpath(rel_path).split(os.sep) + parts[-1] = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1] + is_package = parts[-1] == "__init__" + if is_package: + parts = parts[:-1] + return ".".join(parts), tuple(parts if is_package else parts[:-1]) + + +def _is_nitrostack(module: str) -> bool: + return module == "nitrostack" or module.startswith("nitrostack.") + + +class _Project: + def __init__(self, sources: Iterable[Tuple[str, str]]): + self.modules: Dict[str, _Module] = {} + self.order: List[Tuple[str, _Module]] = [] + for rel_path, text in sources: + name, package = _dotted(rel_path) + try: + tree: Optional[ast.Module] = ast.parse(text) + except (SyntaxError, ValueError): + tree = None + module = _Module(name, package, tree, text, _Namespace(name)) + self.order.append((rel_path, module)) + self.modules[name] = module + if tree is not None: + self._index(module) + self._find_factories() + + # -- indexing --------------------------------------------------------------- + + def _index(self, module: _Module) -> None: + assert module.tree is not None + for node in ast.walk(module.tree): + if isinstance(node, ast.Import): + for alias in node.names: + if alias.asname: + module.imports[alias.asname] = (alias.name, "") + else: + top = alias.name.split(".")[0] + module.imports[top] = (top, "") + elif isinstance(node, ast.ImportFrom): + source = self._absolute(module, node) + if source is None: + continue + for alias in node.names: + if alias.name != "*": + module.imports[alias.asname or alias.name] = (source, alias.name) + for node in module.tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + module.ns.defs[node.name] = _PLAIN + module.funcs.append((node, "func", module.ns)) + elif isinstance(node, ast.ClassDef): + cls = _Namespace(f"{module.name}.{node.name}") + module.ns.defs[node.name] = cls + for item in node.body: + kind = self._method_kind(item) + if kind: + cls.defs[item.name] = _PLAIN + module.funcs.append((item, kind, cls)) + + @staticmethod + def _method_kind(item: ast.AST) -> Optional[str]: + if not isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): + return None + names = {d.id for d in item.decorator_list if isinstance(d, ast.Name)} + if "staticmethod" in names: + return "static" + return "class" if "classmethod" in names else None # instance methods need an object + + @staticmethod + def _absolute(module: _Module, node: ast.ImportFrom) -> Optional[str]: + if not node.level: + return node.module + keep = len(module.package) - (node.level - 1) + if keep < 0: + return None + base = list(module.package[:keep]) + ([node.module] if node.module else []) + return ".".join(base) + + # -- name resolution -------------------------------------------------------- + + def _find(self, dotted: str) -> Optional[_Module]: + if dotted in self.modules: + return self.modules[dotted] + matches = [m for key, m in self.modules.items() if key.endswith("." + dotted)] + return matches[0] if len(matches) == 1 else None # e.g. a src/ layout + + def _name(self, module: _Module, name: str) -> object: + if name in module.ns.defs: + return module.ns.defs[name] + imported = module.imports.get(name) + if imported: + source, attr = imported + if _is_nitrostack(source): + return _WIDGET_OPTIONS if attr == "WidgetOptions" else _NITROSTACK + if not attr: + found = self._find(source) + return found.ns if found else None + found = self._find(source) + if found and attr in found.ns.defs: + return found.ns.defs[attr] + sub = self._find(f"{source}.{attr}") # ``from pkg import module`` + return sub.ns if sub else None + return _WIDGET_OPTIONS if name == "WidgetOptions" else None + + def resolve(self, expr: ast.AST, module: _Module) -> object: + if isinstance(expr, ast.Name): + return self._name(module, expr.id) + if isinstance(expr, ast.Attribute): + base = self.resolve(expr.value, module) + if base is _NITROSTACK: + return _WIDGET_OPTIONS if expr.attr == "WidgetOptions" else _NITROSTACK + if isinstance(base, _Namespace): + if expr.attr in base.defs: + return base.defs[expr.attr] + sub = self._find(f"{base.name}.{expr.attr}") + return sub.ns if sub else None + return None + + @staticmethod + def route_arg(call: ast.Call, target: object) -> Optional[ast.AST]: + """The expression passed where ``target`` expects the route, if it is passed at all.""" + if target is _WIDGET_OPTIONS: + name, index = "route", 0 + elif isinstance(target, _Factory): + name, index = target.param, target.index + else: + return None + if 0 <= index < len(call.args): + if any(isinstance(arg, ast.Starred) for arg in call.args[: index + 1]): + return None + return call.args[index] + for keyword in call.keywords: + if keyword.arg == name: + return keyword.value + return None + + # -- factories -------------------------------------------------------------- + + def _factory_of(self, module: _Module, fn: ast.AST, kind: str) -> Optional[_Factory]: + positional = [a.arg for a in fn.args.posonlyargs + fn.args.args] # type: ignore[attr-defined] + if kind == "class": + positional = positional[1:] + params = positional + [a.arg for a in fn.args.kwonlyargs] # type: ignore[attr-defined] + reassigned = { + n.id for n in ast.walk(fn) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store) + } + for call in (n for n in ast.walk(fn) if isinstance(n, ast.Call)): + expr = self.route_arg(call, self.resolve(call.func, module)) + if isinstance(expr, ast.Name) and expr.id in params and expr.id not in reassigned: + return _Factory(expr.id, positional.index(expr.id) if expr.id in positional else -1) + return None + + def _find_factories(self) -> None: + # Repeat so a function that forwards its parameter to another factory is found too. + for _ in range(sum(len(m.funcs) for _, m in self.order) + 1): + changed = False + for _, module in self.order: + for fn, kind, owner in module.funcs: + if owner.defs.get(fn.name) is not _PLAIN: # type: ignore[attr-defined] + continue + factory = self._factory_of(module, fn, kind) + if factory: + owner.defs[fn.name] = factory # type: ignore[attr-defined] + changed = True + if not changed: + break + + # -- routes ----------------------------------------------------------------- + + def _literal(self, expr: Optional[ast.AST]) -> Optional[str]: + if isinstance(expr, ast.Constant) and isinstance(expr.value, str): + return expr.value + return None + + def routes_in(self, module: _Module) -> List[str]: + if module.tree is None: + return _LEGACY_DECORATOR_RE.findall(module.text) + _LEGACY_OPTIONS_RE.findall(module.text) + found: List[Tuple[int, int, str]] = [] + for node in ast.walk(module.tree): + for decorator in getattr(node, "decorator_list", []): + func = getattr(decorator, "func", None) + is_widget = (isinstance(func, ast.Name) and func.id == "widget") or ( + isinstance(func, ast.Attribute) and func.attr == "widget" + ) + if isinstance(decorator, ast.Call) and is_widget and decorator.args: + route = self._decorator_route(decorator.args[0], module) + if route: + found.append((decorator.lineno, decorator.col_offset, route)) + if isinstance(node, ast.Call) and self.resolve(node.func, module) is _WIDGET_OPTIONS: + route = self._literal(self.route_arg(node, _WIDGET_OPTIONS)) + if route: + found.append((node.lineno, node.col_offset, route)) + return [route for _, _, route in sorted(found)] + + def _decorator_route(self, expr: ast.AST, module: _Module) -> Optional[str]: + literal = self._literal(expr) + if literal is not None: + return literal + if isinstance(expr, ast.Call): + return self._literal(self.route_arg(expr, self.resolve(expr.func, module))) + return None + + +def collect_widget_routes(sources: Iterable[Tuple[str, str]]) -> List[Tuple[str, str]]: + """``(route, rel_path)`` for every route found in ``(rel_path, source_text)`` pairs.""" + project = _Project(sources) + found: List[Tuple[str, str]] = [] + seen = set() + for rel_path, module in project.order: + for route in project.routes_in(module): + if route not in seen: + seen.add(route) + found.append((route, rel_path)) + return found diff --git a/tests/test_validate_widgets.py b/tests/test_validate_widgets.py index 62d5a1c..ba5dfae 100644 --- a/tests/test_validate_widgets.py +++ b/tests/test_validate_widgets.py @@ -120,13 +120,15 @@ def test_helper_wrapped_route_with_html_passes(tmp_path: Path): assert validate_widgets(str(tmp_path)) == [] -def test_helper_call_with_other_positional_arguments_is_not_guessed(tmp_path: Path): +def test_route_is_read_from_the_argument_that_feeds_it(tmp_path: Path): src = ( "from nitrostack import WidgetOptions, widget\n" - "def helper(route, flag): return WidgetOptions(route=route)\n" - "@widget(helper('not-a-route', True))\ndef f(): ...\n" + "def helper(flag, route): return WidgetOptions(route=route)\n" + "@widget(helper(True, 'second'))\ndef a(): ...\n" + "@widget(helper('first', 'third'))\ndef b(): ...\n" + "@widget(helper(flag=False, route='by-keyword'))\ndef c(): ...\n" ) - assert validate_widgets(str(_project(tmp_path, src))) == [] + assert sorted(_routes(tmp_path, {"tools.py": src})) == ["by-keyword", "second", "third"] def test_unrelated_helper_call_is_not_taken_as_a_route(tmp_path: Path): @@ -205,3 +207,104 @@ def validate(): broken = validate().stdout assert "widget route 'pizza-list'" in broken and "file is missing" in broken assert "pizza-map" not in broken and "pizza-shop" not in broken + + +def _routes(tmp_path: Path, files: dict) -> list: + for name, text in files.items(): + target = tmp_path / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + return [route for route, _ in _collect_widget_routes(str(tmp_path))] + + +FACTORY = "from nitrostack import WidgetOptions\ndef panel(route): return WidgetOptions(route=route)\n" + + +def test_argument_that_does_not_feed_route_is_not_a_route(tmp_path: Path): + # panel("dashboard") builds the "card" widget; dashboard.html is never used. + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def panel(name, description=None):\n" + " return WidgetOptions(route='card', description=description)\n" + "@widget(panel('dashboard'))\ndef f(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["card"] + assert validate_widgets(str(tmp_path))[0].message.startswith("widget route 'card'") + assert len(validate_widgets(str(tmp_path))) == 1 + + +def test_reassigned_or_forwarded_to_something_else_is_not_a_factory(tmp_path: Path): + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def fixed(route):\n route = 'always-this'\n return WidgetOptions(route=route)\n" + "def other(route): return WidgetOptions(route='card', description=route)\n" + "@widget(fixed('x'))\ndef a(): ...\n@widget(other('y'))\ndef b(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["card"] + + +def test_same_helper_name_in_another_module_is_not_a_factory(tmp_path: Path): + files = { + "factory.py": FACTORY, + "unrelated.py": ( + "from nitrostack import widget\n" + "def panel(name): return {'name': name}\n" + "@widget(panel('not-a-route'))\ndef f(): ...\n" + ), + "undefined.py": "from nitrostack import widget\n@widget(panel('also-not'))\ndef g(): ...\n", + "other_lib.py": ( + "from some_library import panel\nfrom nitrostack import widget\n" + "@widget(panel('third-party'))\ndef h(): ...\n" + ), + } + assert _routes(tmp_path, files) == [] + + +def test_factory_is_resolved_through_the_calling_modules_imports(tmp_path: Path): + files = { + "factory.py": FACTORY, + "plain.py": "from factory import panel\nfrom nitrostack import widget\n@widget(panel('plain'))\ndef a(): ...\n", + "aliased.py": "from factory import panel as build\nfrom nitrostack import widget\n@widget(build('aliased'))\ndef b(): ...\n", + "module.py": "import factory as fx\nfrom nitrostack import widget\n@widget(fx.panel('via-module'))\ndef c(): ...\n", + "pkg/__init__.py": "", + "pkg/helpers.py": FACTORY, + "pkg/tools.py": "from .helpers import panel\nfrom nitrostack import widget\n@widget(panel('relative'))\ndef d(): ...\n", + "pkg/sub.py": "from pkg import helpers\nfrom nitrostack import widget\n@widget(helpers.panel('pkg-module'))\ndef e(): ...\n", + } + assert sorted(_routes(tmp_path, files)) == ["aliased", "pkg-module", "plain", "relative", "via-module"] + + +def test_a_local_definition_wins_over_an_import_of_the_same_name(tmp_path: Path): + files = { + "factory.py": FACTORY, + "tools.py": ( + "from factory import panel\nfrom nitrostack import widget\n" + "def panel(name): return {'name': name}\n" + "@widget(panel('shadowed'))\ndef f(): ...\n" + ), + } + assert _routes(tmp_path, files) == [] + + +def test_a_factory_that_forwards_to_another_factory_is_found(tmp_path: Path): + src = ( + "from nitrostack import WidgetOptions, widget\n" + "def base(route): return WidgetOptions(route=route)\n" + "def wrapped(r): return base(r)\n" + "@widget(wrapped('deep'))\ndef f(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["deep"] + + +def test_unimported_widget_options_alias_and_attribute_forms(tmp_path: Path): + src = ( + "import nitrostack\nfrom nitrostack import WidgetOptions as WO, widget\n" + "@widget(WO(route='aliased-options'))\ndef a(): ...\n" + "@nitrostack.widget(nitrostack.WidgetOptions('attribute-form'))\ndef b(): ...\n" + ) + assert sorted(_routes(tmp_path, {"tools.py": src})) == ["aliased-options", "attribute-form"] + + +def test_a_file_that_does_not_parse_still_yields_its_literal_routes(tmp_path: Path): + src = "@widget('legacy')\ndef f(:\n pass\nWidgetOptions(route='legacy-options')\n" + assert sorted(_routes(tmp_path, {"broken.py": src})) == ["legacy", "legacy-options"] From d88ec06b8432e649147cd60ddc1eb7907cde073b Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Mon, 9 Nov 2026 18:42:07 +0530 Subject: [PATCH 120/146] Handle missing posthog and drop it from vendored pyproject. Vendored projects do not need the PostHog SDK; the CLI no-ops when import posthog fails. Fix E501 on the default-key comment. Co-Authored-By: Claude Opus 5.5 --- nitrostack/cli/telemetry.py | 15 ++++++++++++--- nitrostack/cli/vendor.py | 1 - tests/test_vendor.py | 1 + 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/nitrostack/cli/telemetry.py b/nitrostack/cli/telemetry.py index e99b778..edd854d 100644 --- a/nitrostack/cli/telemetry.py +++ b/nitrostack/cli/telemetry.py @@ -23,7 +23,8 @@ PRODUCT = "python_sdk" SURFACE = "terminal" -# Public PostHog project key (same CLI/SDK ingest as the TypeScript CLI); override with NITROSTACK_POSTHOG_KEY. +# Public PostHog project key (same CLI/SDK ingest as the TypeScript CLI). +# Override with NITROSTACK_POSTHOG_KEY. DEFAULT_POSTHOG_PROJECT_KEY = "phc_" + "OufG1OuiamSbCBMVHfO70IyFWKBzsiaDpOWqcNwtz6G" DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com" @@ -32,6 +33,7 @@ _POSTHOG_LOCK = threading.Lock() _client: Any = None +_posthog_unavailable = False _anonymous_distinct_id: Optional[str] = None _distinct_id_override: Optional[str] = None _shutdown_done = False @@ -125,12 +127,19 @@ def _super_properties() -> Dict[str, Any]: def _get_client() -> Any: - global _client + global _client, _posthog_unavailable if is_telemetry_disabled(): return None + if _posthog_unavailable: + return None with _POSTHOG_LOCK: if _client is None: - from posthog import Posthog + try: + from posthog import Posthog + except ImportError: + _posthog_unavailable = True + logger.debug("nitrostack telemetry: posthog package not installed") + return None api_key = resolved_posthog_api_key() host = resolved_posthog_host() diff --git a/nitrostack/cli/vendor.py b/nitrostack/cli/vendor.py index 72f384d..af35dd7 100644 --- a/nitrostack/cli/vendor.py +++ b/nitrostack/cli/vendor.py @@ -108,7 +108,6 @@ def _write_minimal_pyproject(dest: Path) -> None: ' "anyio>=4.0.0",\n' ' "packaging>=23.0.0",\n' ' "tomli>=2.0.0; python_version < \'3.11\'",\n' - ' "posthog>=3,<5",\n' "]\n\n" "[project.scripts]\n" 'nitrostack-py = "nitrostack.cli.main:main"\n\n' diff --git a/tests/test_vendor.py b/tests/test_vendor.py index f53be41..f80ca7f 100644 --- a/tests/test_vendor.py +++ b/tests/test_vendor.py @@ -69,6 +69,7 @@ def test_minimal_pyproject_uses_distribution_version(tmp_path: Path, monkeypatch text = (dest / "pyproject.toml").read_text(encoding="utf-8") assert 'version = "9.9.9"' in text assert "0.3.2" not in text + assert "posthog" not in text def test_distribution_version_has_no_hardcoded_fallback(monkeypatch): From d3f10299d6b5e3e5b95dab13492b83988703d3f4 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Mon, 9 Nov 2026 18:42:07 +0530 Subject: [PATCH 121/146] Rewrite telemetry opt-out tests using telemetry_env. Assert capture is blocked under opt-out and allowed otherwise so tests do not pass vacuously under PYTEST_CURRENT_TEST. Co-Authored-By: Claude Opus 5.5 --- tests/test_telemetry.py | 78 ++++++++++++++++++++++++++++++----------- 1 file changed, 58 insertions(+), 20 deletions(-) diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 3a22dbb..17e7ef3 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -31,11 +31,13 @@ def reset_telemetry_state(): """Isolate module globals between tests.""" telemetry_mod._client = None # noqa: SLF001 + telemetry_mod._posthog_unavailable = False # noqa: SLF001 telemetry_mod._anonymous_distinct_id = None # noqa: SLF001 telemetry_mod._distinct_id_override = None # noqa: SLF001 telemetry_mod._shutdown_done = False # noqa: SLF001 yield telemetry_mod._client = None # noqa: SLF001 + telemetry_mod._posthog_unavailable = False # noqa: SLF001 telemetry_mod._anonymous_distinct_id = None # noqa: SLF001 telemetry_mod._distinct_id_override = None # noqa: SLF001 telemetry_mod._shutdown_done = False # noqa: SLF001 @@ -60,37 +62,73 @@ def telemetry_env(monkeypatch, tmp_path): importlib.reload(telemetry_mod) -def test_opt_out_do_not_track(): - os.environ["NITROSTACK_POSTHOG_KEY"] = "phc_x" - os.environ["DO_NOT_TRACK"] = "1" +def _track_with_mock_client(telemetry_env, monkeypatch): + """Return a MagicMock wired as the telemetry PostHog client.""" + mock = MagicMock() + monkeypatch.setattr(telemetry_mod, "get_distinct_id", lambda: "test-distinct-id") + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + return mock + + +def test_opt_out_do_not_track(telemetry_env, monkeypatch): + mock = _track_with_mock_client(telemetry_env, monkeypatch) + track_event("cli_command_invoked", {"command": "baseline"}) + assert mock.capture.call_count == 1 + + monkeypatch.setenv("DO_NOT_TRACK", "1") importlib.reload(telemetry_mod) - assert telemetry_mod.is_telemetry_disabled() is True + mock.reset_mock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_event("cli_command_invoked", {"command": "x"}) + mock.capture.assert_not_called() + +def test_opt_out_telemetry_flag_sends_nothing(telemetry_env, monkeypatch): + mock = _track_with_mock_client(telemetry_env, monkeypatch) + track_event("cli_command_invoked", {"command": "baseline"}) + assert mock.capture.call_count == 1 -def test_opt_out_telemetry_flag_sends_nothing(monkeypatch): - """With opt-out, _get_client is never called.""" - os.environ["NITROSTACK_POSTHOG_KEY"] = "phc_x" - os.environ.pop("DO_NOT_TRACK", None) - os.environ["NITROSTACK_TELEMETRY"] = "0" + monkeypatch.setenv("NITROSTACK_TELEMETRY", "0") importlib.reload(telemetry_mod) - assert telemetry_mod.is_telemetry_disabled() is True - mock_get = MagicMock() - monkeypatch.setattr(telemetry_mod, "_get_client", mock_get) + mock.reset_mock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) track_event("cli_command_invoked", {"command": "x"}) - mock_get.assert_not_called() + mock.capture.assert_not_called() + +def test_ci_default_off_without_explicit_enable(telemetry_env, monkeypatch): + mock = _track_with_mock_client(telemetry_env, monkeypatch) + track_event("cli_command_invoked", {"command": "baseline"}) + assert mock.capture.call_count == 1 -def test_ci_default_off_without_explicit_enable(): - os.environ["NITROSTACK_POSTHOG_KEY"] = "phc_x" - os.environ.pop("DO_NOT_TRACK", None) - os.environ.pop("NITROSTACK_TELEMETRY", None) - os.environ["CI"] = "true" + monkeypatch.setenv("CI", "true") + monkeypatch.delenv("NITROSTACK_TELEMETRY", raising=False) importlib.reload(telemetry_mod) - assert telemetry_mod.is_telemetry_disabled() is True + mock.reset_mock() + monkeypatch.setattr(telemetry_mod, "_get_client", lambda: mock) + track_event("cli_command_invoked", {"command": "x"}) + mock.capture.assert_not_called() + + +def test_posthog_missing_is_silent_noop(telemetry_env, monkeypatch): + import builtins + + real_import = builtins.__import__ + + def guarded_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002 + if name == "posthog": + raise ImportError("posthog not installed") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr(builtins, "__import__", guarded_import) + importlib.reload(telemetry_mod) + track_event("cli_command_invoked", {"command": "x"}) + assert telemetry_mod._posthog_unavailable is True # noqa: SLF001 + track_event("cli_command_invoked", {"command": "y"}) def test_builtin_posthog_key_used_when_env_unset(monkeypatch): - """Without NITROSTACK_POSTHOG_KEY, config resolves to the shipped public project key (no network).""" + """Built-in public project key when NITROSTACK_POSTHOG_KEY is unset (no network).""" monkeypatch.delenv("NITROSTACK_POSTHOG_KEY", raising=False) assert resolved_posthog_api_key() == telemetry_mod.DEFAULT_POSTHOG_PROJECT_KEY From 7971e3f40884b97358db09cb9bd53bd3fd568c43 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Mon, 9 Nov 2026 18:42:07 +0530 Subject: [PATCH 122/146] Document telemetry flush limits and pack dry-run. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/analytics-events.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d1563ed..7031f56 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Once scaffolded, follow the next steps printed by the CLI to run your server, co The CLI is installed with the SDK (`nitrostack-py`, or `python -m nitrostack.cli.main`). Run `nitrostack-py --help` to list commands. -**Usage telemetry** — The CLI sends anonymous usage events to PostHog using a built-in public project key (same CLI/SDK project as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` to override that key, `NITROSTACK_POSTHOG_HOST` to override the ingest URL (default `https://us.i.posthog.com`). Disable with `DO_NOT_TRACK=1` or `NITROSTACK_TELEMETRY=0`. See [`docs/analytics-events.md`](docs/analytics-events.md) for the event list and properties. +**Usage telemetry** — The CLI sends anonymous usage events to PostHog using a built-in public project key (same CLI/SDK project as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` to override that key, `NITROSTACK_POSTHOG_HOST` to override the ingest URL (default `https://us.i.posthog.com`). Disable with `DO_NOT_TRACK=1` or `NITROSTACK_TELEMETRY=0`. Exit runs a best-effort flush (up to 2s); see [`docs/analytics-events.md`](docs/analytics-events.md) for events, opt-out, and delivery notes. ### Project lifecycle diff --git a/docs/analytics-events.md b/docs/analytics-events.md index 65a37fa..5cd6bd2 100644 --- a/docs/analytics-events.md +++ b/docs/analytics-events.md @@ -2,6 +2,10 @@ Telemetry uses a **built-in public PostHog project key** (same ingest as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` only if you need to override that key. Telemetry is **off** when `DO_NOT_TRACK=1`, when `NITROSTACK_TELEMETRY=0` (or `false`/`off`/`no`), during pytest (`PYTEST_CURRENT_TEST`), and in CI when `NITROSTACK_TELEMETRY` is unset (set it to a truthy value to allow capture in CI). +On process exit the CLI runs a **best-effort flush** (PostHog `shutdown` on a background thread, joined for up to **2 seconds**). Events still in the queue after that window may not be delivered; command completion is never blocked longer than that timeout. + +`pack --dry-run` lists files that would be packed but does **not** emit `cli_deploy_completed` or `cli_deploy_failed`. + ## Super properties Sent on every captured event: From b5f6c3db29b5bcb5512ceb7c527e2f76abd3ea34 Mon Sep 17 00:00:00 2001 From: ROHIT-JR Date: Tue, 10 Nov 2026 06:57:47 +0530 Subject: [PATCH 123/146] fix(cli): follow re-exported SDK names and ignore non-SDK .widget decorators in validate Two regressions in the AST route discovery added in #127: - A name re-exported through a project module (for example shared/__init__.py doing `from nitrostack import WidgetOptions`) was not followed, so `from shared import WidgetOptions` skipped the missing-HTML check. Name lookup now follows re-exports through project modules, with a guard against import cycles. - Any decorator ending in `.widget` was treated as the SDK decorator, so `@pytest.mark.widget("smoke")` warned about a missing smoke.html. A `widget` decorator now counts only when it resolves to the SDK's own, by direct import, `import nitrostack`, or a project re-export. Adds regression tests for both, including aliases, multi-hop and cyclic re-exports, and a non-SDK name that is re-exported. --- nitrostack/cli/widget_routes.py | 58 +++++++++++++------ tests/test_validate_widgets.py | 98 +++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+), 18 deletions(-) diff --git a/nitrostack/cli/widget_routes.py b/nitrostack/cli/widget_routes.py index eb29626..c878e4f 100644 --- a/nitrostack/cli/widget_routes.py +++ b/nitrostack/cli/widget_routes.py @@ -5,6 +5,10 @@ route, and a call to a *factory*, meaning a function whose parameter reaches ``WidgetOptions(route=...)`` (``@widget(my_widget("pizza-map"))``). +``widget`` and ``WidgetOptions`` only count when they resolve to the SDK's own, directly, +through ``import nitrostack``, or through a project module that re-exports them, so +``@pytest.mark.widget("smoke")`` is ignored. + A factory call only counts when the name resolves, through the calling module's own definitions and imports, to a real factory, and the string sits in the argument that feeds ``route``. So ``panel("x")`` is ignored when ``panel`` never passes that argument @@ -24,6 +28,7 @@ _LEGACY_OPTIONS_RE = re.compile(r"""WidgetOptions\(\s*route\s*=\s*["']([^"']+)["']""") _WIDGET_OPTIONS = object() # the SDK's WidgetOptions class +_WIDGET = object() # the SDK's @widget decorator _NITROSTACK = object() # the nitrostack package or one of its submodules _PLAIN = object() # a project function or class that is not a factory @@ -142,23 +147,40 @@ def _find(self, dotted: str) -> Optional[_Module]: matches = [m for key, m in self.modules.items() if key.endswith("." + dotted)] return matches[0] if len(matches) == 1 else None # e.g. a src/ layout - def _name(self, module: _Module, name: str) -> object: + @staticmethod + def _sdk(attr: str) -> object: + if attr == "WidgetOptions": + return _WIDGET_OPTIONS + return _WIDGET if attr == "widget" else _NITROSTACK + + def _binding(self, module: _Module, name: str, seen: set) -> object: + """What ``name`` means inside ``module``, following re-exports through project modules.""" + if (module.name, name) in seen: # an import cycle + return None + seen.add((module.name, name)) if name in module.ns.defs: return module.ns.defs[name] imported = module.imports.get(name) - if imported: - source, attr = imported - if _is_nitrostack(source): - return _WIDGET_OPTIONS if attr == "WidgetOptions" else _NITROSTACK - if not attr: - found = self._find(source) - return found.ns if found else None - found = self._find(source) - if found and attr in found.ns.defs: - return found.ns.defs[attr] - sub = self._find(f"{source}.{attr}") # ``from pkg import module`` - return sub.ns if sub else None - return _WIDGET_OPTIONS if name == "WidgetOptions" else None + if not imported: + return None + source, attr = imported + if _is_nitrostack(source): + return self._sdk(attr) + found = self._find(source) + if not attr: + return found.ns if found else None + if found: + bound = self._binding(found, attr, seen) + if bound is not None: + return bound + sub = self._find(f"{source}.{attr}") # ``from pkg import module`` + return sub.ns if sub else None + + def _name(self, module: _Module, name: str) -> object: + bound = self._binding(module, name, set()) + if bound is None and name not in module.ns.defs and name not in module.imports: + return self._sdk(name) if name in ("WidgetOptions", "widget") else None + return bound def resolve(self, expr: ast.AST, module: _Module) -> object: if isinstance(expr, ast.Name): @@ -166,7 +188,7 @@ def resolve(self, expr: ast.AST, module: _Module) -> object: if isinstance(expr, ast.Attribute): base = self.resolve(expr.value, module) if base is _NITROSTACK: - return _WIDGET_OPTIONS if expr.attr == "WidgetOptions" else _NITROSTACK + return self._sdk(expr.attr) if isinstance(base, _Namespace): if expr.attr in base.defs: return base.defs[expr.attr] @@ -236,9 +258,9 @@ def routes_in(self, module: _Module) -> List[str]: found: List[Tuple[int, int, str]] = [] for node in ast.walk(module.tree): for decorator in getattr(node, "decorator_list", []): - func = getattr(decorator, "func", None) - is_widget = (isinstance(func, ast.Name) and func.id == "widget") or ( - isinstance(func, ast.Attribute) and func.attr == "widget" + is_widget = ( + isinstance(decorator, ast.Call) + and self.resolve(decorator.func, module) is _WIDGET ) if isinstance(decorator, ast.Call) and is_widget and decorator.args: route = self._decorator_route(decorator.args[0], module) diff --git a/tests/test_validate_widgets.py b/tests/test_validate_widgets.py index ba5dfae..2a0a251 100644 --- a/tests/test_validate_widgets.py +++ b/tests/test_validate_widgets.py @@ -308,3 +308,101 @@ def test_unimported_widget_options_alias_and_attribute_forms(tmp_path: Path): def test_a_file_that_does_not_parse_still_yields_its_literal_routes(tmp_path: Path): src = "@widget('legacy')\ndef f(:\n pass\nWidgetOptions(route='legacy-options')\n" assert sorted(_routes(tmp_path, {"broken.py": src})) == ["legacy", "legacy-options"] + + +def test_widget_options_reexported_by_a_project_package_is_followed(tmp_path: Path): + files = { + "shared/__init__.py": "from nitrostack import WidgetOptions, widget\n", + "tools.py": ( + "from shared import WidgetOptions, widget\n" + "@widget(WidgetOptions(route='missing-card'))\ndef a(): ...\n" + ), + } + assert sorted(_routes(tmp_path, files)) == ["missing-card"] + + +def test_reexport_through_an_alias_and_two_hops_is_followed(tmp_path: Path): + files = { + "core/options.py": "from nitrostack import WidgetOptions as Options, widget as ui\n", + "core/__init__.py": "from .options import Options, ui\n", + "shared.py": "from core import Options as Opts, ui as sdk_widget\n", + "tools.py": ( + "from shared import Opts, sdk_widget\n" + "@sdk_widget('direct')\ndef a(): ...\n" + "@sdk_widget(Opts(route='via-options'))\ndef b(): ...\n" + ), + } + assert sorted(_routes(tmp_path, files)) == ["direct", "via-options"] + + +def test_reexported_factory_is_still_a_factory(tmp_path: Path): + files = { + "shared/__init__.py": "from .helpers import panel\n", + "shared/helpers.py": FACTORY, + "tools.py": "from nitrostack import widget\nfrom shared import panel\n@widget(panel('reexported'))\ndef a(): ...\n", + } + assert _routes(tmp_path, files) == ["reexported"] + + +def test_import_cycle_between_reexporting_modules_terminates(tmp_path: Path): + files = { + "a.py": "from b import thing\n", + "b.py": "from a import thing\n", + "tools.py": "from a import thing\n@thing('x')\ndef f(): ...\n", + } + assert _routes(tmp_path, files) == [] + + +def test_a_name_reexported_from_a_non_sdk_module_is_not_the_sdk(tmp_path: Path): + files = { + "shared/__init__.py": "from .own import WidgetOptions\n", + "shared/own.py": "class WidgetOptions:\n def __init__(self, route): ...\n", + "tools.py": "from shared import WidgetOptions\nWidgetOptions(route='not-a-widget')\n", + } + assert _routes(tmp_path, files) == [] + + +def test_missing_html_check_runs_for_a_reexported_widget_options(tmp_path: Path): + (tmp_path / "shared").mkdir() + (tmp_path / "shared" / "__init__.py").write_text("from nitrostack import WidgetOptions, widget\n") + (tmp_path / "tools.py").write_text( + "from shared import WidgetOptions, widget\n" + "@widget(WidgetOptions(route='missing-card'))\ndef a(): ...\n" + ) + issues = validate_widgets(str(tmp_path)) + assert [i.severity for i in issues] == ["warning"] + assert "missing-card.html" in issues[0].message + + +@pytest.mark.parametrize( + "decorator, imports", + [ + ("@pytest.mark.widget('smoke')", "import pytest\n"), + ("@marks.widget('smoke')", "from tests import marks\n"), + ("@widget('smoke')", "from other_lib import widget\n"), + ("@widget('smoke')", "def widget(name):\n return lambda f: f\n"), + ("@app.widget('smoke')", "from fastapi import FastAPI\napp = FastAPI()\n"), + ], +) +def test_widget_decorators_that_are_not_the_sdks_are_ignored(tmp_path: Path, decorator, imports): + src = f"{imports}\n{decorator}\ndef test_it(): ...\n" + assert _routes(tmp_path, {"test_tools.py": src}) == [] + assert validate_widgets(str(tmp_path)) == [] + + +def test_pytest_widget_marker_does_not_hide_the_real_widget(tmp_path: Path): + src = ( + "import pytest\nfrom nitrostack import widget\n" + "@pytest.mark.widget('smoke')\ndef test_it(): ...\n" + "@widget('card')\ndef real(): ...\n" + ) + assert _routes(tmp_path, {"tools.py": src}) == ["card"] + + +def test_qualified_sdk_decorators_are_still_collected(tmp_path: Path): + src = ( + "import nitrostack\nimport nitrostack.decorators as deco\n" + "@nitrostack.widget('top')\ndef a(): ...\n" + "@deco.widget('submodule')\ndef b(): ...\n" + ) + assert sorted(_routes(tmp_path, {"tools.py": src})) == ["submodule", "top"] From ee1ea1dc66e54dd9da0f043a0f2cde2f38bc2e5f Mon Sep 17 00:00:00 2001 From: Aadarsh Mahesh K Date: Tue, 10 Nov 2026 12:46:17 +0530 Subject: [PATCH 124/146] fix(auth): retry on busy port and report bound port in discovery server (#117) --- nitrostack/auth/oauth.py | 35 ++++ nitrostack/auth/oauth_discovery.py | 70 +++++--- .../templates/flight-booking/.env.example | 4 + .../templates/flight-booking/OAUTH_SETUP.md | 2 + scripts/probe_discovery_port.py | 5 +- tests/test_oauth_discovery.py | 159 ++++++++++++++++++ 6 files changed, 253 insertions(+), 22 deletions(-) diff --git a/nitrostack/auth/oauth.py b/nitrostack/auth/oauth.py index 0c89073..0865349 100644 --- a/nitrostack/auth/oauth.py +++ b/nitrostack/auth/oauth.py @@ -80,11 +80,36 @@ def __init__( enable_client_registration: Optional[bool] = None, static_client_id: Optional[str] = None, static_client_secret: Union[SecretValue, str, None] = None, + discovery_auto_retry: Optional[bool] = None, + discovery_max_retries: Optional[int] = None, ): self.resource_uri = resource_uri self.authorization_servers = authorization_servers self.scopes_supported = scopes_supported self.discovery_port = discovery_port + if discovery_auto_retry is not None: + self.discovery_auto_retry = discovery_auto_retry + else: + env_retry = os.environ.get("OAUTH_DISCOVERY_AUTO_RETRY") + self.discovery_auto_retry = ( + env_retry.strip().lower() not in ("false", "0", "no", "off") + if env_retry is not None + else True + ) + + if discovery_max_retries is not None: + self.discovery_max_retries = discovery_max_retries + else: + raw_max_retries = os.environ.get("OAUTH_DISCOVERY_MAX_RETRIES") + if raw_max_retries is not None: + try: + self.discovery_max_retries = int(raw_max_retries) + except ValueError: + self.discovery_max_retries = 50 + else: + self.discovery_max_retries = 50 + + self.bound_port: Optional[int] = None # Introspection settings fall back to the environment when not passed # explicitly. Both spellings of the endpoint variable are accepted: the @@ -147,6 +172,10 @@ def start_discovery_server(self) -> None: """Starts a background HTTP discovery server for OAuth Protected Resource metadata.""" start_discovery_server(self) + def get_port(self) -> Optional[int]: + """Returns the actual port bound by the discovery server, or None if not running.""" + return self.bound_port + def raise_if_invalid(self, token_info: Dict[str, Any]) -> Dict[str, Any]: """Raise ``TokenInactiveError`` / ``AudienceMismatchError`` for an introspection result.""" if token_info.get("error") == "audience_mismatch" or ( @@ -160,10 +189,12 @@ def raise_if_invalid(self, token_info: Dict[str, Any]) -> Dict[str, Any]: def stop_discovery_server(self) -> None: if self._server: self._server.shutdown() + self._server.server_close() self._server = None if self._thread: self._thread.join(timeout=1.0) self._thread = None + self.bound_port = None async def introspect_token(self, token: str) -> Dict[str, Any]: """ @@ -248,6 +279,8 @@ def for_root( enable_client_registration: Optional[bool] = None, static_client_id: Optional[str] = None, static_client_secret: Union[SecretValue, str, None] = None, + discovery_auto_retry: Optional[bool] = None, + discovery_max_retries: Optional[int] = None, ): if not resource_uri or not str(resource_uri).strip(): raise ConfigurationError("OAuthModule.for_root requires resource_uri") @@ -270,6 +303,8 @@ def for_root( enable_client_registration=enable_client_registration, static_client_id=static_client_id, static_client_secret=static_client_secret, + discovery_auto_retry=discovery_auto_retry, + discovery_max_retries=discovery_max_retries, ) DIContainer.get_instance().register_value(OAuthService, service) warn_if_oauth_fail_open() diff --git a/nitrostack/auth/oauth_discovery.py b/nitrostack/auth/oauth_discovery.py index 1d56f0b..bbfdb93 100644 --- a/nitrostack/auth/oauth_discovery.py +++ b/nitrostack/auth/oauth_discovery.py @@ -75,10 +75,11 @@ def _trusted_public_origin(self) -> Optional[str]: peer = self._proxy_peer() if not trusted_forwarded_host(headers, peer): return None + port = service_instance.bound_port or service_instance.discovery_port return public_origin( headers, peer, - fallback_host=f"localhost:{service_instance.discovery_port}", + fallback_host=f"localhost:{port}", fallback_proto="http", ) @@ -141,25 +142,52 @@ def do_POST(self): _write_json(self, 200, build_registration_response(service_instance, body)) - def run_server(): - # Try binding to OAUTH_DISCOVERY_PORT - port = int(os.environ.get("OAUTH_DISCOVERY_PORT", service.discovery_port)) + raw_port = os.environ.get("OAUTH_DISCOVERY_PORT") + if raw_port is not None: try: - service._server = HTTPServer(("localhost", port), DiscoveryHandler) - # Notify client via stderr - oauth_metadata = { - "port": port, - "resource_uri": service.resource_uri, - "authorization_servers": service.authorization_servers - } - sys.stderr.write( - f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n" - ) - sys.stderr.flush() - service._server.serve_forever() - except Exception as e: - sys.stderr.write(f"Failed to start OAuth Discovery Server on port {port}: {e}\n") - sys.stderr.flush() - - service._thread = threading.Thread(target=run_server, daemon=True) + start_port = int(raw_port) + except ValueError: + start_port = service.discovery_port + else: + start_port = service.discovery_port + + max_retries = max(0, service.discovery_max_retries) if service.discovery_auto_retry else 0 + last_error: Optional[Exception] = None + bound_server: Optional[HTTPServer] = None + + for attempt in range(max_retries + 1): + candidate_port = start_port + attempt + if candidate_port > 65535: + if last_error is None: + last_error = OverflowError("bind(): port must be 0-65535") + break + try: + server = HTTPServer(("localhost", candidate_port), DiscoveryHandler) + bound_server = server + service.bound_port = server.server_address[1] + break + except (OSError, OverflowError) as e: + last_error = e + + if bound_server is None: + sys.stderr.write(f"Failed to start OAuth Discovery Server on port {start_port}: {last_error}\n") + sys.stderr.flush() + if isinstance(last_error, OSError): + raise last_error + raise OSError(f"Failed to start OAuth Discovery Server on port {start_port}: {last_error}") from last_error + + service._server = bound_server + + # Notify client via stderr + oauth_metadata = { + "port": service.bound_port, + "resource_uri": service.resource_uri, + "authorization_servers": service.authorization_servers, + } + sys.stderr.write( + f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n" + ) + sys.stderr.flush() + + service._thread = threading.Thread(target=service._server.serve_forever, daemon=True) service._thread.start() diff --git a/nitrostack/templates/flight-booking/.env.example b/nitrostack/templates/flight-booking/.env.example index e4a2b46..2ebf690 100644 --- a/nitrostack/templates/flight-booking/.env.example +++ b/nitrostack/templates/flight-booking/.env.example @@ -9,3 +9,7 @@ NITROSTACK_APP_MODE=universal # Unset by default so Studio can call tools without a token (TS default). # Set to true only when testing real OAuth enforcement. # OAUTH_REQUIRED=true +# OAuth Discovery Settings (Optional) +# OAUTH_DISCOVERY_PORT=3005 +# OAUTH_DISCOVERY_AUTO_RETRY=true +# OAUTH_DISCOVERY_MAX_RETRIES=50 diff --git a/nitrostack/templates/flight-booking/OAUTH_SETUP.md b/nitrostack/templates/flight-booking/OAUTH_SETUP.md index 1b6ed26..d66d7c2 100644 --- a/nitrostack/templates/flight-booking/OAUTH_SETUP.md +++ b/nitrostack/templates/flight-booking/OAUTH_SETUP.md @@ -52,6 +52,8 @@ TOKEN_ISSUER=https://your-tenant.us.auth0.com/ # OAUTH_TOKEN_CACHE_SECONDS=300 # Port for the .well-known discovery server (default 3005). # OAUTH_DISCOVERY_PORT=3005 +# OAUTH_DISCOVERY_AUTO_RETRY=true +# OAUTH_DISCOVERY_MAX_RETRIES=50 ``` ## 2. Protected Routes diff --git a/scripts/probe_discovery_port.py b/scripts/probe_discovery_port.py index d538740..45c842f 100644 --- a/scripts/probe_discovery_port.py +++ b/scripts/probe_discovery_port.py @@ -43,8 +43,11 @@ def free_port() -> int: server = getattr(service, "_server", None) print("server object:", server) print("bound to:", getattr(server, "server_address", None)) + bound_port = getattr(service, "bound_port", None) + print("reported bound_port:", bound_port) + target_port = bound_port or port try: - url = f"http://127.0.0.1:{port}/.well-known/oauth-protected-resource" + url = f"http://127.0.0.1:{target_port}/.well-known/oauth-protected-resource" with urllib.request.urlopen(url, timeout=2) as resp: print("GET", url, "->", resp.status) except Exception as exc: diff --git a/tests/test_oauth_discovery.py b/tests/test_oauth_discovery.py index 55b5d88..6fa12d7 100644 --- a/tests/test_oauth_discovery.py +++ b/tests/test_oauth_discovery.py @@ -94,3 +94,162 @@ def test_warn_if_oauth_fail_open_writes_once(monkeypatch, capsys): assert "OAuth is configured" in err assert oauth._oauth_fail_open_warned is True oauth._oauth_fail_open_warned = False + + +def test_discovery_server_busy_port_with_retry(capsys): + port = _free_port() + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + blocker.bind(("127.0.0.1", port)) + blocker.listen(1) + + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + service.start_discovery_server() + assert service.bound_port is not None + assert service.bound_port != port + assert service.get_port() == service.bound_port + assert service._server is not None + + err = capsys.readouterr().err + assert f'"port": {service.bound_port}' in err + + with urllib.request.urlopen( + f"http://127.0.0.1:{service.bound_port}/.well-known/oauth-protected-resource", + timeout=1.0, + ) as resp: + body = json.loads(resp.read().decode("utf-8")) + assert body["resource"] == "http://localhost:3000/mcp" + finally: + service.stop_discovery_server() + blocker.close() + + +def test_discovery_server_retries_exhausted(capsys): + import pytest + + port = _free_port() + blockers = [] + for p in (port, port + 1): + b = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + b.bind(("127.0.0.1", p)) + b.listen(1) + blockers.append(b) + + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + discovery_max_retries=1, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + with pytest.raises(OSError): + service.start_discovery_server() + assert service._server is None + assert service.bound_port is None + assert service.get_port() is None + err = capsys.readouterr().err + assert f"Failed to start OAuth Discovery Server on port {port}" in err + finally: + service.stop_discovery_server() + for b in blockers: + b.close() + + +def test_discovery_server_auto_retry_disabled_surfaces_bind_failure(capsys, monkeypatch): + import pytest + + port = _free_port() + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + blocker.bind(("127.0.0.1", port)) + blocker.listen(1) + + monkeypatch.setenv("OAUTH_DISCOVERY_AUTO_RETRY", "false") + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + with pytest.raises(OSError): + service.start_discovery_server() + assert service._server is None + assert service.bound_port is None + err = capsys.readouterr().err + assert f"Failed to start OAuth Discovery Server on port {port}" in err + finally: + service.stop_discovery_server() + blocker.close() + + +def test_discovery_server_reports_actual_bound_port(capsys): + port = _free_port() + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + service.start_discovery_server() + assert service.bound_port == port + assert service.get_port() == port + err = capsys.readouterr().err + assert f'"port": {port}' in err + finally: + service.stop_discovery_server() + assert service.bound_port is None + assert service.get_port() is None + + +def test_discovery_server_port_overflow_surfaces_oserror(capsys): + import pytest + + port = 65535 + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + blocker.bind(("127.0.0.1", port)) + blocker.listen(1) + except OSError: + pytest.skip("Port 65535 unavailable for test") + + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=port, + discovery_auto_retry=True, + ) + service = DIContainer.get_instance().resolve(OAuthService) + try: + with pytest.raises(OSError): + service.start_discovery_server() + assert service._server is None + assert service.bound_port is None + err = capsys.readouterr().err + assert f"Failed to start OAuth Discovery Server on port {port}" in err + finally: + service.stop_discovery_server() + blocker.close() + + +def test_discovery_server_invalid_max_retries_falls_back_to_default(monkeypatch): + monkeypatch.setenv("OAUTH_DISCOVERY_MAX_RETRIES", "abc") + OAuthModule.for_root( + resource_uri="http://localhost:3000/mcp", + authorization_servers=["http://auth.example/oauth"], + scopes_supported=["read"], + discovery_port=3005, + ) + service = DIContainer.get_instance().resolve(OAuthService) + assert service.discovery_max_retries == 50 From a957f3ce6f605f4fe4da24b00221ae60101e11b5 Mon Sep 17 00:00:00 2001 From: Shreya Vemana Date: Tue, 10 Nov 2026 16:00:20 +0530 Subject: [PATCH 125/146] refactor: split HTTP transport into modules --- nitrostack/transports/http.py | 797 ----------------------- nitrostack/transports/http/__init__.py | 65 ++ nitrostack/transports/http/app.py | 277 ++++++++ nitrostack/transports/http/constants.py | 20 + nitrostack/transports/http/env.py | 16 + nitrostack/transports/http/handlers.py | 251 +++++++ nitrostack/transports/http/middleware.py | 180 +++++ nitrostack/transports/http/tracing.py | 97 +++ 8 files changed, 906 insertions(+), 797 deletions(-) delete mode 100644 nitrostack/transports/http.py create mode 100644 nitrostack/transports/http/__init__.py create mode 100644 nitrostack/transports/http/app.py create mode 100644 nitrostack/transports/http/constants.py create mode 100644 nitrostack/transports/http/env.py create mode 100644 nitrostack/transports/http/handlers.py create mode 100644 nitrostack/transports/http/middleware.py create mode 100644 nitrostack/transports/http/tracing.py diff --git a/nitrostack/transports/http.py b/nitrostack/transports/http.py deleted file mode 100644 index d5a2b60..0000000 --- a/nitrostack/transports/http.py +++ /dev/null @@ -1,797 +0,0 @@ -""" -Streamable HTTP transport for NitroStack (Phase 3). - -The official `mcp` SDK's `StreamableHTTPSessionManager` already provides -per-session isolation (one transport + one `Server.run()` task per session), -SSE streaming, resumability via an event store, idle-session timeouts, and -DNS-rebinding protection via `TransportSecuritySettings`. This module does -NOT reimplement any of that — it wires those existing features through -NitroStack's config/env vars and adds the handful of pieces the manager does -not provide out of the box: - -- CORS headers for browser-based MCP clients -- A concurrent-session cap with a `429` response (the manager has no public - session-count API or creation hook, so this is tracked via a thin ASGI - middleware watching the `mcp-session-id` header) -- A `/mcp/health` endpoint -- A documentation landing page at `GET /` (connection setup + tool catalog) -- Chrome DevTools discovery stubs at `GET /json` and `GET /json/version` so - inspector probes do not 404 -- JSON 404s for OAuth discovery / DCR (`/register`) so MCP Inspector does not - treat the HTML landing page as an OAuth error -- Legacy SSE (`/sse` + `/mcp/messages/`) for older HTTP+SSE-only clients - -See `dev-plan/PHASE-3-http-transport.md` for the full scope. -""" -from __future__ import annotations - -import contextlib -import logging -import os -import sys -import time -from typing import TYPE_CHECKING, Any, Dict, List, Optional - -from starlette.applications import Starlette -from starlette.middleware import Middleware -from starlette.middleware.cors import CORSMiddleware -from starlette.responses import HTMLResponse, JSONResponse, Response -from starlette.routing import Mount, Route -from starlette.types import ASGIApp, Receive, Scope, Send - -from nitrostack.transports.landing_page import render_landing_page -from nitrostack.widgets.preview_page import render_preview_page -from nitrostack.core.di import DIContainer -from nitrostack.transports.cors import configured_cors_origins -from pydantic_core import PydanticUndefined -from mcp.server.sse import SseServerTransport -from mcp.server.streamable_http_manager import StreamableHTTPSessionManager -from mcp.server.transport_security import TransportSecuritySettings - -from nitrostack.protocol.version import ( - HttpEngine, - ProtocolEra, - WireMode, - protocol_version_for_era, - resolve_http_engine, -) -from nitrostack.protocol.constants import LEGACY_SESSION_HEADER -from nitrostack.transports.headers import ( - CORS_ALLOW_HEADER_NAMES, - CORS_EXPOSE_HEADER_NAMES, - SSE_SUBSCRIPTIONS_PATH, - strip_legacy_session_headers_asgi, -) -from nitrostack.transports.subscriptions import subscriptions_listen_endpoint -from nitrostack.transports.proxy import public_url_for_request -from nitrostack.core.log_emitter import install_log_handler - -if TYPE_CHECKING: - from nitrostack.core.app import McpApplication - -logger = logging.getLogger("nitrostack.transports.http") - -DEFAULT_ENDPOINT = "/mcp" - -# Shared 2026 allow-headers. Session id is exposed only on the sessionful engine. -CORS_ALLOW_HEADERS = list(CORS_ALLOW_HEADER_NAMES) - -# The Accept value `StreamableHTTPServerTransport` requires: it needs -# `application/json` on POST and `text/event-stream` on both POST and GET. -MCP_ACCEPT = "application/json, text/event-stream" - -_PROCESS_START = time.monotonic() - - -def _server_meta(mcp_app: "McpApplication") -> Dict[str, str]: - cfg = getattr(mcp_app, "server_config", None) - return { - "name": getattr(cfg, "name", None) or "NitroStack MCP Server", - "version": getattr(cfg, "version", None) or "1.0.0", - } - - -def _landing_tools(mcp_app: "McpApplication") -> List[Dict[str, Any]]: - tools: List[Dict[str, Any]] = [] - for entry in getattr(mcp_app, "_tools", {}).values(): - try: - schema = mcp_app._tool_input_schema(entry.input_model) - except Exception: - logger.exception("Landing page schema failed for %s", entry.config.name) - schema = None - tools.append( - { - "name": entry.config.name, - "description": entry.config.description or "", - "inputSchema": schema, - } - ) - return tools - - -def _env_list(name: str) -> List[str]: - raw = os.environ.get(name) - if not raw: - return [] - return [item.strip() for item in raw.split(",") if item.strip()] - - -def _env_flag(name: str) -> bool: - return (os.environ.get(name) or "").strip().lower() in {"1", "true", "yes", "on"} - - -def _enable_trace_logging() -> None: - """ - Give `logger` its own stderr handler so tracing works regardless of how the - host application configured logging. - - `FileLogger` only attaches handlers to the `nitrostack` logger when it is - first instantiated, which for an HTTP server may not happen until a tool - runs. Until then this module's records fall through to `logging`'s - last-resort handler and INFO is discarded. Propagation is disabled so the - traces are not emitted twice once `FileLogger` does attach its handler. - stderr keeps them off stdout, which dual mode uses for JSON-RPC. - """ - install_log_handler("nitrostack.transports.http") - if any(getattr(handler, "_nitrostack_trace", False) for handler in logger.handlers): - return - handler = logging.StreamHandler(sys.stderr) - handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] (%(name)s): %(message)s")) - handler._nitrostack_trace = True # type: ignore[attr-defined] - logger.addHandler(handler) - logger.setLevel(logging.INFO) - logger.propagate = False - - -class RequestTraceMiddleware: - """ - Log the raw request line, headers and body of every HTTP request, plus the - response status and headers. - - Enabled only when `NITROSTACK_HTTP_DEBUG=1`. uvicorn's access log has no - timestamps and no headers, which makes it impossible to tell *why* the - `mcp` SDK rejected a client request (a `406` and a `400` from the SDK are - both header-driven) or even to correlate a failed client connection with a - log line. This middleware is the outermost layer so it sees requests - exactly as the client sent them, before CORS or any path rewriting. - """ - - MAX_BODY_CHARS = 2000 - REDACTED_HEADERS = {"authorization", "proxy-authorization", "cookie", "set-cookie"} - - def __init__(self, app: ASGIApp) -> None: - self.app = app - - @classmethod - def _decode_headers(cls, raw: Any) -> Dict[str, str]: - headers = {} - for key, value in raw or []: - name = key.decode("latin-1") - headers[name] = "" if name.lower() in cls.REDACTED_HEADERS else value.decode("latin-1") - return headers - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] != "http": - await self.app(scope, receive, send) - return - - method = scope.get("method") - path = scope.get("path") - query = (scope.get("query_string") or b"").decode("latin-1") - target = f"{path}?{query}" if query else path - logger.info("trace >> %s %s headers=%s", method, target, self._decode_headers(scope.get("headers"))) - - async def traced_receive() -> Any: - message = await receive() - if message.get("type") == "http.request": - body = message.get("body") or b"" - if body: - text = body.decode("utf-8", errors="replace") - if len(text) > self.MAX_BODY_CHARS: - text = text[: self.MAX_BODY_CHARS] + "..." - logger.info("trace >> %s %s body=%s", method, target, text) - return message - - async def traced_send(message: Any) -> None: - if message.get("type") == "http.response.start": - logger.info( - "trace << %s %s status=%s headers=%s", - method, - target, - message.get("status"), - self._decode_headers(message.get("headers")), - ) - await send(message) - - await self.app(scope, traced_receive, traced_send) - - -def _preview_default_arguments(entry: Any) -> Dict[str, Any]: - """Prefill live preview with tool examples (shopId, openNow, …).""" - examples = getattr(getattr(entry, "config", None), "examples", None) - raw = getattr(examples, "input", None) if examples is not None else None - if isinstance(raw, dict): - return dict(raw) - model = getattr(entry, "input_model", None) - if model is None: - return {} - data: Dict[str, Any] = {} - for fname, field in getattr(model, "model_fields", {}).items(): - default = getattr(field, "default", PydanticUndefined) - if default is not PydanticUndefined and default is not None: - data[fname] = default - continue - if fname in ("shopId", "shop_id"): - data[fname] = "tonys-pizza" - elif fname == "product_id": - data[fname] = "sku-1" - elif fname == "filter": - data[fname] = "all" - elif fname == "openNow": - data[fname] = True - elif fname == "origin": - data[fname] = "JFK" - elif fname == "destination": - data[fname] = "LAX" - elif fname in ("departureDate", "departure_date"): - data[fname] = "2026-09-15" - elif fname in ("offerId", "offer_id"): - data[fname] = "off_mock123456" - elif fname in ("orderId", "order_id"): - data[fname] = "ord_mock123456" - elif fname == "query": - data[fname] = "London" - return data - - -class ExactEndpointSlashMiddleware: - """ - Internally rewrite `/mcp` → `/mcp/` so Starlette does not 307. - - `Mount("/mcp")` only matches `/mcp/...`. With `redirect_slashes=True` - (Starlette's default) a request to `/mcp` becomes `307 Location: /mcp/`. - MCP Inspector's Streamable HTTP client POSTs and GETs `/mcp` with no - trailing slash; following that 307 on the GET SSE stream drops the - connection, so List Tools shows a blank page and disconnects. - """ - - def __init__(self, app: ASGIApp, endpoint: str) -> None: - self.app = app - self._exact = endpoint.rstrip("/") or "/" - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] == "http" and scope.get("path") == self._exact: - scope = dict(scope) - scope["path"] = self._exact + "/" - raw = scope.get("raw_path") - if isinstance(raw, (bytes, bytearray)): - scope["raw_path"] = raw.rstrip(b"/") + b"/" - await self.app(scope, receive, send) - - -class HeaderCompatMiddleware: - """ - Normalize ``Accept`` on the Streamable HTTP mount so wildcard or absent - Accept does not 406. Session ids are stripped only when - ``drop_session_headers`` is set. - - ``MCP-Protocol-Version`` is never deleted. Duplicate casings are collapsed - to lowercase names and client values are preserved so the official - transport can reject duplicate or inconsistent version claims. - - Stack order on the HTTP app: CORS → this middleware (preserve) → handler. - This middleware only normalizes transport headers; JSON-RPC dispatch remains - owned by the official MCP Streamable HTTP manager. - """ - - def __init__(self, app: ASGIApp, *, drop_session_headers: bool = False, - require_protocol_version: bool = False) -> None: - self.app = app - self.drop_session_headers = drop_session_headers - self.require_protocol_version = require_protocol_version - - @staticmethod - def _normalize_accept(value: Optional[str]) -> Optional[str]: - if value is None or not value.strip(): - return MCP_ACCEPT - media_types = [media_type.strip() for media_type in value.split(",")] - has_json = any(media_type.startswith("application/json") for media_type in media_types) - has_sse = any(media_type.startswith("text/event-stream") for media_type in media_types) - if has_json and has_sse: - return None - # Only a wildcard is rewritten. A client that names concrete media types - # but omits one the transport needs is genuinely non-compliant (the spec - # requires both on POST), so it keeps getting the transport's 406. - if any(media_type.startswith("*/*") for media_type in media_types): - return MCP_ACCEPT - return None - - @staticmethod - def _canonicalize_protocol_version(headers: List[Any]) -> List[Any]: - """Normalize casing without hiding duplicates from MCP's validator.""" - version_values: List[bytes] = [] - kept: List[Any] = [] - for key, value in headers: - if key.lower() == b"mcp-protocol-version": - version_values.append(value) - else: - kept.append((key, value)) - if not version_values: - return headers - kept.extend((b"mcp-protocol-version", value) for value in version_values) - return kept - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] != "http": - await self.app(scope, receive, send) - return - - headers: List[Any] = list(scope.get("headers") or []) - if self.require_protocol_version and scope.get("method") == "POST" and not any( - key.lower() == b"mcp-protocol-version" and value.strip() for key, value in headers - ): - # The official manager selects its strict path using this header. - # Reject before that selection without reading/replaying the body - # or interpreting a method. All JSON-RPC dispatch stays in MCP. - response = JSONResponse( - {"jsonrpc": "2.0", "id": None, "error": { - "code": -32020, "message": "MCP-Protocol-Version header is required", - }}, status_code=400, - ) - await response(scope, receive, send) - return - if self.drop_session_headers: - headers = strip_legacy_session_headers_asgi(headers) - headers = self._canonicalize_protocol_version(headers) - - raw_accept = next((value for key, value in headers if key.lower() == b"accept"), None) - accept = self._normalize_accept(raw_accept.decode("latin-1") if raw_accept is not None else None) - if accept is not None: - headers = [(key, value) for key, value in headers if key.lower() != b"accept"] - headers.append((b"accept", accept.encode("latin-1"))) - logger.debug("Rewrote Accept %r -> %r for %s", raw_accept, accept, scope.get("path")) - - scope = dict(scope) - scope["headers"] = headers - await self.app(scope, receive, send) - - -class SessionCapMiddleware: - """ - Enforce a `max_sessions` concurrent-session cap on the Streamable HTTP - mount, returning a `429` JSON-RPC error once at capacity. - - `StreamableHTTPSessionManager` doesn't expose a public session count or a - session-created/closed hook, so this middleware tracks session ids itself - by observing the `mcp-session-id` request header (existing sessions) and - the `Mcp-Session-Id` response header (newly created sessions), and prunes - entries locally after `session_idle_timeout` so the count self-heals even - if a client disconnects without sending `DELETE`. - """ - - def __init__( - self, - app: ASGIApp, - max_sessions: Optional[int], - session_idle_timeout: Optional[float] = None, - ) -> None: - self.app = app - self.max_sessions = max_sessions - self.session_idle_timeout = session_idle_timeout - self._sessions: Dict[str, float] = {} - - def _prune_stale(self) -> None: - if not self.session_idle_timeout: - return - cutoff = time.monotonic() - self.session_idle_timeout - for sid in [s for s, seen in self._sessions.items() if seen < cutoff]: - self._sessions.pop(sid, None) - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] != "http" or not self.max_sessions: - await self.app(scope, receive, send) - return - - self._prune_stale() - - headers = dict(scope.get("headers") or []) - raw_session_id = headers.get(b"mcp-session-id") - session_id = raw_session_id.decode() if raw_session_id else None - is_known = session_id is not None and session_id in self._sessions - - if not is_known and len(self._sessions) >= self.max_sessions: - response = JSONResponse( - { - "jsonrpc": "2.0", - "error": { - "code": -32000, - "message": "Too many sessions: server at capacity, retry later", - }, - "id": None, - }, - status_code=429, - ) - await response(scope, receive, send) - return - - if is_known: - self._sessions[session_id] = time.monotonic() - - new_session_id: Dict[str, Optional[str]] = {"value": None} - - async def send_wrapper(message: Any) -> None: - if message["type"] == "http.response.start": - for key, value in message.get("headers", []): - if key.lower() == b"mcp-session-id": - new_session_id["value"] = value.decode() - await send(message) - - await self.app(scope, receive, send_wrapper) - - if new_session_id["value"]: - self._sessions[new_session_id["value"]] = time.monotonic() - - if scope.get("method") == "DELETE" and session_id: - self._sessions.pop(session_id, None) - - @property - def active_session_count(self) -> int: - self._prune_stale() - return len(self._sessions) - - -def _oauth_is_configured() -> bool: - """True when ``OAuthModule.for_root`` registered an ``OAuthService`` instance.""" - try: - from nitrostack.auth.oauth import OAuthService - - return DIContainer.get_instance().has_value(OAuthService) - except Exception: - return False - - -def build_http_app( - mcp_app: "McpApplication", - *, - endpoint: str = DEFAULT_ENDPOINT, - max_sessions: Optional[int] = None, - session_idle_timeout: Optional[float] = None, - enable_cors: bool = True, - stateless: bool = False, - json_response: bool = False, - protocol_era: ProtocolEra = "auto", - wire_mode: WireMode = "stateless", - http_engine: Optional[HttpEngine] = None, -) -> Starlette: - """ - Build the Starlette app exposing NitroStack's owned low-level server over - Streamable HTTP (`/mcp`), legacy SSE (`/sse` + `/mcp/messages/`), and a - health check (`/mcp/health`). - - Args: - mcp_app: The bootstrapped `McpApplication` whose `mcp_server` (and - registered tools/resources/prompts) this app serves. - endpoint: Streamable HTTP mount path (default `/mcp`). - max_sessions: Optional concurrent-session cap; `None`/`0` disables the cap. - session_idle_timeout: Optional idle timeout in seconds for stateful - sessions (ignored when `stateless=True`). - enable_cors: Whether to add permissive CORS headers (default `True`). - When `False`, DNS-rebinding - protection (Origin/Host validation) is enabled instead, configured - via `MCP_ALLOWED_HOSTS`/`MCP_ALLOWED_ORIGINS` env vars. - stateless: When `True`, every request gets a fresh transport with no - session id and no session tracking (see `StreamableHTTPSessionManager`). - This is the primitive the `2026-07-28` stateless MCP spec needs; - exposed here as a config knob so adopting that spec later doesn't - require touching this wiring again. - json_response: When `True`, a POST carrying a JSON-RPC request is - answered with a plain `application/json` body instead of a - `text/event-stream` SSE frame. The spec allows either, but a client - that doesn't implement SSE parsing for POST responses sees the SSE - form as a stream that ended without a result. Server-initiated - streaming (progress, notifications) is unavailable in this mode. - protocol_era: ``legacy`` / ``modern`` / ``auto``. Distinct from ``stateless``. - wire_mode: Dual-spec policy for 2025 traffic (``sessionful``, ``stateless`` - fallback, or ``reject``). ``auto`` uses ``stateless``; ``modern`` uses - ``reject``. - http_engine: Era factory result. ``sessionless`` for modern/auto, - ``sessionful`` only for legacy. ``auto`` / ``modern`` never start - a sessionful manager, even if ``stateless=False``. - """ - http_engine = resolve_http_engine( - protocol_era, http_engine=http_engine, stateless=stateless - ) - stateless = http_engine == "sessionless" - - server = mcp_app.mcp_server - if server is not None: - server.http_engine = http_engine - server.sessionful = http_engine == "sessionful" - server.protocol_era = protocol_era - - security_settings = None - if not enable_cors: - allowed_hosts = _env_list("MCP_ALLOWED_HOSTS") or ["localhost:*", "127.0.0.1:*"] - allowed_origins = _env_list("MCP_ALLOWED_ORIGINS") - security_settings = TransportSecuritySettings( - enable_dns_rebinding_protection=True, - allowed_hosts=allowed_hosts, - allowed_origins=allowed_origins, - ) - else: - security_settings = TransportSecuritySettings(enable_dns_rebinding_protection=False) - - # Official mcp 2.x owns /mcp (streamable HTTP, both protocol eras). - # One manager only; auto/modern are sessionless and legacy is sessionful. - session_manager = StreamableHTTPSessionManager( - app=mcp_app.mcp_server, - stateless=stateless, - json_response=json_response, - session_idle_timeout=None if stateless else session_idle_timeout, - security_settings=security_settings, - ) - # Trailing slash is required: Starlette's Mount("/mcp/messages") only matches - # "/mcp/messages/" (or deeper), NOT bare "/mcp/messages". Without the slash the - # endpoint event points at a path that falls through to Mount("/mcp") (Streamable - # HTTP), which then 406s SSE clients that don't send Streamable Accept headers. - # Matches the mcp SDK's own SseServerTransport example ("/messages/"). - sse_messages_path = f"{endpoint.rstrip('/')}/messages/" - sse_transport = SseServerTransport(sse_messages_path) - - async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) -> None: - await session_manager.handle_request(scope, receive, send) - - # Wraps only the Streamable HTTP mount, so `/mcp/health` and the legacy SSE - # routes keep their own (correct) content negotiation. - mcp_asgi_app: ASGIApp = HeaderCompatMiddleware( - handle_streamable_http, drop_session_headers=stateless, - require_protocol_version=protocol_era == "modern", - ) - session_cap: Optional[SessionCapMiddleware] = None - if max_sessions and not stateless: - session_cap = SessionCapMiddleware( - mcp_asgi_app, max_sessions=max_sessions, session_idle_timeout=session_idle_timeout - ) - mcp_asgi_app = session_cap - - async def handle_sse(request): - async with sse_transport.connect_sse(request.scope, request.receive, request._send) as streams: - await mcp_app.mcp_server.run(streams[0], streams[1], mcp_app.mcp_server.create_initialization_options()) - return Response() - - def _request_public_mcp_url(request) -> str: - port = os.environ.get("PORT") or os.environ.get("MCP_SERVER_PORT") or "3000" - return public_url_for_request( - request, - path=endpoint.rstrip("/") or "/mcp", - fallback_host=f"localhost:{port}", - ) - - async def health_check(request): - return JSONResponse( - { - "status": "ok", - "transport": "streamable-http", - "protocolVersion": protocol_version_for_era(protocol_era), - "protocolEra": protocol_era, - "statelessCapable": http_engine == "sessionless", - "stateless": stateless, - "jsonResponse": json_response, - "sessions": session_cap.active_session_count if session_cap else None, - "uptimeSeconds": round(time.monotonic() - _PROCESS_START, 2), - "publicUrl": _request_public_mcp_url(request), - } - ) - - async def root_page(request): - meta = _server_meta(mcp_app) - return HTMLResponse( - render_landing_page( - name=meta["name"], - version=meta["version"], - description=getattr(getattr(mcp_app, "server_config", None), "description", None), - mcp_endpoint=_request_public_mcp_url(request), - tools=_landing_tools(mcp_app), - ) - ) - - async def oauth_not_supported(request): - """Inspector DCR posts `/register` when Authentication is on. - - Return JSON (not the HTML 404 page) so the client shows a clear - OAuth-off message instead of `Unexpected token '<'`. - """ - connect_url = _request_public_mcp_url(request) - return JSONResponse( - { - "error": "invalid_request", - "error_description": ( - "This MCP server does not use OAuth. In MCP Inspector turn " - "Authentication off, then connect with Streamable HTTP to " - f"{connect_url}." - ), - }, - status_code=404, - ) - - async def widgets_preview(request): - catalog = [] - for name, entry in getattr(mcp_app, "_tools", {}).items(): - component = getattr(entry, "component", None) - if component is None: - continue - catalog.append( - { - "name": name, - "resourceUri": component.resource_uri, - "arguments": _preview_default_arguments(entry), - } - ) - return HTMLResponse(render_preview_page(catalog)) - - async def widgets_preview_call(request): - try: - body = await request.json() - except Exception: - return JSONResponse({"error": "Invalid JSON body"}, status_code=400) - if not isinstance(body, dict): - return JSONResponse({"error": "JSON body must be an object"}, status_code=400) - name = body.get("tool") or "" - arguments = body.get("arguments") or {} - if not isinstance(arguments, dict): - return JSONResponse({"error": "arguments must be an object"}, status_code=400) - entry = getattr(mcp_app, "_tools", {}).get(name) - if entry is None or getattr(entry, "component", None) is None: - return JSONResponse({"error": f"No widget tool named {name!r}"}, status_code=404) - try: - result = await mcp_app._call_tool(name, arguments) - except Exception as exc: - logger.exception("Widget preview tool call failed for %s", name) - return JSONResponse({"error": str(exc)}, status_code=400) - structured = getattr(result, "structured_content", None) - if structured is None: - structured = getattr(result, "structuredContent", None) - try: - html = entry.component.html_with_data(structured) - except Exception as exc: - logger.exception("Widget preview render failed for %s", name) - return JSONResponse( - { - "error": f"Widget render failed: {exc}", - "structuredContent": structured, - "html": None, - "resourceUri": entry.component.resource_uri, - "isError": True, - }, - status_code=400, - ) - return JSONResponse( - { - "structuredContent": structured, - "html": html, - "resourceUri": entry.component.resource_uri, - "isError": bool(getattr(result, "is_error", None) if getattr(result, "is_error", None) is not None else getattr(result, "isError", False)), - } - ) - - async def json_version(request): - """Chrome/Cursor DevTools probe `/json/version` when a tab opens localhost.""" - meta = _server_meta(mcp_app) - health_path = f"{endpoint.rstrip('/')}/health" - return JSONResponse( - { - "Browser": meta["name"], - "Protocol-Version": protocol_version_for_era(protocol_era), - "User-Agent": f"NitroStack/{meta['version']}", - "webSocketDebuggerUrl": "", - "transport": "mcp", - "publicUrl": _request_public_mcp_url(request), - "endpoints": { - "mcp": endpoint, - "sse": "/sse", - "health": health_path, - }, - } - ) - - async def json_list(request): - """Chrome DevTools `/json` and `/json/list` expect a page list; empty = not CDP.""" - return JSONResponse([]) - - async def favicon(request): - return Response(status_code=204) - - @contextlib.asynccontextmanager - async def lifespan(app): - async with session_manager.run(): - logger.info( - "StreamableHTTP session manager started (stateless=%s, max_sessions=%s, " - "session_idle_timeout=%s)", - stateless, - max_sessions, - session_idle_timeout, - ) - yield - - oauth_stub_routes: List[Route] = [] - if not _oauth_is_configured(): - # Inspector DCR / discovery stubs. Omit when OAuthModule is registered so - # a real protected-resource document is not replaced with "no OAuth". - oauth_stub_routes = [ - Route("/.well-known/oauth-authorization-server", endpoint=oauth_not_supported, methods=["GET", "POST"]), - Route("/.well-known/oauth-protected-resource", endpoint=oauth_not_supported, methods=["GET", "POST"]), - Route("/register", endpoint=oauth_not_supported, methods=["GET", "POST"]), - Route("/oauth/v2/register", endpoint=oauth_not_supported, methods=["GET", "POST"]), - ] - - routes = [ - # More specific paths MUST come before the catch-all `Mount(endpoint, ...)` - # below — Starlette matches routes in order, and a `Mount` matches any - # path under its prefix, so `/mcp/health` would otherwise be swallowed - # by the `/mcp` mount before ever reaching the health route. - Route("/", endpoint=root_page, methods=["GET"]), - Route("/widgets/preview", endpoint=widgets_preview, methods=["GET"]), - Route("/widgets/preview/call", endpoint=widgets_preview_call, methods=["POST"]), - *oauth_stub_routes, - Route("/json/version", endpoint=json_version, methods=["GET"]), - Route("/json/list", endpoint=json_list, methods=["GET"]), - Route("/json", endpoint=json_list, methods=["GET"]), - Route("/favicon.ico", endpoint=favicon, methods=["GET"]), - Route(f"{endpoint}/health", endpoint=health_check, methods=["GET"]), - Mount(sse_messages_path, app=sse_transport.handle_post_message), - # `handle_streamable_http`/`sse_transport.handle_post_message` are raw - # ASGI apps (scope, receive, send), so they must be `Mount`ed rather - # than used as `Route` endpoints (which expect `Request -> Response`). - Mount(endpoint, app=mcp_asgi_app), - Route("/sse", endpoint=handle_sse, methods=["GET"]), - ] - if protocol_era != "legacy": - routes.append( - Route( - SSE_SUBSCRIPTIONS_PATH, - endpoint=subscriptions_listen_endpoint(mcp_app), - methods=["GET", "POST"], - ) - ) - - # Rewrite `/mcp` → `/mcp/` *before* routing so Inspector never sees a 307. - # CORS stays outermost so preflight still works on the original path. - middleware = [ - Middleware(ExactEndpointSlashMiddleware, endpoint=endpoint), - ] - if enable_cors: - expose_headers = list(CORS_EXPOSE_HEADER_NAMES) - if http_engine == "sessionful": - expose_headers.append(LEGACY_SESSION_HEADER) - # Single CORS layer for `/mcp`: the sidecar that used to add a second - # one has been removed (#22), so `MCP_CORS_ALLOWED_ORIGINS` is honored - # here and nowhere else. - allow_origins = list(configured_cors_origins()) or ["*"] - middleware.insert( - 0, - Middleware( - CORSMiddleware, - allow_origins=allow_origins, - allow_methods=["GET", "POST", "DELETE", "OPTIONS"], - # SEP-2243 permits application-defined Mcp-Param-* names. - # Starlette mirrors requested names when '*' is enabled. - allow_headers=[*CORS_ALLOW_HEADERS, "*"], - expose_headers=expose_headers, - ), - ) - - if _env_flag("NITROSTACK_HTTP_DEBUG"): - _enable_trace_logging() - middleware.insert(0, Middleware(RequestTraceMiddleware)) - - app = Starlette(routes=routes, middleware=middleware, lifespan=lifespan) - app.state.protocol_era = protocol_era - app.state.wire_mode = wire_mode - app.state.stateless = stateless - app.state.http_engine = http_engine - app.state.sessionful = http_engine == "sessionful" - app.state.session_manager = session_manager - app.state.streamable_http_manager_count = 1 - app.state.subscription_bus = getattr(mcp_app.mcp_server, "subscription_bus", None) - app.state.protocol_version = protocol_version_for_era(protocol_era) - return app diff --git a/nitrostack/transports/http/__init__.py b/nitrostack/transports/http/__init__.py new file mode 100644 index 0000000..99d39cc --- /dev/null +++ b/nitrostack/transports/http/__init__.py @@ -0,0 +1,65 @@ +""" +Streamable HTTP transport for NitroStack (Phase 3). + +The official `mcp` SDK's `StreamableHTTPSessionManager` already provides +per-session isolation (one transport + one `Server.run()` task per session), +SSE streaming, resumability via an event store, idle-session timeouts, and +DNS-rebinding protection via `TransportSecuritySettings`. This package does +NOT reimplement any of that — it wires those existing features through +NitroStack's config/env vars and adds the handful of pieces the manager does +not provide out of the box: + +- CORS headers for browser-based MCP clients +- A concurrent-session cap with a `429` response (the manager has no public + session-count API or creation hook, so this is tracked via a thin ASGI + middleware watching the `mcp-session-id` header) +- A `/mcp/health` endpoint +- A documentation landing page at `GET /` (connection setup + tool catalog) +- Chrome DevTools discovery stubs at `GET /json` and `GET /json/version` so + inspector probes do not 404 +- JSON 404s for OAuth discovery / DCR (`/register`) so MCP Inspector does not + treat the HTML landing page as an OAuth error +- Legacy SSE (`/sse` + `/mcp/messages/`) for older HTTP+SSE-only clients + +Module layout (dependencies point one way, top to bottom): + constants, env -> middleware, tracing, handlers -> app -> __init__ + +This package replaces the former single module `nitrostack/transports/http.py`. +Names are re-exported here so existing imports keep working. + +See `dev-plan/PHASE-3-http-transport.md` for the full scope. +""" +from nitrostack.transports.http.app import _oauth_is_configured, build_http_app +from nitrostack.transports.http.constants import ( + CORS_ALLOW_HEADERS, + DEFAULT_ENDPOINT, + MCP_ACCEPT, + _PROCESS_START, + logger, +) +from nitrostack.transports.http.env import _env_flag, _env_list +from nitrostack.transports.http.handlers import ( + _landing_tools, + _preview_default_arguments, + _server_meta, +) +from nitrostack.transports.http.middleware import ( + ExactEndpointSlashMiddleware, + HeaderCompatMiddleware, + SessionCapMiddleware, +) +from nitrostack.transports.http.tracing import ( + RequestTraceMiddleware, + _enable_trace_logging, +) + +__all__ = [ + "build_http_app", + "DEFAULT_ENDPOINT", + "CORS_ALLOW_HEADERS", + "MCP_ACCEPT", + "ExactEndpointSlashMiddleware", + "HeaderCompatMiddleware", + "SessionCapMiddleware", + "RequestTraceMiddleware", +] \ No newline at end of file diff --git a/nitrostack/transports/http/app.py b/nitrostack/transports/http/app.py new file mode 100644 index 0000000..57e10c8 --- /dev/null +++ b/nitrostack/transports/http/app.py @@ -0,0 +1,277 @@ +"""HTTP app assembly: `build_http_app`.""" +from __future__ import annotations + +import contextlib +from typing import TYPE_CHECKING, List, Optional + +from mcp.server.sse import SseServerTransport +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from mcp.server.transport_security import TransportSecuritySettings +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.middleware.cors import CORSMiddleware +from starlette.responses import Response +from starlette.routing import Mount, Route +from starlette.types import ASGIApp, Receive, Scope, Send + +from nitrostack.core.di import DIContainer +from nitrostack.protocol.constants import LEGACY_SESSION_HEADER +from nitrostack.protocol.version import ( + HttpEngine, + ProtocolEra, + WireMode, + protocol_version_for_era, + resolve_http_engine, +) +from nitrostack.transports.cors import configured_cors_origins +from nitrostack.transports.headers import ( + CORS_EXPOSE_HEADER_NAMES, + SSE_SUBSCRIPTIONS_PATH, +) +from nitrostack.transports.http.constants import ( + CORS_ALLOW_HEADERS, + DEFAULT_ENDPOINT, + logger, +) +from nitrostack.transports.http.env import _env_flag, _env_list +from nitrostack.transports.http.handlers import make_handlers +from nitrostack.transports.http.middleware import ( + ExactEndpointSlashMiddleware, + HeaderCompatMiddleware, + SessionCapMiddleware, +) +from nitrostack.transports.http.tracing import ( + RequestTraceMiddleware, + _enable_trace_logging, +) +from nitrostack.transports.subscriptions import subscriptions_listen_endpoint + +if TYPE_CHECKING: + from nitrostack.core.app import McpApplication + + +def _oauth_is_configured() -> bool: + """True when ``OAuthModule.for_root`` registered an ``OAuthService`` instance.""" + try: + from nitrostack.auth.oauth import OAuthService + + return DIContainer.get_instance().has_value(OAuthService) + except Exception: + return False + + +def build_http_app( + mcp_app: "McpApplication", + *, + endpoint: str = DEFAULT_ENDPOINT, + max_sessions: Optional[int] = None, + session_idle_timeout: Optional[float] = None, + enable_cors: bool = True, + stateless: bool = False, + json_response: bool = False, + protocol_era: ProtocolEra = "auto", + wire_mode: WireMode = "stateless", + http_engine: Optional[HttpEngine] = None, +) -> Starlette: + """ + Build the Starlette app exposing NitroStack's owned low-level server over + Streamable HTTP (`/mcp`), legacy SSE (`/sse` + `/mcp/messages/`), and a + health check (`/mcp/health`). + + Args: + mcp_app: The bootstrapped `McpApplication` whose `mcp_server` (and + registered tools/resources/prompts) this app serves. + endpoint: Streamable HTTP mount path (default `/mcp`). + max_sessions: Optional concurrent-session cap; `None`/`0` disables the cap. + session_idle_timeout: Optional idle timeout in seconds for stateful + sessions (ignored when `stateless=True`). + enable_cors: Whether to add permissive CORS headers (default `True`). + When `False`, DNS-rebinding + protection (Origin/Host validation) is enabled instead, configured + via `MCP_ALLOWED_HOSTS`/`MCP_ALLOWED_ORIGINS` env vars. + stateless: When `True`, every request gets a fresh transport with no + session id and no session tracking (see `StreamableHTTPSessionManager`). + This is the primitive the `2026-07-28` stateless MCP spec needs; + exposed here as a config knob so adopting that spec later doesn't + require touching this wiring again. + json_response: When `True`, a POST carrying a JSON-RPC request is + answered with a plain `application/json` body instead of a + `text/event-stream` SSE frame. The spec allows either, but a client + that doesn't implement SSE parsing for POST responses sees the SSE + form as a stream that ended without a result. Server-initiated + streaming (progress, notifications) is unavailable in this mode. + protocol_era: ``legacy`` / ``modern`` / ``auto``. Distinct from ``stateless``. + wire_mode: Dual-spec policy for 2025 traffic (``sessionful``, ``stateless`` + fallback, or ``reject``). ``auto`` uses ``stateless``; ``modern`` uses + ``reject``. + http_engine: Era factory result. ``sessionless`` for modern/auto, + ``sessionful`` only for legacy. ``auto`` / ``modern`` never start + a sessionful manager, even if ``stateless=False``. + """ + http_engine = resolve_http_engine( + protocol_era, http_engine=http_engine, stateless=stateless + ) + stateless = http_engine == "sessionless" + + server = mcp_app.mcp_server + if server is not None: + server.http_engine = http_engine + server.sessionful = http_engine == "sessionful" + server.protocol_era = protocol_era + + security_settings = None + if not enable_cors: + allowed_hosts = _env_list("MCP_ALLOWED_HOSTS") or ["localhost:*", "127.0.0.1:*"] + allowed_origins = _env_list("MCP_ALLOWED_ORIGINS") + security_settings = TransportSecuritySettings( + enable_dns_rebinding_protection=True, + allowed_hosts=allowed_hosts, + allowed_origins=allowed_origins, + ) + else: + security_settings = TransportSecuritySettings(enable_dns_rebinding_protection=False) + + # Official mcp 2.x owns /mcp (streamable HTTP, both protocol eras). + # One manager only; auto/modern are sessionless and legacy is sessionful. + session_manager = StreamableHTTPSessionManager( + app=mcp_app.mcp_server, + stateless=stateless, + json_response=json_response, + session_idle_timeout=None if stateless else session_idle_timeout, + security_settings=security_settings, + ) + # Trailing slash is required: Starlette's Mount("/mcp/messages") only matches + # "/mcp/messages/" (or deeper), NOT bare "/mcp/messages". Without the slash the + # endpoint event points at a path that falls through to Mount("/mcp") (Streamable + # HTTP), which then 406s SSE clients that don't send Streamable Accept headers. + # Matches the mcp SDK's own SseServerTransport example ("/messages/"). + sse_messages_path = f"{endpoint.rstrip('/')}/messages/" + sse_transport = SseServerTransport(sse_messages_path) + + async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) -> None: + await session_manager.handle_request(scope, receive, send) + + # Wraps only the Streamable HTTP mount, so `/mcp/health` and the legacy SSE + # routes keep their own (correct) content negotiation. +# Line 156 + mcp_asgi_app: ASGIApp = HeaderCompatMiddleware( + handle_streamable_http, + drop_session_headers=stateless, + require_protocol_version=protocol_era == "modern", +) + session_cap: Optional[SessionCapMiddleware] = None + if max_sessions and not stateless: + session_cap = SessionCapMiddleware( + mcp_asgi_app, max_sessions=max_sessions, session_idle_timeout=session_idle_timeout + ) + mcp_asgi_app = session_cap + + async def handle_sse(request): + async with sse_transport.connect_sse(request.scope, request.receive, request._send) as streams: + await mcp_app.mcp_server.run(streams[0], streams[1], mcp_app.mcp_server.create_initialization_options()) + return Response() + + h = make_handlers( + mcp_app, + endpoint=endpoint, + protocol_era=protocol_era, + http_engine=http_engine, + stateless=stateless, + json_response=json_response, + session_cap=session_cap, + ) + + @contextlib.asynccontextmanager + async def lifespan(app): + async with session_manager.run(): + logger.info( + "StreamableHTTP session manager started (stateless=%s, max_sessions=%s, " + "session_idle_timeout=%s)", + stateless, + max_sessions, + session_idle_timeout, + ) + yield + + oauth_stub_routes: List[Route] = [] + if not _oauth_is_configured(): + # Inspector DCR / discovery stubs. Omit when OAuthModule is registered so + # a real protected-resource document is not replaced with "no OAuth". + oauth_stub_routes = [ + Route("/.well-known/oauth-authorization-server", endpoint=h["oauth_not_supported"], methods=["GET", "POST"]), + Route("/.well-known/oauth-protected-resource", endpoint=h["oauth_not_supported"], methods=["GET", "POST"]), + Route("/register", endpoint=h["oauth_not_supported"], methods=["GET", "POST"]), + Route("/oauth/v2/register", endpoint=h["oauth_not_supported"], methods=["GET", "POST"]), + ] + + routes = [ + # More specific paths MUST come before the catch-all `Mount(endpoint, ...)` + # below — Starlette matches routes in order, and a `Mount` matches any + # path under its prefix, so `/mcp/health` would otherwise be swallowed + # by the `/mcp` mount before ever reaching the health route. + Route("/", endpoint=h["root_page"], methods=["GET"]), + Route("/widgets/preview", endpoint=h["widgets_preview"], methods=["GET"]), + Route("/widgets/preview/call", endpoint=h["widgets_preview_call"], methods=["POST"]), + *oauth_stub_routes, + Route("/json/version", endpoint=h["json_version"], methods=["GET"]), + Route("/json/list", endpoint=h["json_list"], methods=["GET"]), + Route("/json", endpoint=h["json_list"], methods=["GET"]), + Route("/favicon.ico", endpoint=h["favicon"], methods=["GET"]), + Route(f"{endpoint}/health", endpoint=h["health_check"], methods=["GET"]), + Mount(sse_messages_path, app=sse_transport.handle_post_message), + # `handle_streamable_http`/`sse_transport.handle_post_message` are raw + # ASGI apps (scope, receive, send), so they must be `Mount`ed rather + # than used as `Route` endpoints (which expect `Request -> Response`). + Mount(endpoint, app=mcp_asgi_app), + Route("/sse", endpoint=handle_sse, methods=["GET"]), + ] + if protocol_era != "legacy": + routes.append( + Route( + SSE_SUBSCRIPTIONS_PATH, + endpoint=subscriptions_listen_endpoint(mcp_app), + methods=["GET", "POST"], + ) + ) + + # Rewrite `/mcp` → `/mcp/` *before* routing so Inspector never sees a 307. + # CORS stays outermost so preflight still works on the original path. + middleware = [ + Middleware(ExactEndpointSlashMiddleware, endpoint=endpoint), + ] + if enable_cors: + expose_headers = list(CORS_EXPOSE_HEADER_NAMES) + if http_engine == "sessionful": + expose_headers.append(LEGACY_SESSION_HEADER) + # Single CORS layer for `/mcp`: the sidecar that used to add a second + # one has been removed (#22), so `MCP_CORS_ALLOWED_ORIGINS` is honored + # here and nowhere else. + allow_origins = list(configured_cors_origins()) or ["*"] + middleware.insert( + 0, + Middleware( + CORSMiddleware, + allow_origins=allow_origins, + allow_methods=["GET", "POST", "DELETE", "OPTIONS"], + # SEP-2243 permits application-defined Mcp-Param-* names. + # Starlette mirrors requested names when '*' is enabled. + allow_headers=[*CORS_ALLOW_HEADERS, "*"], + expose_headers=expose_headers, + ), + ) + + if _env_flag("NITROSTACK_HTTP_DEBUG"): + _enable_trace_logging() + middleware.insert(0, Middleware(RequestTraceMiddleware)) + + app = Starlette(routes=routes, middleware=middleware, lifespan=lifespan) + app.state.protocol_era = protocol_era + app.state.wire_mode = wire_mode + app.state.stateless = stateless + app.state.http_engine = http_engine + app.state.sessionful = http_engine == "sessionful" + app.state.session_manager = session_manager + app.state.streamable_http_manager_count = 1 + app.state.subscription_bus = getattr(mcp_app.mcp_server, "subscription_bus", None) + app.state.protocol_version = protocol_version_for_era(protocol_era) + return app \ No newline at end of file diff --git a/nitrostack/transports/http/constants.py b/nitrostack/transports/http/constants.py new file mode 100644 index 0000000..d93ba42 --- /dev/null +++ b/nitrostack/transports/http/constants.py @@ -0,0 +1,20 @@ +"""Shared constants for the HTTP transport.""" +from __future__ import annotations + +import logging +import time + +from nitrostack.transports.headers import CORS_ALLOW_HEADER_NAMES + +logger = logging.getLogger("nitrostack.transports.http") + +DEFAULT_ENDPOINT = "/mcp" + +# Shared 2026 allow-headers. Session id is exposed only on the sessionful engine. +CORS_ALLOW_HEADERS = list(CORS_ALLOW_HEADER_NAMES) + +# The Accept value `StreamableHTTPServerTransport` requires: it needs +# `application/json` on POST and `text/event-stream` on both POST and GET. +MCP_ACCEPT = "application/json, text/event-stream" + +_PROCESS_START = time.monotonic() \ No newline at end of file diff --git a/nitrostack/transports/http/env.py b/nitrostack/transports/http/env.py new file mode 100644 index 0000000..e205dc1 --- /dev/null +++ b/nitrostack/transports/http/env.py @@ -0,0 +1,16 @@ +"""Environment variable helpers for the HTTP transport.""" +from __future__ import annotations + +import os +from typing import List + + +def _env_list(name: str) -> List[str]: + raw = os.environ.get(name) + if not raw: + return [] + return [item.strip() for item in raw.split(",") if item.strip()] + + +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 diff --git a/nitrostack/transports/http/handlers.py b/nitrostack/transports/http/handlers.py new file mode 100644 index 0000000..45c07ab --- /dev/null +++ b/nitrostack/transports/http/handlers.py @@ -0,0 +1,251 @@ +"""Route handlers: landing page, widget preview, health, discovery stubs.""" +from __future__ import annotations + +import os +import time +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional + +from pydantic_core import PydanticUndefined +from starlette.responses import HTMLResponse, JSONResponse, Response + +from nitrostack.protocol.version import ProtocolEra, protocol_version_for_era +from nitrostack.transports.http.constants import _PROCESS_START, logger +from nitrostack.transports.landing_page import render_landing_page +from nitrostack.transports.proxy import public_url_for_request +from nitrostack.widgets.preview_page import render_preview_page + +if TYPE_CHECKING: + from nitrostack.core.app import McpApplication + from nitrostack.transports.http.middleware import SessionCapMiddleware + + +def _server_meta(mcp_app: "McpApplication") -> Dict[str, str]: + cfg = getattr(mcp_app, "server_config", None) + return { + "name": getattr(cfg, "name", None) or "NitroStack MCP Server", + "version": getattr(cfg, "version", None) or "1.0.0", + } + + +def _landing_tools(mcp_app: "McpApplication") -> List[Dict[str, Any]]: + tools: List[Dict[str, Any]] = [] + for entry in getattr(mcp_app, "_tools", {}).values(): + try: + schema = mcp_app._tool_input_schema(entry.input_model) + except Exception: + logger.exception("Landing page schema failed for %s", entry.config.name) + schema = None + tools.append( + { + "name": entry.config.name, + "description": entry.config.description or "", + "inputSchema": schema, + } + ) + return tools + + +def _preview_default_arguments(entry: Any) -> Dict[str, Any]: + """Prefill live preview with tool examples (shopId, openNow, …).""" + examples = getattr(getattr(entry, "config", None), "examples", None) + raw = getattr(examples, "input", None) if examples is not None else None + if isinstance(raw, dict): + return dict(raw) + model = getattr(entry, "input_model", None) + if model is None: + return {} + data: Dict[str, Any] = {} + for fname, field in getattr(model, "model_fields", {}).items(): + default = getattr(field, "default", PydanticUndefined) + if default is not PydanticUndefined and default is not None: + data[fname] = default + continue + if fname in ("shopId", "shop_id"): + data[fname] = "tonys-pizza" + elif fname == "product_id": + data[fname] = "sku-1" + elif fname == "filter": + data[fname] = "all" + elif fname == "openNow": + data[fname] = True + elif fname == "origin": + data[fname] = "JFK" + elif fname == "destination": + data[fname] = "LAX" + elif fname in ("departureDate", "departure_date"): + data[fname] = "2026-09-15" + elif fname in ("offerId", "offer_id"): + data[fname] = "off_mock123456" + elif fname in ("orderId", "order_id"): + data[fname] = "ord_mock123456" + elif fname == "query": + data[fname] = "London" + return data + + +def make_handlers( + mcp_app: "McpApplication", + *, + endpoint: str, + protocol_era: ProtocolEra, + http_engine: str, + stateless: bool, + json_response: bool, + session_cap: Optional["SessionCapMiddleware"], +) -> Dict[str, Callable]: + """Build the route handlers. Bodies are unchanged from the original + `build_http_app`; they close over the arguments above.""" + + def _request_public_mcp_url(request) -> str: + port = os.environ.get("PORT") or os.environ.get("MCP_SERVER_PORT") or "3000" + return public_url_for_request( + request, + path=endpoint.rstrip("/") or "/mcp", + fallback_host=f"localhost:{port}", + ) + + async def health_check(request): + return JSONResponse( + { + "status": "ok", + "transport": "streamable-http", + "protocolVersion": protocol_version_for_era(protocol_era), + "protocolEra": protocol_era, + "statelessCapable": http_engine == "sessionless", + "stateless": stateless, + "jsonResponse": json_response, + "sessions": session_cap.active_session_count if session_cap else None, + "uptimeSeconds": round(time.monotonic() - _PROCESS_START, 2), + "publicUrl": _request_public_mcp_url(request), + } + ) + + async def root_page(request): + meta = _server_meta(mcp_app) + return HTMLResponse( + render_landing_page( + name=meta["name"], + version=meta["version"], + description=getattr(getattr(mcp_app, "server_config", None), "description", None), + mcp_endpoint=_request_public_mcp_url(request), + tools=_landing_tools(mcp_app), + ) + ) + + async def oauth_not_supported(request): + """Inspector DCR posts `/register` when Authentication is on. + + Return JSON (not the HTML 404 page) so the client shows a clear + OAuth-off message instead of `Unexpected token '<'`. + """ + connect_url = _request_public_mcp_url(request) + return JSONResponse( + { + "error": "invalid_request", + "error_description": ( + "This MCP server does not use OAuth. In MCP Inspector turn " + "Authentication off, then connect with Streamable HTTP to " + f"{connect_url}." + ), + }, + status_code=404, + ) + + async def widgets_preview(request): + catalog = [] + for name, entry in getattr(mcp_app, "_tools", {}).items(): + component = getattr(entry, "component", None) + if component is None: + continue + catalog.append( + { + "name": name, + "resourceUri": component.resource_uri, + "arguments": _preview_default_arguments(entry), + } + ) + return HTMLResponse(render_preview_page(catalog)) + + async def widgets_preview_call(request): + try: + body = await request.json() + except Exception: + return JSONResponse({"error": "Invalid JSON body"}, status_code=400) + if not isinstance(body, dict): + return JSONResponse({"error": "JSON body must be an object"}, status_code=400) + name = body.get("tool") or "" + arguments = body.get("arguments") or {} + if not isinstance(arguments, dict): + return JSONResponse({"error": "arguments must be an object"}, status_code=400) + entry = getattr(mcp_app, "_tools", {}).get(name) + if entry is None or getattr(entry, "component", None) is None: + return JSONResponse({"error": f"No widget tool named {name!r}"}, status_code=404) + try: + result = await mcp_app._call_tool(name, arguments) + except Exception as exc: + logger.exception("Widget preview tool call failed for %s", name) + return JSONResponse({"error": str(exc)}, status_code=400) + structured = getattr(result, "structured_content", None) + if structured is None: + structured = getattr(result, "structuredContent", None) + try: + html = entry.component.html_with_data(structured) + except Exception as exc: + logger.exception("Widget preview render failed for %s", name) + return JSONResponse( + { + "error": f"Widget render failed: {exc}", + "structuredContent": structured, + "html": None, + "resourceUri": entry.component.resource_uri, + "isError": True, + }, + status_code=400, + ) + return JSONResponse( + { + "structuredContent": structured, + "html": html, + "resourceUri": entry.component.resource_uri, + "isError": bool(getattr(result, "is_error", None) if getattr(result, "is_error", None) is not None else getattr(result, "isError", False)), + } + ) + + async def json_version(request): + """Chrome/Cursor DevTools probe `/json/version` when a tab opens localhost.""" + meta = _server_meta(mcp_app) + health_path = f"{endpoint.rstrip('/')}/health" + return JSONResponse( + { + "Browser": meta["name"], + "Protocol-Version": protocol_version_for_era(protocol_era), + "User-Agent": f"NitroStack/{meta['version']}", + "webSocketDebuggerUrl": "", + "transport": "mcp", + "publicUrl": _request_public_mcp_url(request), + "endpoints": { + "mcp": endpoint, + "sse": "/sse", + "health": health_path, + }, + } + ) + + async def json_list(request): + """Chrome DevTools `/json` and `/json/list` expect a page list; empty = not CDP.""" + return JSONResponse([]) + + async def favicon(request): + return Response(status_code=204) + + return { + "request_public_mcp_url": _request_public_mcp_url, + "health_check": health_check, + "root_page": root_page, + "oauth_not_supported": oauth_not_supported, + "widgets_preview": widgets_preview, + "widgets_preview_call": widgets_preview_call, + "json_version": json_version, + "json_list": json_list, + "favicon": favicon, + } \ No newline at end of file diff --git a/nitrostack/transports/http/middleware.py b/nitrostack/transports/http/middleware.py new file mode 100644 index 0000000..5fbf314 --- /dev/null +++ b/nitrostack/transports/http/middleware.py @@ -0,0 +1,180 @@ +"""ASGI middleware for the HTTP transport.""" +from __future__ import annotations + +import time +from typing import Any, Dict, List, Optional +from starlette.responses import JSONResponse, Response +from starlette.types import ASGIApp, Receive, Scope, Send + +from nitrostack.transports.headers import strip_legacy_session_headers_asgi +from nitrostack.transports.http.constants import MCP_ACCEPT, logger + + +class ExactEndpointSlashMiddleware: + """Internally rewrite `/mcp` -> `/mcp/` so Starlette does not 307.""" + + def __init__(self, app: ASGIApp, endpoint: str) -> None: + self.app = app + self._exact = endpoint.rstrip("/") or "/" + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] == "http" and scope.get("path") == self._exact: + scope = dict(scope) + scope["path"] = self._exact + "/" + raw = scope.get("raw_path") + if isinstance(raw, (bytes, bytearray)): + scope["raw_path"] = raw.rstrip(b"/") + b"/" + await self.app(scope, receive, send) + + +class HeaderCompatMiddleware: + """Normalize Accept and version headers; JSON-RPC stays with the MCP manager.""" + + def __init__(self, app: ASGIApp, *, drop_session_headers: bool = False, + require_protocol_version: bool = False) -> None: + self.app = app + self.drop_session_headers = drop_session_headers + self.require_protocol_version = require_protocol_version + + @staticmethod + def _normalize_accept(value: Optional[str]) -> Optional[str]: + if value is None or not value.strip(): + return MCP_ACCEPT + media_types = [m.strip() for m in value.split(",")] + has_json = any(m.startswith("application/json") for m in media_types) + has_sse = any(m.startswith("text/event-stream") for m in media_types) + if has_json and has_sse: + return None + if any(m.startswith("*/*") for m in media_types): + return MCP_ACCEPT + return None + + @staticmethod + def _canonicalize_protocol_version(headers: List[Any]) -> List[Any]: + """Normalize casing without hiding duplicates from MCP's validator.""" + version_values: List[bytes] = [] + kept: List[Any] = [] + for key, value in headers: + if key.lower() == b"mcp-protocol-version": + version_values.append(value) + else: + kept.append((key, value)) + if not version_values: + return headers + kept.extend((b"mcp-protocol-version", v) for v in version_values) + return kept + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + headers: List[Any] = list(scope.get("headers") or []) + if self.require_protocol_version and scope.get("method") == "POST" and not any( + key.lower() == b"mcp-protocol-version" and value.strip() for key, value in headers + ): + response = JSONResponse( + {"jsonrpc": "2.0", "id": None, "error": { + "code": -32020, "message": "MCP-Protocol-Version header is required", + }}, status_code=400, + ) + await response(scope, receive, send) + return + if self.drop_session_headers: + headers = strip_legacy_session_headers_asgi(headers) + headers = self._canonicalize_protocol_version(headers) + + raw_accept = next((v for k, v in headers if k.lower() == b"accept"), None) + accept = self._normalize_accept(raw_accept.decode("latin-1") if raw_accept is not None else None) + if accept is not None: + headers = [(k, v) for k, v in headers if k.lower() != b"accept"] + headers.append((b"accept", accept.encode("latin-1"))) + logger.debug("Rewrote Accept %r -> %r for %s", raw_accept, accept, scope.get("path")) + + scope = dict(scope) + scope["headers"] = headers + await self.app(scope, receive, send) + + +class SessionCapMiddleware: + """ + Enforce a `max_sessions` concurrent-session cap on the Streamable HTTP + mount, returning a `429` JSON-RPC error once at capacity. + + `StreamableHTTPSessionManager` doesn't expose a public session count or a + session-created/closed hook, so this middleware tracks session ids itself + by observing the `mcp-session-id` request header (existing sessions) and + the `Mcp-Session-Id` response header (newly created sessions), and prunes + entries locally after `session_idle_timeout` so the count self-heals even + if a client disconnects without sending `DELETE`. + """ + + def __init__( + self, + app: ASGIApp, + max_sessions: Optional[int], + session_idle_timeout: Optional[float] = None, + ) -> None: + self.app = app + self.max_sessions = max_sessions + self.session_idle_timeout = session_idle_timeout + self._sessions: Dict[str, float] = {} + + def _prune_stale(self) -> None: + if not self.session_idle_timeout: + return + cutoff = time.monotonic() - self.session_idle_timeout + for sid in [s for s, seen in self._sessions.items() if seen < cutoff]: + self._sessions.pop(sid, None) + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http" or not self.max_sessions: + await self.app(scope, receive, send) + return + + self._prune_stale() + + headers = dict(scope.get("headers") or []) + raw_session_id = headers.get(b"mcp-session-id") + session_id = raw_session_id.decode() if raw_session_id else None + is_known = session_id is not None and session_id in self._sessions + + if not is_known and len(self._sessions) >= self.max_sessions: + response = JSONResponse( + { + "jsonrpc": "2.0", + "error": { + "code": -32000, + "message": "Too many sessions: server at capacity, retry later", + }, + "id": None, + }, + status_code=429, + ) + await response(scope, receive, send) + return + + if is_known: + self._sessions[session_id] = time.monotonic() + + new_session_id: Dict[str, Optional[str]] = {"value": None} + + async def send_wrapper(message: Any) -> None: + if message["type"] == "http.response.start": + for key, value in message.get("headers", []): + if key.lower() == b"mcp-session-id": + new_session_id["value"] = value.decode() + await send(message) + + await self.app(scope, receive, send_wrapper) + + if new_session_id["value"]: + self._sessions[new_session_id["value"]] = time.monotonic() + + if scope.get("method") == "DELETE" and session_id: + self._sessions.pop(session_id, None) + + @property + def active_session_count(self) -> int: + self._prune_stale() + return len(self._sessions) \ No newline at end of file diff --git a/nitrostack/transports/http/tracing.py b/nitrostack/transports/http/tracing.py new file mode 100644 index 0000000..5d3bf4f --- /dev/null +++ b/nitrostack/transports/http/tracing.py @@ -0,0 +1,97 @@ +"""Opt-in request tracing, enabled with NITROSTACK_HTTP_DEBUG=1.""" +from __future__ import annotations + +import logging +import sys +from typing import Any, Dict + +from starlette.types import ASGIApp, Receive, Scope, Send + +from nitrostack.core.log_emitter import install_log_handler +from nitrostack.transports.http.constants import logger + + +def _enable_trace_logging() -> None: + """ + Give `logger` its own stderr handler so tracing works regardless of how the + host application configured logging. + + `FileLogger` only attaches handlers to the `nitrostack` logger when it is + first instantiated, which for an HTTP server may not happen until a tool + runs. Until then this module's records fall through to `logging`'s + last-resort handler and INFO is discarded. Propagation is disabled so the + traces are not emitted twice once `FileLogger` does attach its handler. + stderr keeps them off stdout, which dual mode uses for JSON-RPC. + """ + install_log_handler("nitrostack.transports.http") + if any(getattr(handler, "_nitrostack_trace", False) for handler in logger.handlers): + return + handler = logging.StreamHandler(sys.stderr) + handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] (%(name)s): %(message)s")) + handler._nitrostack_trace = True # type: ignore[attr-defined] + logger.addHandler(handler) + logger.setLevel(logging.INFO) + logger.propagate = False + + +class RequestTraceMiddleware: + """ + Log the raw request line, headers and body of every HTTP request, plus the + response status and headers. + + Enabled only when `NITROSTACK_HTTP_DEBUG=1`. uvicorn's access log has no + timestamps and no headers, which makes it impossible to tell *why* the + `mcp` SDK rejected a client request (a `406` and a `400` from the SDK are + both header-driven) or even to correlate a failed client connection with a + log line. This middleware is the outermost layer so it sees requests + exactly as the client sent them, before CORS or any path rewriting. + """ + + MAX_BODY_CHARS = 2000 + REDACTED_HEADERS = {"authorization", "proxy-authorization", "cookie", "set-cookie"} + + def __init__(self, app: ASGIApp) -> None: + self.app = app + + @classmethod + def _decode_headers(cls, raw: Any) -> Dict[str, str]: + headers = {} + for key, value in raw or []: + name = key.decode("latin-1") + headers[name] = "" if name.lower() in cls.REDACTED_HEADERS else value.decode("latin-1") + return headers + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + method = scope.get("method") + path = scope.get("path") + query = (scope.get("query_string") or b"").decode("latin-1") + target = f"{path}?{query}" if query else path + logger.info("trace >> %s %s headers=%s", method, target, self._decode_headers(scope.get("headers"))) + + async def traced_receive() -> Any: + message = await receive() + if message.get("type") == "http.request": + body = message.get("body") or b"" + if body: + text = body.decode("utf-8", errors="replace") + if len(text) > self.MAX_BODY_CHARS: + text = text[: self.MAX_BODY_CHARS] + "..." + logger.info("trace >> %s %s body=%s", method, target, text) + return message + + async def traced_send(message: Any) -> None: + if message.get("type") == "http.response.start": + logger.info( + "trace << %s %s status=%s headers=%s", + method, + target, + message.get("status"), + self._decode_headers(message.get("headers")), + ) + await send(message) + + await self.app(scope, traced_receive, traced_send) \ No newline at end of file From c9daf8c55a89e9f54f617fbb274c91a53648dd10 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:21:43 +0530 Subject: [PATCH 126/146] feat(core): default app mode to openai (TS 1.1.3) Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- nitrostack/cli/_project_init.py | 4 +- nitrostack/core/app_mode.py | 18 +++-- .../templates/flight-booking/.env.example | 2 +- nitrostack/templates/pizzaz/.env.example | 2 +- nitrostack/widgets/preview_page.py | 2 +- tests/test_app_mode.py | 65 ++++++++++++++++--- tests/test_cli.py | 2 +- tests/test_widgets.py | 2 +- 9 files changed, 76 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 3ee7cfa..3a3a890 100644 --- a/README.md +++ b/README.md @@ -665,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 | |------|----------------|---------------| diff --git a/nitrostack/cli/_project_init.py b/nitrostack/cli/_project_init.py index 6faecdb..36fec80 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,7 @@ 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 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/core/app_mode.py b/nitrostack/core/app_mode.py index cadb517..eb08563 100644 --- a/nitrostack/core/app_mode.py +++ b/nitrostack/core/app_mode.py @@ -13,13 +13,19 @@ 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() - if raw in ("mcp-app", "mcpapp", "mcp_app", "mcp app", "mcp", "mcpapps"): + 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"): return "mcp-app" if raw in ("universal", "all", "both"): return "universal" @@ -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/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/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/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/tests/test_app_mode.py b/tests/test_app_mode.py index e11c0e1..8df9c54 100644 --- a/tests/test_app_mode.py +++ b/tests/test_app_mode.py @@ -1,9 +1,12 @@ -"""Phase 4 — NITROSTACK_APP_MODE parsing (Python-only).""" +"""NITROSTACK_APP_MODE / APP_MODE parsing (mirrors TS core app-mode tests).""" + from __future__ import annotations import os import sys +import pytest + sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from nitrostack.core.app_mode import ( @@ -16,19 +19,63 @@ ) -def test_default_mode_is_universal(monkeypatch): +@pytest.fixture(autouse=True) +def _clean_app_mode_env(monkeypatch): monkeypatch.delenv("NITROSTACK_APP_MODE", raising=False) + monkeypatch.delenv("APP_MODE", raising=False) + yield + + +def test_default_mode_is_openai(): + assert get_app_mode() == "openai" + assert is_mcp_app_mode() is False + assert is_openai_mode() is True + assert get_widget_mime_type() == RESOURCE_MIME_TYPE_OPENAI + + +def test_defaults_openai_for_blank_or_unknown(monkeypatch): + monkeypatch.setenv("NITROSTACK_APP_MODE", " ") + assert get_app_mode() == "openai" + monkeypatch.setenv("NITROSTACK_APP_MODE", "unknown-flavor") + assert get_app_mode() == "openai" + + +def test_openai_aliases(monkeypatch): + monkeypatch.setenv("NITROSTACK_APP_MODE", " OPENAI ") + assert get_app_mode() == "openai" + monkeypatch.setenv("NITROSTACK_APP_MODE", "chatgpt") + assert get_app_mode() == "openai" + monkeypatch.setenv("APP_MODE", "openai") + assert get_app_mode() == "openai" + + +@pytest.mark.parametrize( + "alias", + ["mcp-app", "mcpapp", "mcp_app", "mcp app", "MCP-APP"], +) +def test_mcp_app_aliases(monkeypatch, alias): + monkeypatch.setenv("NITROSTACK_APP_MODE", alias) + assert get_app_mode() == "mcp-app" + assert is_mcp_app_mode() is True + assert is_openai_mode() is False + assert get_widget_mime_type() == RESOURCE_MIME_TYPE_MCP_APP + + +def test_mcp_app_via_app_mode(monkeypatch): + monkeypatch.setenv("APP_MODE", "mcp-app") + assert get_app_mode() == "mcp-app" + + +@pytest.mark.parametrize("alias", ["universal", "UNIVERSAL", "all", "both"]) +def test_universal_aliases(monkeypatch, alias): + monkeypatch.setenv("NITROSTACK_APP_MODE", alias) assert get_app_mode() == "universal" assert is_mcp_app_mode() is True assert is_openai_mode() is True assert get_widget_mime_type() == RESOURCE_MIME_TYPE_MCP_APP -def test_mcp_app_and_openai_aliases(monkeypatch): - monkeypatch.setenv("NITROSTACK_APP_MODE", "mcp-app") - assert get_app_mode() == "mcp-app" - assert is_openai_mode() is False +def test_nitrostack_app_mode_wins_over_app_mode(monkeypatch): monkeypatch.setenv("NITROSTACK_APP_MODE", "openai") - assert get_app_mode() == "openai" - assert is_mcp_app_mode() is False - assert get_widget_mime_type() == RESOURCE_MIME_TYPE_OPENAI + monkeypatch.setenv("APP_MODE", "mcp-app") + assert get_app_mode() == "openai" \ No newline at end of file diff --git a/tests/test_cli.py b/tests/test_cli.py index 0a7fc3a..17d1576 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -139,7 +139,7 @@ def test_init_with_name_and_explicit_template(): env_text = open(os.path.join(project, ".env"), encoding="utf-8").read() assert "PORT=3000" in env_text assert "WIDGETS_DEV_PORT=3001" in env_text - assert "NITROSTACK_APP_MODE=universal" in env_text + assert "NITROSTACK_APP_MODE=openai" in env_text assert "SERVER_DESC=\"A test server\"" in env_text assert "SERVER_AUTHOR=\"Tester\"" in env_text assert os.path.isfile(os.path.join(project, "widgets", "out", "calculator-result.html")) 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 From 432e3330e7e5e7133da1bd2f43067c1613eca826 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:22:27 +0530 Subject: [PATCH 127/146] feat(core): expose tool arguments on ExecutionContext.input (TS #373) Co-Authored-By: Claude Opus 5.5 --- nitrostack/core/context.py | 1 + nitrostack/core/pipeline.py | 11 +++ tests/test_tool_context_input.py | 124 +++++++++++++++++++++++++++++++ 3 files changed, 136 insertions(+) create mode 100644 tests/test_tool_context_input.py 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/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 From d4e0263e085c28c6c242b8a8709299831a194cb2 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:23:47 +0530 Subject: [PATCH 128/146] feat(transports): configurable JSON body limit (TS #366) Co-Authored-By: Claude Opus 5.5 --- nitrostack/core/app_config.py | 1 + nitrostack/core/app_startup.py | 1 + nitrostack/transports/http/app.py | 10 ++- nitrostack/transports/http/env.py | 30 ++++++++- nitrostack/transports/http/middleware.py | 48 ++++++++++++++ tests/test_json_body_limit.py | 83 ++++++++++++++++++++++++ 6 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 tests/test_json_body_limit.py 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_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/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..9f32891 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 = "100kb" 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 100kb.""" + 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..303adfb 100644 --- a/nitrostack/transports/http/middleware.py +++ b/nitrostack/transports/http/middleware.py @@ -10,6 +10,54 @@ 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 _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 b"application/json" in value.lower(): + return True + return False + + 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: + response = JSONResponse({"error": "Payload too large"}, status_code=413) + await response(scope, receive, send) + return + except ValueError: + break + + seen = 0 + + async def limited_receive(): + nonlocal seen + message = await receive() + if message["type"] == "http.request": + chunk = message.get("body", b"") or b"" + seen += len(chunk) + if seen > self.limit_bytes: + response = JSONResponse({"error": "Payload too large"}, status_code=413) + await response(scope, receive, send) + return {"type": "http.disconnect"} + return message + + await self.app(scope, limited_receive, send) + + class ExactEndpointSlashMiddleware: """Internally rewrite `/mcp` -> `/mcp/` so Starlette does not 307.""" diff --git a/tests/test_json_body_limit.py b/tests/test_json_body_limit.py new file mode 100644 index 0000000..d62239c --- /dev/null +++ b/tests/test_json_body_limit.py @@ -0,0 +1,83 @@ +"""Configurable JSON body limit on HTTP transports (TS #366).""" + +from __future__ import annotations + +import asyncio +import json +import os +import sys + +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 + + +class EmptyInput(BaseModel): + pass + +INITIALIZE = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "1.0"}, + }, +} + + +@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 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 \ No newline at end of file From 5ac26d327da142bf1b5beb760d1e1759b2bbe836 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:27:06 +0530 Subject: [PATCH 129/146] fix(templates): harden starter calculator tools (TS #368) Co-Authored-By: Claude Opus 5.5 --- .../modules/calculator/calculator_tools.py | 115 +++++++++++++++--- tests/test_flight_booking.py | 1 + tests/test_pr12_review.py | 3 +- tests/test_starter_calculator_hardening.py | 40 ++++++ 4 files changed, 141 insertions(+), 18 deletions(-) create mode 100644 tests/test_starter_calculator_hardening.py 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/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_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_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 From 1ba549ca63bd14a24efeb9d15717ee0cc42a2bd6 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:32:14 +0530 Subject: [PATCH 130/146] fix: review fixes for TS sync Co-Authored-By: Claude Opus 5.5 --- nitrostack/core/app_mode.py | 2 +- tests/test_app_mode.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nitrostack/core/app_mode.py b/nitrostack/core/app_mode.py index eb08563..e53e7ce 100644 --- a/nitrostack/core/app_mode.py +++ b/nitrostack/core/app_mode.py @@ -25,7 +25,7 @@ def get_app_mode() -> AppMode: return "openai" if raw in ("openai", "chatgpt"): return "openai" - if raw in ("mcp-app", "mcpapp", "mcp_app", "mcp app"): + if raw in ("mcp-app", "mcpapp", "mcp_app", "mcp app", "mcp", "mcpapps"): return "mcp-app" if raw in ("universal", "all", "both"): return "universal" diff --git a/tests/test_app_mode.py b/tests/test_app_mode.py index 8df9c54..d1615ac 100644 --- a/tests/test_app_mode.py +++ b/tests/test_app_mode.py @@ -51,7 +51,7 @@ def test_openai_aliases(monkeypatch): @pytest.mark.parametrize( "alias", - ["mcp-app", "mcpapp", "mcp_app", "mcp app", "MCP-APP"], + ["mcp-app", "mcpapp", "mcp_app", "mcp app", "mcp", "mcpapps", "MCP-APP"], ) def test_mcp_app_aliases(monkeypatch, alias): monkeypatch.setenv("NITROSTACK_APP_MODE", alias) From 717b71309a79d56ca47fe1711ae475e1cffa6138 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:32:14 +0530 Subject: [PATCH 131/146] fix: review fixes for TS sync Co-Authored-By: Claude Opus 5.5 --- nitrostack/cli/_project_init.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/nitrostack/cli/_project_init.py b/nitrostack/cli/_project_init.py index 36fec80..163ecd8 100644 --- a/nitrostack/cli/_project_init.py +++ b/nitrostack/cli/_project_init.py @@ -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 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)") From 063cf32b04792223cee4cd5253e288277738920e Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:32:14 +0530 Subject: [PATCH 132/146] fix: review fixes for TS sync Co-Authored-By: Claude Opus 5.5 --- nitrostack/transports/http/env.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nitrostack/transports/http/env.py b/nitrostack/transports/http/env.py index 9f32891..fa1a07b 100644 --- a/nitrostack/transports/http/env.py +++ b/nitrostack/transports/http/env.py @@ -5,7 +5,7 @@ import re from typing import List, Union -DEFAULT_JSON_BODY_LIMIT = "100kb" +DEFAULT_JSON_BODY_LIMIT = "1mb" def _env_list(name: str) -> List[str]: @@ -36,7 +36,7 @@ def parse_json_body_limit(value: Union[str, int]) -> int: 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 100kb.""" + """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 From b064874770eb86a2f0c0cac5fa6e9bb4be1d6e73 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:32:14 +0530 Subject: [PATCH 133/146] fix: review fixes for TS sync Co-Authored-By: Claude Opus 5.5 --- nitrostack/transports/http/middleware.py | 56 +++++++++++++++++------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/nitrostack/transports/http/middleware.py b/nitrostack/transports/http/middleware.py index 303adfb..41f8728 100644 --- a/nitrostack/transports/http/middleware.py +++ b/nitrostack/transports/http/middleware.py @@ -17,15 +17,26 @@ 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 b"application/json" in value.lower(): + 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) @@ -35,27 +46,38 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if key.lower() == b"content-length": try: if int(value) > self.limit_bytes: - response = JSONResponse({"error": "Payload too large"}, status_code=413) - await response(scope, receive, send) + await self._reject_too_large(scope, receive, send) return except ValueError: break - seen = 0 - - async def limited_receive(): - nonlocal seen + buffered: List[Any] = [] + total = 0 + while True: message = await receive() - if message["type"] == "http.request": - chunk = message.get("body", b"") or b"" - seen += len(chunk) - if seen > self.limit_bytes: - response = JSONResponse({"error": "Payload too large"}, status_code=413) - await response(scope, receive, send) - return {"type": "http.disconnect"} - return message - - await self.app(scope, limited_receive, send) + 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: From 2b5765f69c9c8d0564d8498945587a9f5b44b69c Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:32:14 +0530 Subject: [PATCH 134/146] fix: review fixes for TS sync Co-Authored-By: Claude Opus 5.5 --- tests/test_json_body_limit.py | 132 ++++++++++++++++++++++++++++++++-- 1 file changed, 127 insertions(+), 5 deletions(-) diff --git a/tests/test_json_body_limit.py b/tests/test_json_body_limit.py index d62239c..59a5b27 100644 --- a/tests/test_json_body_limit.py +++ b/tests/test_json_body_limit.py @@ -6,7 +6,9 @@ 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__), ".."))) @@ -16,10 +18,7 @@ from nitrostack import McpApplicationFactory, ServerConfig, injectable, mcp_app, module, tool from nitrostack.core.context import ExecutionContext from nitrostack.transports.http import build_http_app - - -class EmptyInput(BaseModel): - pass +from nitrostack.transports.http.middleware import JsonBodyLimitMiddleware INITIALIZE = { "jsonrpc": "2.0", @@ -33,6 +32,10 @@ class EmptyInput(BaseModel): } +class EmptyInput(BaseModel): + pass + + @injectable() class PingController: @tool(name="ping", description="ping", input_schema=EmptyInput) @@ -61,6 +64,24 @@ def _big_initialize(padding: str) -> dict: 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( @@ -80,4 +101,105 @@ def test_json_body_limit_default_accepts_over_1kb(): 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 \ No newline at end of file + 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 From bcf98e071ca1bdbad57b3711cd11ebe7558f1b0f Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 17:19:14 +0530 Subject: [PATCH 135/146] perf(tools/list): cache tool input JSON schemas at bootstrap (130 -> 487 rps @ 50 tools) Precompute per-tool inputSchema during bootstrap so tools/list skips repeated model_json_schema() work while preserving APP_MODE-dependent list metadata. Co-Authored-By: Claude Opus 5.5 --- nitrostack/core/app_definitions.py | 4 ++-- nitrostack/core/app_entries.py | 4 +++- nitrostack/core/app_registration.py | 3 +++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/nitrostack/core/app_definitions.py b/nitrostack/core/app_definitions.py index a101422..97428c6 100644 --- a/nitrostack/core/app_definitions.py +++ b/nitrostack/core/app_definitions.py @@ -40,7 +40,7 @@ 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) + input_schema = entry.input_json_schema or self._tool_input_schema(entry.input_model) tasks_visible = self._tasks_visible_on_wire() meta: Dict[str, Any] = { @@ -105,7 +105,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..175bd5b 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: bool = False @dataclass diff --git a/nitrostack/core/app_registration.py b/nitrostack/core/app_registration.py index 0d5f99b..31cd0b4 100644 --- a/nitrostack/core/app_registration.py +++ b/nitrostack/core/app_registration.py @@ -127,12 +127,15 @@ 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(): + entry.has_spillover = self._has_spillover(entry.method) 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) + for entry in self._tools.values(): + entry.input_json_schema = self._tool_input_schema(entry.input_model) self._setup_handlers(self.mcp_server) def _assert_declared_dependencies( From e9606ff9e168dfd15cc3167a9ab98bee8877aa44 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 17:24:48 +0530 Subject: [PATCH 136/146] fix(templates): ship main and app_module in packed wheels Co-Authored-By: Claude Opus 5.5 --- .../templates/flight-booking/pyproject.toml | 3 +++ nitrostack/templates/pizzaz/pyproject.toml | 3 +++ nitrostack/templates/starter/pyproject.toml | 3 +++ tests/test_project_templates.py | 17 +++++++++++++++++ 4 files changed, 26 insertions(+) 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/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/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/tests/test_project_templates.py b/tests/test_project_templates.py index 2fe8a29..9323e86 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) From e3bffa9eeff3783e55754bfc558cefd34698668a Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 17:24:52 +0530 Subject: [PATCH 137/146] fix(tools/list): lazy spillover/schema cache and isolate inputSchema dicts Compute has_spillover and input JSON schema on first list build, wire spillover when tools register after bootstrap, and deep-copy cached schemas per response. Co-Authored-By: Claude Opus 5.5 --- nitrostack/core/app_definitions.py | 11 +++- nitrostack/core/app_entries.py | 2 +- nitrostack/core/app_registration.py | 21 ++++--- tests/test_tools_list_wire_cache.py | 85 +++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 11 deletions(-) create mode 100644 tests/test_tools_list_wire_cache.py diff --git a/nitrostack/core/app_definitions.py b/nitrostack/core/app_definitions.py index 97428c6..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 = entry.input_json_schema or 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] = { diff --git a/nitrostack/core/app_entries.py b/nitrostack/core/app_entries.py index 175bd5b..9177e15 100644 --- a/nitrostack/core/app_entries.py +++ b/nitrostack/core/app_entries.py @@ -20,7 +20,7 @@ class _ToolEntry: method: Callable component: Optional[Component] = None input_json_schema: Optional[Dict[str, Any]] = None - has_spillover: bool = False + has_spillover: Optional[bool] = None @dataclass diff --git a/nitrostack/core/app_registration.py b/nitrostack/core/app_registration.py index 31cd0b4..2cb73b6 100644 --- a/nitrostack/core/app_registration.py +++ b/nitrostack/core/app_registration.py @@ -127,17 +127,18 @@ 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(): - entry.has_spillover = self._has_spillover(entry.method) - 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) - for entry in self._tools.values(): - entry.input_json_schema = self._tool_input_schema(entry.input_model) + 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 ) -> None: @@ -223,6 +224,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/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 From 751a454858ab32954ccf4cb779d94025058e75a0 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 17:36:47 +0530 Subject: [PATCH 138/146] perf(import): lazy public API + lightweight nitrostack-py entry (~500ms -> ~20ms import) PEP 562 lazy exports for `import nitrostack`; CLI console script routes through `nitrostack.cli.entry` so --help avoids telemetry and heavy command imports. Co-Authored-By: Claude Opus 5.5 --- nitrostack/__init__.py | 545 ++++++++++++++----------------------- nitrostack/_export_map.py | 153 +++++++++++ nitrostack/cli/entry.py | 54 ++++ nitrostack/cli/main.py | 143 +++++----- nitrostack/cli/vendor.py | 2 +- pyproject.toml | 2 +- tests/test_lazy_imports.py | 60 ++++ 7 files changed, 539 insertions(+), 420 deletions(-) create mode 100644 nitrostack/_export_map.py create mode 100644 nitrostack/cli/entry.py create mode 100644 tests/test_lazy_imports.py diff --git a/nitrostack/__init__.py b/nitrostack/__init__.py index 8ca72b1..a6aea81 100644 --- a/nitrostack/__init__.py +++ b/nitrostack/__init__.py @@ -1,5 +1,14 @@ # NitroStack Python SDK Public API Exports +from __future__ import annotations + +import importlib +from typing import TYPE_CHECKING + +from nitrostack._export_map import EXPORT_LOCATIONS + +# NitroStack Python SDK Public API Exports + try: from importlib.metadata import PackageNotFoundError, version as _package_version @@ -21,347 +30,203 @@ 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'] + +_LAZY_CACHE: dict[str, object] = {} -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 __getattr__(name: str) -> object: + location = EXPORT_LOCATIONS.get(name) + if location is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + if name not in _LAZY_CACHE: + module_name, attr = location + module = importlib.import_module(module_name) + _LAZY_CACHE[name] = getattr(module, attr) + return _LAZY_CACHE[name] +def __dir__() -> list[str]: + return sorted({*globals().keys(), *__all__}) -__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/cli/entry.py b/nitrostack/cli/entry.py new file mode 100644 index 0000000..c698a1b --- /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() \ No newline at end of file diff --git a/nitrostack/cli/main.py b/nitrostack/cli/main.py index 507f7bb..187b6a8 100644 --- a/nitrostack/cli/main.py +++ b/nitrostack/cli/main.py @@ -264,86 +264,73 @@ def register_cursor_server(name: str, file_path: str = "main.py", *, global_conf ) -def main(): - if hasattr(sys.stdout, "reconfigure"): - try: - sys.stdout.reconfigure(encoding="utf-8") - except Exception: - pass - if hasattr(sys.stderr, "reconfigure"): +def dispatch_command(args, gen_parser) -> None: + def _run_command(fn, *fn_args, **fn_kwargs): 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, 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) - 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/vendor.py b/nitrostack/cli/vendor.py index 08abbea..a7ace2e 100644 --- a/nitrostack/cli/vendor.py +++ b/nitrostack/cli/vendor.py @@ -125,7 +125,7 @@ def _write_minimal_pyproject( f"{deps}" "]\n\n" "[project.scripts]\n" - 'nitrostack-py = "nitrostack.cli.main:main"\n\n' + 'nitrostack-py = "nitrostack.cli.entry:main"\n\n' "[tool.setuptools.packages.find]\n" 'include = ["nitrostack*"]\n\n' "[tool.setuptools]\n" diff --git a/pyproject.toml b/pyproject.toml index d63c2df..0688b7e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,7 @@ Repository = "https://github.com/nitrocloudofficial/nitrostack-python-sdk" Issues = "https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues" [project.scripts] -nitrostack-py = "nitrostack.cli.main:main" +nitrostack-py = "nitrostack.cli.entry:main" [tool.setuptools.packages.find] include = ["nitrostack*"] diff --git a/tests/test_lazy_imports.py b/tests/test_lazy_imports.py new file mode 100644 index 0000000..34d1bf1 --- /dev/null +++ b/tests/test_lazy_imports.py @@ -0,0 +1,60 @@ +"""Import-time regression: public API and CLI should stay light.""" + +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +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" From e21f75fe1e198a6493214ef4c90e96d27cabee95 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 17:50:28 +0530 Subject: [PATCH 139/146] fix(core): deterministic tools/list order Iterate resolved modules in DFS declaration order instead of a set so multi-module bootstrap order no longer depends on PYTHONHASHSEED. Co-Authored-By: Claude Opus 5.5 --- nitrostack/core/app_registration.py | 23 ++-- tests/test_list_registration_order.py | 146 ++++++++++++++++++++++++++ 2 files changed, 161 insertions(+), 8 deletions(-) create mode 100644 tests/test_list_registration_order.py diff --git a/nitrostack/core/app_registration.py b/nitrostack/core/app_registration.py index 2cb73b6..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) @@ -140,7 +141,7 @@ def _wire_spillover_for_entry(self, entry: _ToolEntry) -> None: 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] = [] @@ -170,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") 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 From 4416f5b08ab89080b9c1af03cc649c54a065a3b3 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 17:54:23 +0530 Subject: [PATCH 140/146] fix(import): keep subpackage attribute access with lazy exports Co-Authored-By: Claude Opus 5.5 --- nitrostack/__init__.py | 36 +++++++++++++---- nitrostack/cli/entry.py | 2 +- tests/test_lazy_imports.py | 80 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 9 deletions(-) diff --git a/nitrostack/__init__.py b/nitrostack/__init__.py index a6aea81..f6f10e0 100644 --- a/nitrostack/__init__.py +++ b/nitrostack/__init__.py @@ -3,10 +3,22 @@ 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: @@ -181,20 +193,28 @@ 'StatelessInvariants', 'assert_stateless_headers'] -_LAZY_CACHE: dict[str, object] = {} - def __getattr__(name: str) -> object: location = EXPORT_LOCATIONS.get(name) - if location is None: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - if name not in _LAZY_CACHE: + if location is not None: module_name, attr = location module = importlib.import_module(module_name) - _LAZY_CACHE[name] = getattr(module, attr) - return _LAZY_CACHE[name] + value = getattr(module, attr) + globals()[name] = value + return value + if name.startswith("_") or name not in _subpackage_names(): + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + try: + module = importlib.import_module(f"{__name__}.{name}") + except ModuleNotFoundError as exc: + if exc.name == f"{__name__}.{name}": + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None + raise + globals()[name] = module + return module + def __dir__() -> list[str]: - return sorted({*globals().keys(), *__all__}) + return sorted({*globals().keys(), *__all__, *_subpackage_names()}) if TYPE_CHECKING: from nitrostack.widgets.registry import WidgetExample, WidgetManifest, WidgetMetadata, WidgetRegistry, get_widget_registry # noqa: F401 diff --git a/nitrostack/cli/entry.py b/nitrostack/cli/entry.py index c698a1b..f324279 100644 --- a/nitrostack/cli/entry.py +++ b/nitrostack/cli/entry.py @@ -51,4 +51,4 @@ def main() -> None: track_command_invoked(args.command) dispatch_command(args, gen_parser) finally: - shutdown_telemetry() \ No newline at end of file + shutdown_telemetry() diff --git a/tests/test_lazy_imports.py b/tests/test_lazy_imports.py index 34d1bf1..1203e48 100644 --- a/tests/test_lazy_imports.py +++ b/tests/test_lazy_imports.py @@ -1,13 +1,26 @@ """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(): @@ -58,3 +71,70 @@ def test_nitrostack_py_help_starts_quickly(): 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 From 1f8015355a61cfff1ba11aec132ad6f22174bf72 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 19:11:17 +0530 Subject: [PATCH 141/146] fix(cli): dev hot reload restarts child reliably and serves new code Terminate the MCP child as a process group, wait for uvicorn shutdown, and keep child logs off the parent pipe so reload is not blocked. Add an integration test that edits a tool description and asserts tools/list updates within 10s. Co-Authored-By: Claude Opus 5.5 --- nitrostack/cli/_servers.py | 144 +++++++++++++++++++++++++++-------- tests/test_dev_hot_reload.py | 120 +++++++++++++++++++++++++++++ 2 files changed, 232 insertions(+), 32 deletions(-) create mode 100644 tests/test_dev_hot_reload.py diff --git a/nitrostack/cli/_servers.py b/nitrostack/cli/_servers.py index 02d748f..6493586 100644 --- a/nitrostack/cli/_servers.py +++ b/nitrostack/cli/_servers.py @@ -1,10 +1,86 @@ """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 _stop_child(process: subprocess.Popen | None) -> None: + if process is None or process.poll() is not None: + return + try: + if sys.platform == "win32": + process.terminate() + else: + os.killpg(process.pid, signal.SIGTERM) + except (ProcessLookupError, OSError, AttributeError): + try: + process.terminate() + except Exception: + pass + try: + process.wait(timeout=_CHILD_GRACE_SECONDS) + return + except subprocess.TimeoutExpired: + pass + try: + if sys.platform == "win32": + process.kill() + else: + os.killpg(process.pid, signal.SIGKILL) + 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 +110,41 @@ 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) + popen_kwargs = { + "env": env, + "cwd": os.getcwd(), + "stdout": subprocess.DEVNULL, + "stderr": subprocess.DEVNULL, + } + 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 +153,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 +175,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 +212,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 +261,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/tests/test_dev_hot_reload.py b/tests/test_dev_hot_reload.py new file mode 100644 index 0000000..3aaa2c3 --- /dev/null +++ b/tests/test_dev_hot_reload.py @@ -0,0 +1,120 @@ +"""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) \ No newline at end of file From 7ce8d8fc5c7750c82a62ad4e35da9acd9e013daa Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 19:11:17 +0530 Subject: [PATCH 142/146] fix(cli): pin minimum nitrostack version in generated/packed projects Emit nitrostack>= in vendored pyproject/requirements and wheel metadata so clean venv installs cannot resolve ancient PyPI builds. Co-Authored-By: Claude Opus 5.5 --- nitrostack/cli/_pack_metadata.py | 8 ++++++-- nitrostack/cli/vendor.py | 21 +++++++++++++++----- tests/test_cli.py | 2 +- tests/test_cli_upgrade_vendored.py | 4 +++- tests/test_vendor.py | 32 ++++++++++++++++++++++++++---- 5 files changed, 54 insertions(+), 13 deletions(-) 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/vendor.py b/nitrostack/cli/vendor.py index a7ace2e..62cec1f 100644 --- a/nitrostack/cli/vendor.py +++ b/nitrostack/cli/vendor.py @@ -19,10 +19,14 @@ from pathlib import Path from typing import List, Optional -from nitrostack.cli._shared import loads_toml, write_text_atomic +from nitrostack.cli._shared import loads_toml, requirement_name, write_text_atomic VENDOR_REL = os.path.join("vendor", "nitrostack") -_PLAIN_REQUIREMENT = "nitrostack" + + +def runtime_nitrostack_requirement() -> str: + """PEP 508 requirement pinning at least the SDK version running this CLI.""" + return f"nitrostack>={_distribution_version()}" _PATH_PINS = frozenset({"./vendor/nitrostack", "-e ./vendor/nitrostack"}) _NAMED_REQUIREMENT = re.compile( r"^(?:-e\s+|--editable\s+)?nitrostack" @@ -257,8 +261,9 @@ def replace_vendored_nitrostack(project: str, wheel: Optional[bytes] = None) -> def _pin_text(text: str) -> str: - """Keep `[project].dependencies` as a plain name (valid wheel Requires-Dist).""" - return _QUOTED_NITROSTACK.sub(lambda match: f"{match.group(1)}nitrostack{match.group(1)}", text) + """Keep `[project].dependencies` on `nitrostack` with a minimum SDK version.""" + spec = runtime_nitrostack_requirement() + return _QUOTED_NITROSTACK.sub(lambda match: f"{match.group(1)}{spec}{match.group(1)}", text) def _pin_requirements(path: Path) -> None: @@ -270,7 +275,7 @@ def _pin_requirements(path: Path) -> None: for line in lines: stripped = line.strip() if stripped in _PATH_PINS or _NAMED_REQUIREMENT.match(stripped): - out.append(f"{_PLAIN_REQUIREMENT}\n") + out.append(f"{runtime_nitrostack_requirement()}\n") else: out.append(line) path.write_text("".join(out), encoding="utf-8") @@ -296,6 +301,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/tests/test_cli.py b/tests/test_cli.py index 17d1576..6536dc6 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1535,7 +1535,7 @@ def test_pack_and_validate_agree_on_bom_dependencies(tmp_path: Path): validate_deps = validate_parse((tmp_path / "pyproject.toml").read_text(encoding="utf-8-sig")) assert pack_deps == validate_deps assert pack_deps[0] == "uvicorn[standard]>=0.20" - assert requirements_from_project(str(tmp_path)) == pack_deps + assert [d for d in requirements_from_project(str(tmp_path)) if not d.lower().startswith("nitrostack")] == [d for d in pack_deps if not d.lower().startswith("nitrostack")] issues = validate_dependencies(str(tmp_path)) assert not any("not declared" in issue.message for issue in issues) diff --git a/tests/test_cli_upgrade_vendored.py b/tests/test_cli_upgrade_vendored.py index 8cc09c8..45f3398 100644 --- a/tests/test_cli_upgrade_vendored.py +++ b/tests/test_cli_upgrade_vendored.py @@ -123,7 +123,9 @@ def test_upgrade_replaces_the_vendored_sdk_from_the_wheel(project: Path, no_skil assert deps == ["mcp<3,>=2", "pydantic>=2.0.0", 'tomli>=2.0.0; python_version < "3.11"'] # The project keeps the plain name; the vendored copy decides the version. assert (project / "pyproject.toml").read_text(encoding="utf-8") == pyproject_before - assert (project / "requirements.txt").read_text(encoding="utf-8") == "nitrostack\n" + from nitrostack.cli.vendor import runtime_nitrostack_requirement + + assert (project / "requirements.txt").read_text(encoding="utf-8") == f"{runtime_nitrostack_requirement()}\n" assert not [p for p in (project / "vendor").iterdir() if p.name.startswith(".nitrostack-")] diff --git a/tests/test_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 From fd6514a063160f23148b8ae50054c3fd474f32c1 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Thu, 26 Nov 2026 14:50:46 +0530 Subject: [PATCH 143/146] fix(cli): keep dev server output visible Hot reload had started sending the child server's stdout and stderr to /dev/null, which hid tracebacks and request logs during development. Co-Authored-By: Claude Opus 5.5 --- nitrostack/cli/_servers.py | 8 ++------ nitrostack/cli/vendor.py | 2 ++ 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/nitrostack/cli/_servers.py b/nitrostack/cli/_servers.py index 6493586..aa83c5c 100644 --- a/nitrostack/cli/_servers.py +++ b/nitrostack/cli/_servers.py @@ -117,12 +117,8 @@ def start_process(): env["PYTHONDONTWRITEBYTECODE"] = "1" if has_widgets: env["WIDGETS_DEV_PORT"] = str(widgets_port) - popen_kwargs = { - "env": env, - "cwd": os.getcwd(), - "stdout": subprocess.DEVNULL, - "stderr": subprocess.DEVNULL, - } + # 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: diff --git a/nitrostack/cli/vendor.py b/nitrostack/cli/vendor.py index 62cec1f..21dfbbc 100644 --- a/nitrostack/cli/vendor.py +++ b/nitrostack/cli/vendor.py @@ -27,6 +27,8 @@ 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" From 5367c50e807e0bb66d6bcb9518728bfc21de1d49 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Thu, 26 Nov 2026 14:50:47 +0530 Subject: [PATCH 144/146] chore: restore release automation removed by c625ff8 The revert of #41 on develop also deleted publish.yml, bump-version.yml, scripts/bump_version.py and its test. Without them, merging develop into main would remove the PyPI publish workflow. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/bump-version.yml | 85 +++++++++++++++ .github/workflows/publish.yml | 64 ++++++++++++ scripts/bump_version.py | 159 +++++++++++++++++++++++++++++ tests/test_bump_version.py | 68 ++++++++++++ 4 files changed, 376 insertions(+) create mode 100644 .github/workflows/bump-version.yml create mode 100644 .github/workflows/publish.yml create mode 100644 scripts/bump_version.py create mode 100644 tests/test_bump_version.py 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/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/tests/test_bump_version.py b/tests/test_bump_version.py new file mode 100644 index 0000000..ffa7bb7 --- /dev/null +++ b/tests/test_bump_version.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import importlib.util +import os + +import pytest + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +SCRIPT = os.path.join(ROOT, "scripts", "bump_version.py") + + +def _load(): + spec = importlib.util.spec_from_file_location("bump_version", SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +bump = _load() + + +def test_bump_x_y_z(): + assert bump.bump_x_y_z("0.3.5", "patch") == "0.3.6" + assert bump.bump_x_y_z("0.3.5", "minor") == "0.4.0" + assert bump.bump_x_y_z("0.3.5", "major") == "1.0.0" + + +def test_plan_bump_skips_unpublished_git_version(): + assert bump.plan_bump("0.3.6", "0.3.5", {"0.3.5"}, "patch") is None + + +def test_plan_bump_from_pypi_when_git_is_stale(): + released = {"0.3.2", "0.3.4", "0.3.5"} + assert bump.plan_bump("0.3.2", "0.3.5", released, "patch") == "0.3.6" + + +def test_plan_bump_patch_when_git_matches_pypi(): + assert bump.plan_bump("0.3.5", "0.3.5", {"0.3.5"}, "patch") == "0.3.6" + + +def test_should_publish(): + assert bump.should_publish("0.3.6", {"0.3.5"}) is True + assert bump.should_publish("0.3.5", {"0.3.5"}) is False + + +def test_apply_version_syncs_pyproject_and_lock(tmp_path): + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "nitrostack"\nversion = "0.3.2"\n', + encoding="utf-8", + ) + (tmp_path / "uv.lock").write_text( + '[[package]]\nname = "annotated-types"\nversion = "0.8.0"\n\n' + '[[package]]\nname = "nitrostack"\nversion = "0.3.2"\n' + 'source = { editable = "." }\n', + encoding="utf-8", + ) + bump.apply_version(str(tmp_path), "0.3.6") + pyproject = (tmp_path / "pyproject.toml").read_text(encoding="utf-8") + lock = (tmp_path / "uv.lock").read_text(encoding="utf-8") + assert 'version = "0.3.6"' in pyproject + assert 'name = "nitrostack"\nversion = "0.3.6"\nsource = { editable = "." }' in lock + assert 'name = "annotated-types"\nversion = "0.8.0"' in lock + + +def test_set_project_version_only_first_field(): + text = '[project]\nversion = "0.3.2"\n\n[tool.ruff]\ntarget-version = "py310"\n' + assert bump.read_project_version(bump.set_project_version(text, "0.3.6")) == "0.3.6" From 2a3c007282f24198de0e2c4939ebf5b0117ec128 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Thu, 26 Nov 2026 14:50:47 +0530 Subject: [PATCH 145/146] chore(release): 0.5.0 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- pyproject.toml | 2 +- tests/test_project_templates.py | 2 +- uv.lock | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3a3a890..17471dc 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ nitrostack-py pack --include-env # also pack .env files (use with caution!) ```bash nitrostack-py upgrade # move the project to the latest nitrostack on PyPI -nitrostack-py upgrade --version 0.4.2 # move it to exactly this version +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 diff --git a/pyproject.toml b/pyproject.toml index 0688b7e..9739a17 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nitrostack" -version = "0.4.2" +version = "0.5.0" description = "NitroStack Python SDK — A Python-idiomatic port of the NitroStack MCP framework" readme = "README.md" requires-python = ">=3.10" diff --git a/tests/test_project_templates.py b/tests/test_project_templates.py index 9323e86..fd6f94d 100644 --- a/tests/test_project_templates.py +++ b/tests/test_project_templates.py @@ -83,7 +83,7 @@ def test_generated_project_lifecycle(name, kind, tmp_path): run([kind], project) if kind == "code-mode": run(["cleanup"], project) - run(["cli", "upgrade", "--version", "0.4.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" diff --git a/uv.lock b/uv.lock index 60eba12..a0154ab 100644 --- a/uv.lock +++ b/uv.lock @@ -758,7 +758,7 @@ wheels = [ [[package]] name = "nitrostack" -version = "0.4.2" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "anyio" }, From 364e412a684522d131bed3cb9e0c316299f96a9e Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Thu, 26 Nov 2026 15:00:37 +0530 Subject: [PATCH 146/146] fix(cli): only signal process groups that dev created _stop_child called os.killpg(process.pid) unconditionally. With a fake process in tests, pid became 1 and Linux CI signalled init's process group, shutting the runner down. Signal a group only when the child leads its own group and it is not ours; otherwise fall back to terminate/kill. Co-Authored-By: Claude Opus 5.5 --- nitrostack/cli/_servers.py | 40 ++++++++++++++++++++++++++++-------- tests/test_dev_hot_reload.py | 18 +++++++++++++++- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/nitrostack/cli/_servers.py b/nitrostack/cli/_servers.py index aa83c5c..8bc0930 100644 --- a/nitrostack/cli/_servers.py +++ b/nitrostack/cli/_servers.py @@ -48,14 +48,41 @@ def _skip_polling_root(root: str) -> bool: 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: - if sys.platform == "win32": - process.terminate() - else: - os.killpg(process.pid, signal.SIGTERM) + _signal_child(process, force=False) except (ProcessLookupError, OSError, AttributeError): try: process.terminate() @@ -67,10 +94,7 @@ def _stop_child(process: subprocess.Popen | None) -> None: except subprocess.TimeoutExpired: pass try: - if sys.platform == "win32": - process.kill() - else: - os.killpg(process.pid, signal.SIGKILL) + _signal_child(process, force=True) except (ProcessLookupError, OSError, AttributeError): try: process.kill() diff --git a/tests/test_dev_hot_reload.py b/tests/test_dev_hot_reload.py index 3aaa2c3..b4b8d53 100644 --- a/tests/test_dev_hot_reload.py +++ b/tests/test_dev_hot_reload.py @@ -117,4 +117,20 @@ def test_dev_hot_reload_updates_tool_description(tmp_path: Path) -> None: tool_file.write_text(original, encoding="utf-8") if dev.poll() is None: dev.kill() - dev.wait(timeout=3) \ No newline at end of file + 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