From df5456f441f878ac36c7d81336eb09a8442ea5f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aykut=20G=C3=BCney?= <50778230+KeuqS@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:29:50 +0300 Subject: [PATCH 01/34] docs: document widget data and CSP handling --- README.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/README.md b/README.md index 6074a49..c1ea808 100644 --- a/README.md +++ b/README.md @@ -330,6 +330,57 @@ from nitrostack import WidgetOptions, WidgetCsp, widget `nitrostack-py init` copies `widgets/out/{route}.html` for every `@widget`. Widget HTML is generated in Python from the tool's `structuredContent` (one iframe, N cards). +#### Custom widget HTML: data and host bridge + +The tool result is passed to the widget as a JSON-compatible object. The shared host bridge +normalizes the following sources, in order: + +1. `window.openai.toolOutput.structuredContent` (or `toolResult`). +2. A JSON `application/json` content block, or a JSON object in a `text/plain` content block. +3. The `#nitrostack-tool-data` embedded JSON script used by Python-rendered pages. + +The normalized object is passed to `window.__nitroWidgetRender(data)`. Keep the tool return +shape stable and render from that object. `NITROSTACK_APP_MODE` changes the advertised +metadata and resource MIME type, not this data shape: + +- `openai` uses OpenAI output-template metadata and the OpenAI host data channel. +- `mcp-app` uses MCP Apps `_meta.ui` metadata; tool-result notifications are normalized by the bridge. +- `universal` (the default) publishes both forms. + +A hand-written file found at `widgets/out/{route}.html` is loaded as-is. The loader does +not inject the host bridge into that file. The built-in route templates created by `init` +do include the bridge, so custom HTML must include the equivalent bridge/render hook itself. +The generated files under `examples/widgets/out/` are the reference implementation. + +Minimal render hook (used after the bridge has been included): + +```html +
Waiting for tool data…
+ +``` + +#### Widget CSP metadata + +`WidgetCsp` describes the origins a widget needs; NitroStack publishes this as +metadata for the host to enforce. The SDK does not build or attach a response +`Content-Security-Policy` header itself. + +| Field | Meaning | MCP Apps metadata | OpenAI metadata | +|---|---|---|---| +| `connect_domains` | Network connections made by the widget | `connectDomains` | `connect_domains` | +| `resource_domains` | External resources such as images, scripts, or styles | `resourceDomains` | `resource_domains` | +| `frame_domains` | Origins the widget may embed in frames | `frameDomains` | `frame_domains` | + +Whether a scheme such as `data:` is accepted is host-dependent. Listing `data:` +in `resource_domains` requests/advertises that resource origin; it is not a guarantee +that every host will allow data URIs. + MCP Inspector: use **HTTP + stateless**, then the **Apps** tab. `tools/call` also embeds the data-filled HTML. Do not use `widgets/preview.html` as the live result — that file is a static helper. Live preview: `http://localhost:3000/widgets/preview`. From 421ae5f42bbc05fe7412f932a4ae76df07072373 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Fri, 16 Oct 2026 05:26:54 +0530 Subject: [PATCH 02/34] ConfigService: process environment wins over .env .env values were written over os.environ unconditionally, so the PORT=3000 that `nitrostack init` puts in .env overrode the PORT a host passes when starting the server. NitroStudio starts a second project on 3001; it bound 3000 anyway and died with "address already in use" (NITSTD-222). Keys already in the process environment are now kept, as with python-dotenv and Node's dotenv. .env still fills keys the process doesn't set, and defaults stay lowest. Co-Authored-By: Claude Opus 5.5 --- nitrostack/auth/config.py | 7 ++++++- tests/test_auth_modules.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/nitrostack/auth/config.py b/nitrostack/auth/config.py index f97c56d..7b4cd4c 100644 --- a/nitrostack/auth/config.py +++ b/nitrostack/auth/config.py @@ -19,7 +19,10 @@ def __init__( # Merge system environment variables first self._config.update(os.environ) - # Parse .env manually (no stdout prints allowed) + # Parse .env manually (no stdout prints allowed). The process + # environment wins, as with python-dotenv and Node's dotenv: a host + # that starts the server with PORT=3001 must not be overridden by the + # PORT=3000 that `nitrostack init` writes into .env. if not ignore_env_file and os.path.exists(env_file_path): try: with open(env_file_path, "r", encoding="utf-8") as f: @@ -31,6 +34,8 @@ def __init__( k, v = line.split("=", 1) k = k.strip() v = v.strip().strip("'\"") # Remove wrapping quotes + if k in os.environ: + continue self._config[k] = v os.environ[k] = v except Exception as e: diff --git a/tests/test_auth_modules.py b/tests/test_auth_modules.py index cd19843..8030511 100644 --- a/tests/test_auth_modules.py +++ b/tests/test_auth_modules.py @@ -178,3 +178,33 @@ def test_api_key_empty_string_is_rejected(monkeypatch): service = DIContainer.get_instance().resolve(ApiKeyService) assert service.validate("") is False assert service.validate("anything") is False + + +def test_config_process_env_wins_over_env_file(tmp_path, monkeypatch): + from nitrostack.core.app import resolve_http_port + + env_file = tmp_path / ".env" + env_file.write_text("PORT=3000\nFROM_FILE=file\n", encoding="utf-8") + monkeypatch.setenv("PORT", "3001") + monkeypatch.delenv("FROM_FILE", raising=False) + ConfigModule.for_root(env_file_path=str(env_file), defaults={"PORT": "9999", "ONLY_DEFAULT": "d"}) + cfg = DIContainer.get_instance().resolve(ConfigService) + assert cfg.get("PORT") == "3001" + assert resolve_http_port() == 3001 + # Keys the process doesn't set still come from the file, then defaults. + assert cfg.get("FROM_FILE") == "file" + assert cfg.get("ONLY_DEFAULT") == "d" + monkeypatch.delenv("FROM_FILE", raising=False) + + +def test_config_env_file_port_applies_when_process_has_none(tmp_path, monkeypatch): + from nitrostack.core.app import resolve_http_port + + env_file = tmp_path / ".env" + env_file.write_text("PORT=3005\n", encoding="utf-8") + monkeypatch.delenv("PORT", raising=False) + ConfigModule.for_root(env_file_path=str(env_file), defaults={"PORT": "3000"}) + cfg = DIContainer.get_instance().resolve(ConfigService) + assert cfg.get("PORT") == "3005" + assert resolve_http_port() == 3005 + monkeypatch.delenv("PORT", raising=False) From 57e8d35e85f4922c875e5e21fad173ea2f20cb7d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:04:04 +0000 Subject: [PATCH 03/34] chore(release): 0.4.1 --- pyproject.toml | 2 +- uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index f370a58..68ea96b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nitrostack" -version = "0.4.0" +version = "0.4.1" description = "NitroStack Python SDK — A Python-idiomatic port of the NitroStack MCP framework" readme = "README.md" requires-python = ">=3.10" diff --git a/uv.lock b/uv.lock index ed009ff..bab7717 100644 --- a/uv.lock +++ b/uv.lock @@ -568,7 +568,7 @@ wheels = [ [[package]] name = "nitrostack" -version = "0.3.2" +version = "0.4.1" source = { editable = "." } dependencies = [ { name = "anyio" }, From 0e145d4bc8c71cefa293a2e643d0a8d42ea3746a Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Fri, 16 Oct 2026 05:55:41 +0530 Subject: [PATCH 04/34] Add scripts/release.sh for releasing to PyPI by hand publish.yml only uploads through PyPI trusted publishing, which has never run here, and the Bump version workflow can't open its release PR (the org doesn't allow GitHub Actions to create pull requests). The script covers both: optionally makes release/ from origin/main (--bump), checks the branch matches origin, the lockfile matches and the version is new, runs the tests, builds, twine-checks, uploads after asking, verifies a clean install from PyPI, and opens the release PR. `--tag` tags origin/main after the merge. `--dry-run` stops before anything leaves the machine. Co-Authored-By: Claude Opus 5.5 --- scripts/release.sh | 235 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 scripts/release.sh diff --git a/scripts/release.sh b/scripts/release.sh new file mode 100644 index 0000000..c12c846 --- /dev/null +++ b/scripts/release.sh @@ -0,0 +1,235 @@ +#!/usr/bin/env bash +# Release the SDK to PyPI from this machine. +# +# publish.yml uploads only through PyPI trusted publishing, and the Bump +# version workflow can't open its release PR (the org doesn't let GitHub +# Actions create pull requests). This script does both by hand. +# +# 1. Get a release branch, either way: +# - the Bump version workflow already pushed `release/X.Y.Z`: +# git switch release/X.Y.Z && git pull +# - or have this script make one from origin/main: +# scripts/release.sh --bump patch (or minor / major) +# 2. On that branch: scripts/release.sh +# checks, tests, builds, uploads to PyPI (asks first), verifies the +# install, and opens the release PR if there isn't one. +# 3. Merge the release PR (publish.yml sees the version on PyPI and skips). +# 4. scripts/release.sh --tag tags origin/main vX.Y.Z and pushes the tag. +# +# Options: +# --bump KIND patch|minor|major: create release/ from origin/main +# --skip-tests don't run the test suite before building +# --yes don't ask before uploading +# --dry-run stop before anything leaves this machine (no push, upload, +# PR or tag); --bump still creates the branch locally +# --tag step 4 only +# +# Needs uv, gh (for the PR) and a PyPI token, in ~/.pypirc ([pypi] with +# username __token__) or in TWINE_USERNAME=__token__ / TWINE_PASSWORD. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" + +BUMP="" +SKIP_TESTS=0 +YES=0 +DRY_RUN=0 +TAG_ONLY=0 +while [ $# -gt 0 ]; do + case "$1" in + --bump) + BUMP="${2:-}" + shift + ;; + --skip-tests) SKIP_TESTS=1 ;; + --yes) YES=1 ;; + --dry-run) DRY_RUN=1 ;; + --tag) TAG_ONLY=1 ;; + -h | --help) + sed -n '2,29p' "$0" | sed 's/^# \{0,1\}//' + exit 0 + ;; + *) + echo "Unknown option: $1 (see --help)" >&2 + exit 2 + ;; + esac + shift +done +case "$BUMP" in "" | patch | minor | major) ;; *) + echo "--bump takes patch, minor or major" >&2 + exit 2 + ;; +esac + +step() { printf '\n==> %s\n' "$*"; } +fail() { + printf '\nerror: %s\n' "$*" >&2 + exit 1 +} + +# uv: a pyenv shim fails inside this repo when the pinned .python-version +# isn't installed in pyenv, so fall back to known install locations. +find_uv() { + local candidate + for candidate in "${UV:-}" "$(command -v uv 2>/dev/null || true)" \ + "$HOME/.local/bin/uv" "$HOME/.cargo/bin/uv" /opt/homebrew/bin/uv /usr/local/bin/uv \ + "$HOME"/.pyenv/versions/*/bin/uv; do + if [ -n "$candidate" ] && [ -x "$candidate" ] && "$candidate" --version >/dev/null 2>&1; then + echo "$candidate" + return 0 + fi + done + return 1 +} +UV="$(find_uv)" || fail "uv not found. Install it (https://docs.astral.sh/uv/) or set UV=/path/to/uv." +UVX="$(dirname "$UV")/uvx" +[ -x "$UVX" ] || UVX="$UV tool run" +PY=("$UV" run --no-project --quiet python) + +project_version() { "${PY[@]}" -c 'import re,sys; print(re.search(r"(?m)^version = \"([^\"]+)\"", sys.stdin.read()).group(1))'; } +# Exit 0 when VERSION is on PyPI. +on_pypi() { curl -fs -o /dev/null "https://pypi.org/pypi/nitrostack/$1/json"; } +tag_exists() { git rev-parse -q --verify "refs/tags/v$1" >/dev/null || [ -n "$(git ls-remote --tags origin "refs/tags/v$1")" ]; } + +step "Fetching origin" +git fetch -q --tags origin + +# --- Step 4: tag the merged release ------------------------------------- +if [ "$TAG_ONLY" = 1 ]; then + VERSION="$(git show origin/main:pyproject.toml | project_version)" + echo "origin/main is at $VERSION" + on_pypi "$VERSION" || fail "$VERSION isn't on PyPI. Release it first (scripts/release.sh on its release branch)." + tag_exists "$VERSION" && fail "Tag v$VERSION already exists." + if [ "$DRY_RUN" = 1 ]; then + echo "Dry run: would tag origin/main ($(git rev-parse --short origin/main)) as v$VERSION and push it." + exit 0 + fi + git tag -a "v$VERSION" origin/main -m "nitrostack $VERSION" + git push -q origin "v$VERSION" + echo "Tagged and pushed v$VERSION." + exit 0 +fi + +[ -z "$(git status --porcelain --untracked-files=no)" ] || fail "Uncommitted changes. Commit or stash them first." + +# --- Step 1 (optional): make the release branch ------------------------- +if [ -n "$BUMP" ]; then + step "Creating a $BUMP release branch from origin/main" + MAIN_VERSION="$(git show origin/main:pyproject.toml | project_version)" + on_pypi "$MAIN_VERSION" || fail "origin/main's version $MAIN_VERSION isn't on PyPI yet. Release it as is (no --bump)." + # bump_version plans from the checked-out tree, so check out origin/main; + # go back to where we were if anything below fails. + ORIG_REF="$(git branch --show-current)" + ORIG_REF="${ORIG_REF:-$(git rev-parse HEAD)}" + trap 'git switch -q "$ORIG_REF" 2>/dev/null || git switch -q --detach "$ORIG_REF"' ERR + git switch -q --detach origin/main + NEXT="$("${PY[@]}" scripts/bump_version.py --root . --bump "$BUMP" | tail -n 1)" + [ -n "$NEXT" ] || { + git switch -q "$ORIG_REF" 2>/dev/null || git switch -q --detach "$ORIG_REF" + fail "PyPI's project index doesn't list $MAIN_VERSION yet (it's cached for up to 15 minutes after a release). Try again shortly." + } + git rev-parse -q --verify "refs/heads/release/$NEXT" >/dev/null && fail "Branch release/$NEXT already exists locally." + [ -z "$(git ls-remote --heads origin "release/$NEXT")" ] || fail "release/$NEXT already exists on origin. Use it: git switch release/$NEXT" + git switch -q -c "release/$NEXT" + "${PY[@]}" scripts/bump_version.py --root . --bump "$BUMP" --write >/dev/null + git add pyproject.toml uv.lock + git commit -q -m "chore(release): $NEXT" + trap - ERR + echo "Created release/$NEXT with the version bump." + if [ "$DRY_RUN" = 0 ]; then + git push -q -u origin "release/$NEXT" + fi +fi + +# --- Step 2: check, test, build, upload --------------------------------- +BRANCH="$(git branch --show-current)" +[ -n "$BRANCH" ] || fail "Not on a branch. Switch to the release branch first." +VERSION="$(project_version /dev/null; then + installed="$("$VENV/bin/python" -c 'import importlib.metadata as m, nitrostack; print(m.version("nitrostack"))')" + break + fi + sleep 10 +done +rm -rf "$(dirname "$VENV")" +[ "$installed" = "$VERSION" ] || fail "Couldn't install and import nitrostack==$VERSION from PyPI." +echo "OK: pip install nitrostack==$VERSION works and imports." + +# --- Release PR --------------------------------------------------------- +step "Release PR" +if ! command -v gh >/dev/null; then + echo "gh not found. Open a PR from $BRANCH to main, labelled 'release'." +else + PR="$(gh pr list --base main --head "$BRANCH" --json url --jq '.[0].url // empty')" + if [ -z "$PR" ]; then + PR="$(gh pr create --base main --head "$BRANCH" --title "chore(release): $VERSION" --label release --body "$( + cat < Date: Fri, 16 Oct 2026 06:00:10 +0530 Subject: [PATCH 05/34] release.sh: review fixes - Run from a temp copy: --bump switches branches, which can rewrite the script while bash is still reading it. - --bump plans from origin/main's files in a scratch folder and checks everything before switching, so a failed check no longer leaves you on a detached origin/main. - Only a 404 counts as "not on PyPI"; offline or PyPI errors stop the run instead of passing the "version is new" check. - No terminal and no --yes means "no" instead of a silent exit. - Tag the uploaded commit right after the upload (no separate step that could tag later, unreleased merges on main). --tag stays for catching up untagged releases and prefers the release branch head. - A failed PR creation after the upload prints the manual step. Co-Authored-By: Claude Opus 5.5 --- scripts/release.sh | 82 +++++++++++++++++++++++++++++++--------------- 1 file changed, 55 insertions(+), 27 deletions(-) diff --git a/scripts/release.sh b/scripts/release.sh index c12c846..8042f2f 100644 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -12,9 +12,8 @@ # scripts/release.sh --bump patch (or minor / major) # 2. On that branch: scripts/release.sh # checks, tests, builds, uploads to PyPI (asks first), verifies the -# install, and opens the release PR if there isn't one. +# install, tags the uploaded commit vX.Y.Z, and opens the release PR. # 3. Merge the release PR (publish.yml sees the version on PyPI and skips). -# 4. scripts/release.sh --tag tags origin/main vX.Y.Z and pushes the tag. # # Options: # --bump KIND patch|minor|major: create release/ from origin/main @@ -22,13 +21,24 @@ # --yes don't ask before uploading # --dry-run stop before anything leaves this machine (no push, upload, # PR or tag); --bump still creates the branch locally -# --tag step 4 only +# --tag only tag a version that's already on PyPI but untagged +# (the head of origin/release/X.Y.Z if it still exists, +# else origin/main) # # Needs uv, gh (for the PR) and a PyPI token, in ~/.pypirc ([pypi] with # username __token__) or in TWINE_USERNAME=__token__ / TWINE_PASSWORD. set -euo pipefail -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +# bash reads a script while running it, and --bump switches branches, which +# can rewrite this file. Run from a copy. +if [ -z "${NITRO_RELEASE_ROOT:-}" ]; then + NITRO_RELEASE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + copy="$(mktemp)" + cp "${BASH_SOURCE[0]}" "$copy" + NITRO_RELEASE_ROOT="$NITRO_RELEASE_ROOT" NITRO_RELEASE_COPY="$copy" exec bash "$copy" "$@" +fi +trap 'rm -f "${NITRO_RELEASE_COPY:-}"' EXIT +ROOT="$NITRO_RELEASE_ROOT" cd "$ROOT" BUMP="" @@ -47,7 +57,7 @@ while [ $# -gt 0 ]; do --dry-run) DRY_RUN=1 ;; --tag) TAG_ONLY=1 ;; -h | --help) - sed -n '2,29p' "$0" | sed 's/^# \{0,1\}//' + sed -n '2,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//' exit 0 ;; *) @@ -89,8 +99,17 @@ UVX="$(dirname "$UV")/uvx" PY=("$UV" run --no-project --quiet python) project_version() { "${PY[@]}" -c 'import re,sys; print(re.search(r"(?m)^version = \"([^\"]+)\"", sys.stdin.read()).group(1))'; } -# Exit 0 when VERSION is on PyPI. -on_pypi() { curl -fs -o /dev/null "https://pypi.org/pypi/nitrostack/$1/json"; } +# Exit 0 when VERSION is on PyPI, 1 when it isn't; stop on any other answer +# (offline, PyPI down) rather than guess. +on_pypi() { + local code + code="$(curl -s -o /dev/null -w '%{http_code}' "https://pypi.org/pypi/nitrostack/$1/json" || true)" + case "$code" in + 200) return 0 ;; + 404) return 1 ;; + *) fail "Couldn't check PyPI for $1 (HTTP ${code:-none}). Check your connection and try again." ;; + esac +} tag_exists() { git rev-parse -q --verify "refs/tags/v$1" >/dev/null || [ -n "$(git ls-remote --tags origin "refs/tags/v$1")" ]; } step "Fetching origin" @@ -102,11 +121,17 @@ if [ "$TAG_ONLY" = 1 ]; then echo "origin/main is at $VERSION" on_pypi "$VERSION" || fail "$VERSION isn't on PyPI. Release it first (scripts/release.sh on its release branch)." tag_exists "$VERSION" && fail "Tag v$VERSION already exists." + # Tag what was uploaded: the release branch head, when it's still around. + TARGET=origin/main + if git rev-parse -q --verify "refs/remotes/origin/release/$VERSION" >/dev/null && + [ "$(git show "origin/release/$VERSION:pyproject.toml" | project_version)" = "$VERSION" ]; then + TARGET="origin/release/$VERSION" + fi if [ "$DRY_RUN" = 1 ]; then - echo "Dry run: would tag origin/main ($(git rev-parse --short origin/main)) as v$VERSION and push it." + echo "Dry run: would tag $TARGET ($(git rev-parse --short "$TARGET")) as v$VERSION and push it." exit 0 fi - git tag -a "v$VERSION" origin/main -m "nitrostack $VERSION" + git tag -a "v$VERSION" "$TARGET" -m "nitrostack $VERSION" git push -q origin "v$VERSION" echo "Tagged and pushed v$VERSION." exit 0 @@ -119,24 +144,23 @@ if [ -n "$BUMP" ]; then step "Creating a $BUMP release branch from origin/main" MAIN_VERSION="$(git show origin/main:pyproject.toml | project_version)" on_pypi "$MAIN_VERSION" || fail "origin/main's version $MAIN_VERSION isn't on PyPI yet. Release it as is (no --bump)." - # bump_version plans from the checked-out tree, so check out origin/main; - # go back to where we were if anything below fails. - ORIG_REF="$(git branch --show-current)" - ORIG_REF="${ORIG_REF:-$(git rev-parse HEAD)}" - trap 'git switch -q "$ORIG_REF" 2>/dev/null || git switch -q --detach "$ORIG_REF"' ERR - git switch -q --detach origin/main - NEXT="$("${PY[@]}" scripts/bump_version.py --root . --bump "$BUMP" | tail -n 1)" - [ -n "$NEXT" ] || { - git switch -q "$ORIG_REF" 2>/dev/null || git switch -q --detach "$ORIG_REF" - fail "PyPI's project index doesn't list $MAIN_VERSION yet (it's cached for up to 15 minutes after a release). Try again shortly." - } + # Plan from origin/main's files (and its bump_version.py) in a scratch + # folder, so nothing changes here until every check has passed. + PLAN="$(mktemp -d)" + for f in pyproject.toml uv.lock scripts/bump_version.py; do + mkdir -p "$PLAN/$(dirname "$f")" + git show "origin/main:$f" >"$PLAN/$f" + done + NEXT="$("${PY[@]}" "$PLAN/scripts/bump_version.py" --root "$PLAN" --bump "$BUMP" | tail -n 1)" + [ -n "$NEXT" ] || fail "PyPI's project index doesn't list $MAIN_VERSION yet (it's cached for up to 15 minutes after a release). Try again shortly." git rev-parse -q --verify "refs/heads/release/$NEXT" >/dev/null && fail "Branch release/$NEXT already exists locally." [ -z "$(git ls-remote --heads origin "release/$NEXT")" ] || fail "release/$NEXT already exists on origin. Use it: git switch release/$NEXT" - git switch -q -c "release/$NEXT" - "${PY[@]}" scripts/bump_version.py --root . --bump "$BUMP" --write >/dev/null + "${PY[@]}" "$PLAN/scripts/bump_version.py" --root "$PLAN" --bump "$BUMP" --write >/dev/null + git switch -q -c "release/$NEXT" origin/main + cp "$PLAN/pyproject.toml" "$PLAN/uv.lock" . + rm -rf "$PLAN" git add pyproject.toml uv.lock git commit -q -m "chore(release): $NEXT" - trap - ERR echo "Created release/$NEXT with the version bump." if [ "$DRY_RUN" = 0 ]; then git push -q -u origin "release/$NEXT" @@ -186,11 +210,15 @@ fi step "Uploading nitrostack $VERSION to PyPI" if [ "$YES" = 0 ]; then - read -r -p "Upload nitrostack $VERSION to PyPI? A version can't be uploaded twice. [y/N] " answer + read -r -p "Upload nitrostack $VERSION to PyPI? A version can't be uploaded twice. [y/N] " answer || answer="" case "$answer" in y | Y | yes) ;; *) fail "Not uploaded." ;; esac fi $UVX twine upload --non-interactive "$WHEEL" "$SDIST" +# Tag the exact commit that was built and uploaded. +git tag -a "v$VERSION" HEAD -m "nitrostack $VERSION" +git push -q origin "v$VERSION" || echo "warning: couldn't push tag v$VERSION. Push it yourself: git push origin v$VERSION" >&2 + step "Checking the release on PyPI" for _ in $(seq 1 30); do on_pypi "$VERSION" && break @@ -224,12 +252,12 @@ else - Bump SDK version to **$VERSION** in \`pyproject.toml\` and \`uv.lock\`. - $VERSION is already on PyPI (uploaded by \`scripts/release.sh\`), so \`publish.yml\` will skip the upload when this merges. -After merging, tag it: \`scripts/release.sh --tag\` +Tagged \`v$VERSION\` on the uploaded commit. EOF - )")" + )")" || PR="Couldn't open the PR. Open one from $BRANCH to main, labelled 'release'." fi echo "$PR" fi echo -echo "Released nitrostack $VERSION. Next: merge the release PR, then run scripts/release.sh --tag" +echo "Released nitrostack $VERSION (tag v$VERSION). Next: merge the release PR." From b7257e8601782087ab600df883e4747e5fed8001 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Fri, 16 Oct 2026 06:10:31 +0530 Subject: [PATCH 06/34] docs: refresh README for the current SDK; add PyPI project links The README is the PyPI project page. Rewrite it for 0.4.x: building blocks (tools, resources, prompts, guards, auth, caching, rate limits, tasks, events, health), env precedence, templates, clients. tests/test_readme_examples.py compiles every python block, checks every nitrostack import exists, and runs the Quick Start and Building Blocks examples through the testing harness so the page can't drift. Co-Authored-By: Claude Opus 5.5 --- README.md | 528 +++++++++++++++++++++++++--------- pyproject.toml | 6 + tests/test_readme_examples.py | 148 ++++++++++ 3 files changed, 541 insertions(+), 141 deletions(-) create mode 100644 tests/test_readme_examples.py diff --git a/README.md b/README.md index 6074a49..66b02cd 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,26 @@ # NitroStack Python SDK -A Python-idiomatic port of the **NitroStack** Model Context Protocol (MCP) framework, enabling NestJS-like modular architecture, dependency injection, execution pipelines, background task processing, built-in authentication modules, and a diagnostic testing harness. +Build Model Context Protocol (MCP) servers in Python with a NestJS-style structure: modules, dependency injection, decorators for tools, resources and prompts, and a pipeline of guards, middleware, interceptors, pipes and exception filters. It's the Python port of the [NitroStack](https://docs.nitrostack.ai/) TypeScript framework. + +- **Docs:** [docs.nitrostack.ai/python](https://docs.nitrostack.ai/python) +- **Source and issues:** [github.com/nitrocloudofficial/nitrostack-python-sdk](https://github.com/nitrocloudofficial/nitrostack-python-sdk) +- **Requires:** Python 3.10+ --- ## Features -- **Nested Modular Architecture**: Group components cleanly with `@module`. -- **Dependency Injection**: Explicit class constructor DI with `DIContainer` and `@injectable(deps=[...])`. -- **Pipeline Interceptors**: Build guards, middleware, interceptors, pipes, and exception filters for tool execution. -- **Asynchronous Background Tasks**: Spawn background workers automatically for long-running tools. -- **Built-in Authentication**: Modules for API Keys, JWT verification, and OAuth 2.1 (featuring Protected Resource Metadata discovery servers). -- **In-Process Testing Harness**: Run unit and integration tests against modules without managing subprocesses or real network transports. -- **CLI Tooling (`nitrostack-py`)**: Scaffold apps (`init`), generate components (`generate`), pack deployable wheels (`pack`), upgrade/install dependencies, validate projects, auto-register servers with Claude (`register`), and run hot-reload development servers (`dev`). +- **Modules and dependency injection**: group code with `@module`, inject services with `@injectable(deps=[...])`. +- **Tools, resources and prompts**: plain decorated methods, with Pydantic input/output schemas, tool annotations and examples. +- **Execution pipeline**: guards, middleware, interceptors, pipes and exception filters per tool. +- **Auth**: API keys, JWT, and OAuth 2.1 (protected resource metadata, token introspection or JWKS, PKCE, CIMD, scopes). +- **Long-running tasks**: tools that report progress and can be cancelled, over the MCP tasks API. +- **Widgets**: attach an HTML UI to a tool for ChatGPT Apps and MCP Apps clients. +- **Transports**: stdio, Streamable HTTP (plus legacy SSE), or both at once; 2025 and 2026 protocol versions. +- **Caching, rate limits, events and health checks** as decorators. +- **Testing harness**: call tools, resources and prompts in-process, without a transport. +- **CLI (`nitrostack-py`)**: scaffold, generate code, run with hot reload, validate, pack wheels, upgrade. +- **NitroStudio**: open a project folder in [NitroStudio](https://nitrostack.ai/) to run, chat with and debug it. --- @@ -20,41 +28,43 @@ A Python-idiomatic port of the **NitroStack** Model Context Protocol (MCP) frame ```bash pip install nitrostack +# or +uv add nitrostack ``` -To install local developer or test dependencies: +To work on the SDK itself (tests and tooling): + ```bash -pip install -e . +pip install -e ".[dev]" ``` --- ## Scaffolding a New Project (Recommended) -You can quickly scaffold a new project template using the interactive CLI tool: - ```bash -nitrostack-py init +nitrostack-py init my-server --template python-starter ``` *(Or via Python: `python -m nitrostack.cli.main init`)* -The project name is optional on the command line. If omitted, the CLI asks for it next: +Both arguments are optional; without them `init` asks: -```bash -nitrostack-py init my-server --template python-starter -``` +1. **Project name**. Default: `my-mcp-server`. +2. **Template**: + + | Template | What it shows | + |---|---| + | `python-starter` | A calculator: tools, a widget, a health check. | + | `python-pizzaz` | A pizza shop finder with map and list widgets. | + | `python-oauth` | Flight booking with OAuth 2.1 and scope-guarded tools (see `OAUTH_SETUP.md` in the project). | -This launches an interactive prompt where you can: -1. **Project name** (if not passed as an argument). Default: `my-mcp-server`. -2. **Choose a template** by explicit name: - - **python-starter**: A simple calculator server. - - **python-pizzaz**: A pizza shop finder with maps and widgets. - - **python-oauth**: A flight booking server demonstrating OAuth 2.1 authentication and guarded routes. -3. **Provide metadata**: Specify a custom description and author name. -4. **Install dependencies**: `Install dependencies: (Y/n)` — Enter or `Y` runs `npm install` in `src/widgets`; `n` skips it. `--skip-install` skips the prompt. +3. **Description and author**. +4. **Install dependencies (Y/n)**: installs the Python dependencies (`uv sync` when `uv` is on PATH, otherwise `.venv` + `pip`), then runs `npm install` in `src/widgets` if the template has one. `--skip-install` skips this. -Optional port flags override the defaults (**3000** MCP, **3001** widgets): +`init` also installs agent skills for this SDK (from [skills-python-sdk](https://github.com/nitrocloudofficial/skills-python-sdk)) into the project's coding-agent folders. `--force` overwrites existing skill folders. + +Port flags override the defaults (**3000** for MCP, **3001** for widgets): ```bash nitrostack-py init my-server --template python-starter --port 4000 --widget 4001 @@ -62,86 +72,9 @@ nitrostack-py dev --port 4000 --widget 4001 nitrostack-py start --port 4000 --widget 4001 ``` -`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies` — that breaks the cloud wheel metadata. - -Once scaffolded, follow the next steps printed by the CLI to run your server, configure environment variables, and try it out. - ---- - -## CLI (`nitrostack-py`) - -The CLI is installed with the SDK (`nitrostack-py`, or `python -m nitrostack.cli.main`). Run `nitrostack-py --help` to list commands. - -### Project lifecycle - -```bash -nitrostack-py init my-server -nitrostack-py dev # hot-reload development server -nitrostack-py start # production server (no reload) -nitrostack-py register --name my-mcp-server --file app.py -``` - -### Generate components - -Existing `tool` and `module` generators are unchanged. Additional generators create pipeline and service stubs that follow the current Python decorator/protocol APIs: - -```bash -nitrostack-py generate tool add_numbers -nitrostack-py generate module payments -nitrostack-py generate guard MyGuard -nitrostack-py generate pipe Validation -nitrostack-py generate interceptor Transform -nitrostack-py generate filter HttpException -nitrostack-py generate service Email -``` - -Generated files: - -| Command | Output | -|---|---| -| `generate tool ` | `{name}_tool.py` in the current directory | -| `generate module ` | `{name}_module.py` in the current directory | -| `generate guard ` | `guards/.py` | -| `generate pipe ` | `pipes/.py` | -| `generate interceptor ` | `interceptors/.py` | -| `generate filter ` | `filters/.py` | -| `generate service ` | `services/.py` | - -Attach generated pipeline classes with `@use_guards`, `@use_pipes`, `@use_interceptors`, or `@use_filters`. Register services in a module's `providers` list. - -### Pack a deployable wheel - -```bash -nitrostack-py pack --dry-run # list files; does not write an artifact -nitrostack-py pack # write dist/*.whl -``` - -`pack` builds a wheel with setuptools (the same backend as this SDK), refreshes `requirements.txt` from `pyproject.toml` when possible, and always includes `.env.example`. The real `.env` file and other secrets are never packed. Temporary build directories are deleted afterwards. - -### Upgrade, install, validate - -```bash -nitrostack-py upgrade # latest nitrostack on PyPI (writes nitrostack>=latest) -nitrostack-py upgrade --version 0.3.2 # pin exactly this version (writes nitrostack==0.3.2) -nitrostack-py upgrade --dry-run # print the change; do not edit files -nitrostack-py upgrade --allow-downgrade --version 0.1.0 # required to pin an older version - -nitrostack-py install # install project + development dependencies -nitrostack-py install --production # skip optional extras and requirements-dev.txt - -nitrostack-py validate # lint deps, @mcp_app imports, and @module() refs -``` - -`init` writes `pyproject.toml`, `.python-version`, and `uv.toml`, then runs `uv lock` when `uv` is on PATH. `install` prefers `uv sync` in that case. If `requirements.txt` pins nitrostack as a local path (`-e /path/to/nitrostack-python-sdk`), install uses `pip install -r requirements.txt` instead so unpublished SDK testing still works. The uv equivalent is: +`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies`; that breaks the cloud wheel metadata. Because the SDK is vendored, `nitrostack-py upgrade` (below) is how an existing project picks up a new SDK release. -```toml -[tool.uv.sources] -nitrostack = { path = "/path/to/nitrostack-python-sdk", editable = true } -``` - -then `uv lock` / `uv sync`. Without `uv`, install falls back to `.venv` + `pip`. - -`upgrade` updates the `nitrostack` dependency spec in `pyproject.toml` in place (and `requirements.txt` when it already pins nitrostack). `--version X` writes `nitrostack==X`. Without `--version`, the latest PyPI release is written as `nitrostack>=latest`. A target older than the currently declared version is rejected unless `--allow-downgrade` is passed. `validate` reports missing/conflicting dependencies, `@mcp_app` modules that fail to import, and `@module()` `imports`/`exports` that are not real classes. +Once scaffolded, follow the next steps the CLI prints. --- @@ -231,9 +164,13 @@ if __name__ == "__main__": asyncio.run(main()) ``` +Run it with `python app.py` (stdio), or `MCP_TRANSPORT_TYPE=http python app.py` for Streamable HTTP on `http://127.0.0.1:3000/mcp`. + +Scaffolded projects split the same pieces into files: `main.py` calls `McpApplicationFactory.create(AppModule)`, `app_module.py` holds the root module, and each feature lives in `modules//`. When the server's name is generic (`app` or `mcp-server`, as with a root `@module(name="app")` and no `@mcp_app`), the name and description reported to clients come from `SERVER_NAME` / `SERVER_DESC`. + ### 2. Configure Environment Variables -The SDK reads standard settings from the environment or `.env` files: +The SDK reads settings from the process environment and the project's `.env` file. **The process environment wins:** a variable already set when the server starts (for example `PORT=3001` from NitroStudio or your shell) is not overwritten by `.env`. `.env` fills in what isn't set, and `ConfigModule.for_root(defaults=...)` fills in the rest. (Before 0.4.1, `.env` overwrote the environment.) | Environment Variable | Description | |---|---| @@ -241,6 +178,7 @@ The SDK reads standard settings from the environment or `.env` files: | `TRUSTED_PROXIES` / `MCP_TRUSTED_PROXIES` | Comma-separated IPs, CIDRs, or hostnames allowed to send `X-Forwarded-Host` / `X-Forwarded-Proto`. Unset means those headers are ignored. `X-Forwarded-For` is never used to decide trust. | | `PORT` / `MCP_SERVER_PORT` | The port to bind for HTTP/SSE transport (default: `3000`). Overridden by `nitrostack-py --port`. | | `WIDGETS_DEV_PORT` | Widget Next.js port (default: `3001`). Overridden by `nitrostack-py --widget`. | +| `SERVER_NAME` / `SERVER_DESC` | Server name and description reported to clients when the configured name is generic (`app`, `mcp-server`). `init` sets `SERVER_NAME` to the project folder name. | | `MCP_TRANSPORT_TYPE` | Transport selection: `stdio`, `http`, or `dual` (combining stdio + HTTP/SSE). | | `NODE_ENV` | If set to `production`, defaults to `dual` transport. Otherwise defaults to `stdio`. | | `MCP_MAX_SESSIONS` | Cap on concurrent Streamable HTTP sessions; new sessions beyond the cap get an HTTP `429`. Unset = unlimited. | @@ -249,11 +187,241 @@ The SDK reads standard settings from the environment or `.env` files: | `NITRO_MCP_PROTOCOL_VERSION` | Protocol era (case-insensitive): `auto` / `both` / `dual` / `dual-spec` (default when unset or unknown), `modern` / `latest` / `2026` / `2026-07-28`, or `legacy` / `2025` / `2025-06-18` / `2025-11-25`. `auto` is not the same as `modern`. Wins over `ServerConfig.protocol_era`. | | `MCP_STATELESS` | Explicit override: `true` forces `modern` (stateless HTTP), `false` forces `legacy` (sessionful). Wins over `NITRO_MCP_PROTOCOL_VERSION` and `ServerConfig.protocol_era`. | | `MCP_ALLOWED_HOSTS` / `MCP_ALLOWED_ORIGINS` | Comma-separated allow-lists for DNS-rebinding protection, used only when CORS is disabled. | +| `NITROSTACK_APP_MODE` | Widget metadata flavour: `universal` (default), `openai`, or `mcp-app`. See [Widgets](#widgets-ui-tools). | +| `OAUTH_REQUIRED` | With `OAuthGuard`: `true` rejects calls without a valid token. Unset lets token-less calls through, for local development. | | `NITROSTACK_LOG_FILE` | Destination file for logs (default: `nitrostack.log`). | | `NITROSTACK_LOG_LEVEL` | Log level (`DEBUG`, `INFO`, `WARNING`, `ERROR`). | | `NITROSTACK_LOG_TO_STDOUT` | Set to `true` to allow logging to stdout under stdio transport (Caution: may corrupt protocol stream). | | `NITROSTACK_HTTP_DEBUG` | Set to `1` to log every HTTP request (method, path, headers, body) and response status to stderr. Use when diagnosing a client that fails to connect: uvicorn's access log shows neither headers nor timestamps. | +Read your own settings through `ConfigService`: + +```python +from nitrostack import ConfigModule, ConfigService, injectable, module + +@injectable(deps=[ConfigService]) +class WeatherService: + def __init__(self, config: ConfigService): + self.units = config.get("WEATHER_UNITS", "metric") + self.api_key = config.get_or_throw("WEATHER_API_KEY") # KeyError if unset + +@module( + name="app", + imports=[ConfigModule.for_root(env_file_path=".env", defaults={"WEATHER_UNITS": "metric"})], + providers=[WeatherService], +) +class AppModule: + pass +``` + +--- + +## Building Blocks + +The examples below build on each other (later ones reuse `LookupInput` and `NoInput`) and are methods on a controller (an `@injectable` class listed in a module's `controllers`). Every tool takes `(self, input, context)`, where `input` is an instance of its `input_schema` model and `context` is the `ExecutionContext` (logger, auth, task, request metadata). + +### Tools + +```python +from pydantic import BaseModel, Field +from nitrostack import tool, initial_tool, ToolAnnotations, ToolExamples, ExecutionContext + +class LookupInput(BaseModel): + city: str = Field(description="City name") + +class Weather(BaseModel): + city: str + temp: float + units: str + +class NoInput(BaseModel): + pass + +class WeatherController: + @tool( + name="get_weather", + title="Get Weather", + description="Current weather for a city", + input_schema=LookupInput, + output_schema=Weather, # optional; adds structuredContent + annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True), + examples=ToolExamples(input={"city": "Paris"}, output={"city": "Paris", "temp": 21, "units": "metric"}), + ) + async def get_weather(self, input: LookupInput, context: ExecutionContext) -> dict: + return {"city": input.city, "temp": 21, "units": "metric"} + + @tool(name="whats_new", description="Shown when a client connects", input_schema=NoInput) + @initial_tool # clients that support it call this on connect + async def whats_new(self, input: NoInput, context: ExecutionContext) -> str: + return "Try get_weather." +``` + +A tool with no arguments still needs an input model; use an empty `BaseModel` subclass like `NoInput` (not `BaseModel` itself). `visibility="hidden"` keeps a tool callable but out of `tools/list`. Raise an exception to return an MCP error to the client. + +### Resources and prompts + +```python +from typing import List +from nitrostack import resource, prompt, PromptArgument, PromptMessage, ExecutionContext + +class WeatherController: + @resource(uri="weather://units", name="Units", description="Units in use", mime_type="text/plain") + async def units(self, context: ExecutionContext) -> str: + return "metric" + + @prompt( + name="forecast_brief", + description="Write a short forecast", + arguments=[PromptArgument(name="city", description="City", required=True)], + ) + async def forecast_brief(self, args: dict, context: ExecutionContext) -> List[PromptMessage]: + return [PromptMessage(role="user", content=f"Write a short forecast for {args['city']}.")] +``` + +### Guards, interceptors, pipes, middleware and filters + +Each is a small class with one async method; attach it with a decorator below `@tool`. Generate stubs with `nitrostack-py generate guard|pipe|interceptor|filter `. + +| Stage | Method | Attach with | Runs | +|---|---|---|---| +| Guard | `can_activate(context) -> bool` | `@use_guards(...)` | first; `False` rejects the call ("Access denied by guard") | +| Pipe | `transform(value, metadata)` | `@use_pipes(...)` | on the tool input, after guards | +| Middleware | `use(context, next_fn)` | `@use_middleware(...)` | around interceptors and the tool | +| Interceptor | `intercept(context, next_fn)` | `@use_interceptors(...)` | around the tool; can change its result | +| Exception filter | `catch(error, context)` | `@use_filters(...)` | on errors; its return value becomes the result | + +```python +from nitrostack import tool, use_guards, use_interceptors, use_filters, ExecutionContext + +class OfficeHoursGuard: + async def can_activate(self, context: ExecutionContext) -> bool: + return context.metadata.get("office_open", True) + +class TimingInterceptor: + async def intercept(self, context: ExecutionContext, next_fn): + result = await next_fn() + context.logger.info(f"{context.tool_name} finished") + return result + +class FriendlyErrors: + async def catch(self, error: Exception, context: ExecutionContext): + return {"error": str(error)} + +class WeatherController: + @tool(name="get_forecast", description="Forecast for a city", input_schema=LookupInput) + @use_guards(OfficeHoursGuard) + @use_interceptors(TimingInterceptor) + @use_filters(FriendlyErrors) + async def get_forecast(self, input: LookupInput, context: ExecutionContext) -> dict: + return {"city": input.city, "forecast": "sunny"} +``` + +### Authentication + +Register an auth module in the root module, then guard tools. Guards fill `context.auth` (`subject`, `scopes`, `client_id`, `claims`, ...). + +| Module | Guard | Configured by | +|---|---|---| +| `ApiKeyModule.for_root(keys_env_prefix="API_KEY", hashed=False)` | `ApiKeyGuard` | `x-api-key` header checked against `API_KEY`, `API_KEY_1`, `API_KEY_2`, ... (SHA-256 hashes when `hashed=True`) | +| `JWTModule.for_root(secret_env_var="JWT_SECRET", audience=..., issuer=...)` | `JwtGuard` | `Authorization: Bearer ` | +| `OAuthModule.for_root(resource_uri=..., authorization_servers=[...], scopes_supported=[...], token_introspection_endpoint=... or jwks_uri=...)` | `OAuthGuard` | OAuth 2.1 access tokens, audience-bound; `OAUTH_REQUIRED=true` to require one | + +```python +from nitrostack import ( + ApiKeyGuard, ApiKeyModule, ExecutionContext, OAuthGuard, module, require_scopes, tool, use_guards, +) + +class AccountController: + @tool(name="get_balance", description="Account balance", input_schema=NoInput) + @use_guards(ApiKeyGuard) + async def get_balance(self, input: NoInput, context: ExecutionContext) -> dict: + return {"balance": 42} + + @tool(name="close_account", description="Close the account", input_schema=NoInput) + @use_guards(OAuthGuard) + @require_scopes("admin") # needs context.auth with every listed scope + async def close_account(self, input: NoInput, context: ExecutionContext) -> dict: + return {"closed": True} + +@module(name="app", imports=[ApiKeyModule.for_root()], controllers=[AccountController]) +class AppModule: + pass +``` + +Register `ApiKeyModule` when you use `ApiKeyGuard`: without it, the guard falls back to the `API_KEY` variable, and with neither set it lets every call through. + +`has_scope`, `has_any_scope` and `has_all_scopes` check `context.auth` inside a tool. For OAuth, start from the `python-oauth` template and its `OAUTH_SETUP.md`; PKCE (`generate_pkce_params`, `verify_pkce`), client ID metadata documents (`resolve_cimd`) and `generate_www_authenticate_header` are exported for custom flows. + +### Caching and rate limits + +```python +from nitrostack import cache, injectable, rate_limit, tool + +@injectable() +class WeatherService: + @cache(ttl=60) # seconds; keyed on the arguments + async def lookup(self, city: str) -> dict: + return {"city": city, "temp": 21} + +class WeatherController: + @tool(name="ping", description="Ping", input_schema=NoInput) + @rate_limit(max=10, window=60) # 10 calls per 60 s, across all callers + async def ping(self, input: NoInput, context: ExecutionContext) -> str: + return "pong" +``` + +Put `@cache` on a service method with plain, hashable arguments (strings, numbers, tuples). It can't key on a tool's Pydantic input object. + +### Long-running tasks + +Set `task_support="optional"` (or `"required"`) and the client can run the tool as an MCP task: it polls `tasks/get`, can cancel it, and gets live `notifications/progress` when it sends a `progressToken`. `context.task` is `None` when the tool is called normally. + +```python +import asyncio +from pydantic import BaseModel +from nitrostack import tool, ExecutionContext + +class ReportInput(BaseModel): + steps: int = 5 + +class ReportController: + @tool(name="build_report", description="Build a report", input_schema=ReportInput, task_support="optional") + async def build_report(self, input: ReportInput, context: ExecutionContext) -> dict: + for step in range(1, input.steps + 1): + if context.task: + context.task.update_progress(f"Step {step}/{input.steps}") + context.task.throw_if_cancelled() + await asyncio.sleep(1) + return {"steps": input.steps} +``` + +### Events and health checks + +```python +from typing import List +from nitrostack import EventEmitter, health_check, injectable, on_event + +@injectable() +class OrderService: + async def place(self, order_id: str) -> None: + await EventEmitter.get_instance().emit("order.placed", {"id": order_id}) + +@injectable() +class AuditLog: + def __init__(self): + self.entries: List[str] = [] + + @on_event("order.placed") + def record(self, payload: dict) -> None: + self.entries.append(payload["id"]) + + @health_check("audit") + def healthy(self) -> bool: + return True +``` + +Listeners and health checks are found on any provider or controller in a module. When any health check exists, the server exposes the `health://status` resource (`{"audit": "healthy"}`). Keep health checks synchronous. + --- ## Transport Options @@ -279,28 +447,93 @@ server = ServerConfig(name="my-server", transport_type="http", max_sessions=100, --- -## Developing & Testing +## CLI (`nitrostack-py`) + +The CLI is installed with the SDK (`nitrostack-py`, or `python -m nitrostack.cli.main`). Run `nitrostack-py --help` to list commands. + +### Project lifecycle -### Auto-Registering with Claude Desktop -To automatically configure your server script with Claude Desktop without any manual editing: ```bash -nitrostack-py register --name my-mcp-server --file app.py +nitrostack-py init my-server +nitrostack-py dev # hot-reload development server +nitrostack-py start # production server (no reload) +nitrostack-py register --name my-mcp-server --file main.py ``` -*(If your scripts folder is not in PATH, use: `python -m nitrostack.cli.main register --name my-mcp-server --file app.py`)* -This detects all standard and Windows Store installation directories, sets up virtualenv executables, and writes the JSON configuration. Once registered, simply restart Claude Desktop. +### Generate components -### Widgets (UI tools) +```bash +nitrostack-py generate tool add_numbers +nitrostack-py generate module payments +nitrostack-py generate guard MyGuard +nitrostack-py generate pipe Validation +nitrostack-py generate interceptor Transform +nitrostack-py generate filter HttpException +nitrostack-py generate service Email +``` -Bind a static HTML template to a tool with `@widget` and return domain JSON from the handler: +Generated files: + +| Command | Output | +|---|---| +| `generate tool ` | `{name}_tool.py` in the current directory | +| `generate module ` | `{name}_module.py` in the current directory | +| `generate guard ` | `guards/.py` | +| `generate pipe ` | `pipes/.py` | +| `generate interceptor ` | `interceptors/.py` | +| `generate filter ` | `filters/.py` | +| `generate service ` | `services/.py` | + +Attach generated pipeline classes with `@use_guards`, `@use_pipes`, `@use_interceptors`, or `@use_filters`. Register services in a module's `providers` list. + +### Pack a deployable wheel + +```bash +nitrostack-py pack --dry-run # list files; does not write an artifact +nitrostack-py pack # write dist/*.whl +``` + +`pack` builds a wheel with setuptools (the same backend as this SDK), refreshes `requirements.txt` from `pyproject.toml` when possible, and always includes `.env.example`. The real `.env` file and other secrets are never packed. Temporary build directories are deleted afterwards. + +### Upgrade, install, validate + +```bash +nitrostack-py upgrade # latest nitrostack on PyPI (writes nitrostack>=latest) +nitrostack-py upgrade --version 0.4.1 # pin exactly this version (writes nitrostack==0.4.1) +nitrostack-py upgrade --dry-run # print the change; do not edit files +nitrostack-py upgrade --allow-downgrade --version 0.1.0 # required to pin an older version + +nitrostack-py install # install project + development dependencies +nitrostack-py install --production # skip optional extras and requirements-dev.txt + +nitrostack-py validate # lint deps, @mcp_app imports, and @module() refs +``` + +`init` writes `pyproject.toml`, `.python-version`, and `uv.toml`, then runs `uv lock` when `uv` is on PATH. `install` prefers `uv sync` in that case. If `requirements.txt` pins nitrostack as a local path (`-e /path/to/nitrostack-python-sdk`), install uses `pip install -r requirements.txt` instead so unpublished SDK testing still works. The uv equivalent is: + +```toml +[tool.uv.sources] +nitrostack = { path = "/path/to/nitrostack-python-sdk", editable = true } +``` + +then `uv lock` / `uv sync`. Without `uv`, install falls back to `.venv` + `pip`. + +`upgrade` updates the `nitrostack` dependency spec in `pyproject.toml` in place (and `requirements.txt` when it already pins nitrostack). `--version X` writes `nitrostack==X`. Without `--version`, the latest PyPI release is written as `nitrostack>=latest`. A target older than the currently declared version is rejected unless `--allow-downgrade` is passed. `validate` reports missing/conflicting dependencies, `@mcp_app` modules that fail to import, and `@module()` `imports`/`exports` that are not real classes. + +--- + +## Widgets (UI tools) + +Bind an HTML template to a tool with `@widget` and return domain JSON from the handler: ```python from nitrostack import tool, widget, ExecutionContext -@tool(name="show_card", description="Product card", input_schema=CardInput) -@widget("card") -async def show_card(self, input: CardInput, context: ExecutionContext) -> dict: - return {"name": "Widget", "price": 9.99} +class ShopController: + @tool(name="show_card", description="Product card", input_schema=CardInput) + @widget("card") + async def show_card(self, input: CardInput, context: ExecutionContext) -> dict: + return {"name": "Widget", "price": 9.99} ``` Place HTML at `widgets/out/{route}.html` (e.g. `widgets/out/card.html`). The SDK registers @@ -325,6 +558,8 @@ from nitrostack import WidgetOptions, WidgetCsp, widget prefers_border=True, csp=WidgetCsp(connect_domains=["https://api.example.com"]), )) +async def show_chart(self, input, context): + ... ``` `nitrostack-py init` copies `widgets/out/{route}.html` for every `@widget`. Widget HTML @@ -334,7 +569,7 @@ MCP Inspector: use **HTTP + stateless**, then the **Apps** tab. `tools/call` als the data-filled HTML. Do not use `widgets/preview.html` as the live result — that file is a static helper. Live preview: `http://localhost:3000/widgets/preview`. -Turn **Authentication off** in Inspector. Pizzaz/starter have no OAuth. If Auth is on, +Turn **Authentication off** in Inspector for the starter and pizzaz templates (they have no OAuth). If Auth is on, Inspector POSTs `/register` and you will see `Cannot POST /register` / `Unexpected token '<'`. Connect Streamable HTTP to `http://localhost:3000/mcp` (no trailing slash). @@ -342,11 +577,6 @@ For **open pizza shops only**, call `show_pizza_list` with `{"openNow": true}` o `show_pizza_map` with `{"filter": "open_now"}`. Omitting those fields returns every shop, including closed ones (Pizzeria Delfina). -**NitroStudio:** folder-connect looks for a TypeScript project (`package.json` with -`@nitrostack/core` and `src/index.ts`). A Python server will not detect. Keep using -MCP Inspector over HTTP, or point Studio at a custom Streamable HTTP URL if the build -supports it. Do not enable OAuth against this server. - Example server: `examples/widgets_example.py` with templates in `examples/widgets/out/`. For MCP Inspector over HTTP, use stateless mode: @@ -355,24 +585,32 @@ cd examples MCP_TRANSPORT_TYPE=http MCP_STATELESS=true NITROSTACK_APP_MODE=universal python widgets_example.py ``` -### Running Tests -To run the automated test suite, execute: +--- + +## Using with Clients + +### NitroStudio + +Open the project folder in NitroStudio. It recognises a Python NitroStack project by `main.py` plus `nitrostack` in `requirements.txt` or `pyproject.toml`, starts it, and lets you call tools, preview widgets, chat with it, and run OAuth. Studio passes the port it picks through `PORT`, which wins over `.env` (0.4.1 and later), so several projects can run side by side. + +### Claude Desktop + ```bash -python tests/test_basic.py -python tests/test_tasks.py -python tests/test_initial_tool.py -python tests/test_transports.py -python tests/test_widgets.py -python tests/test_widget_metadata.py -python tests/test_pizzaz_widgets.py -python tests/test_template_widgets.py -python tests/test_cli.py -pytest tests/test_cli.py -v -python tests/test_tool_input_schema.py +nitrostack-py register --name my-mcp-server --file main.py ``` +*(If your scripts folder is not in PATH, use: `python -m nitrostack.cli.main register --name my-mcp-server --file main.py`)* + +This finds the Claude Desktop config (standard and Windows Store installs), points it at your virtualenv's Python, and writes the server entry. Restart Claude Desktop afterwards. + +--- + +## Testing + ### Testing Harness -Write in-process unit tests using the harness: + +Call tools, resources and prompts in-process with `NitroTestingModule`; no transport, no subprocess: + ```python import asyncio from nitrostack.testing import NitroTestingModule @@ -380,10 +618,18 @@ from app import AppModule async def test_add(): harness = await NitroTestingModule.create(AppModule) - result = await harness.call_tool("add", {"input": {"a": 5, "b": 10}}) - assert result == 15.0 - print("Test passed!") + assert await harness.call_tool("add", {"a": 5, "b": 10}) == 15.0 + assert await harness.read_resource("calc://info") == "Simple Add Calculator v1.0.0" if __name__ == "__main__": asyncio.run(test_add()) ``` + +`call_tool` takes the tool's arguments as an MCP client sends them and returns the decoded result (JSON is parsed; errors come back as their message). `get_prompt(name, args)` returns the prompt messages. + +### Running the SDK's tests + +```bash +pip install -e ".[dev]" +pytest tests +``` diff --git a/pyproject.toml b/pyproject.toml index 68ea96b..06867ee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,12 @@ dev = [ "tox>=4.0.0", ] +[project.urls] +Homepage = "https://nitrostack.ai/" +Documentation = "https://docs.nitrostack.ai/python" +Repository = "https://github.com/nitrocloudofficial/nitrostack-python-sdk" +Issues = "https://github.com/nitrocloudofficial/nitrostack-python-sdk/issues" + [project.scripts] nitrostack-py = "nitrostack.cli.main:main" diff --git a/tests/test_readme_examples.py b/tests/test_readme_examples.py new file mode 100644 index 0000000..0e004fd --- /dev/null +++ b/tests/test_readme_examples.py @@ -0,0 +1,148 @@ +"""README examples must stay true to the SDK: PyPI shows this README. + +Every ```python block must compile and import only names the SDK has. The +Quick Start and Building Blocks examples are also run through the testing +harness. +""" +from __future__ import annotations + +import asyncio +import importlib +import os +import re +import sys +import types + +import pytest + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +sys.path.insert(0, ROOT) + +from nitrostack import DIContainer, NitroTestingModule, module # noqa: E402 +from nitrostack.core.additional_decorators import HealthCheckRegistry # noqa: E402 +from nitrostack.events.event_emitter import EventEmitter # noqa: E402 + +README = open(os.path.join(ROOT, "README.md"), encoding="utf-8").read() +FENCE = re.compile(r"^```python\n(.*?)^```", re.S | re.M) + + +def _section(title: str) -> str: + match = re.search(rf"^## {re.escape(title)}\n(.*?)(?=^## |\Z)", README, re.S | re.M) + assert match, f"README has no '## {title}' section" + return match.group(1) + + +def _blocks(text: str): + return FENCE.findall(text) + + +@pytest.fixture(autouse=True) +def fresh_globals(): + DIContainer.reset() + EventEmitter.reset() + HealthCheckRegistry._bound_checks.clear() + yield + DIContainer.reset() + EventEmitter.reset() + HealthCheckRegistry._bound_checks.clear() + + +def test_every_python_block_compiles(): + blocks = _blocks(README) + assert len(blocks) >= 10 + for i, code in enumerate(blocks): + compile(code, f"README.md python block {i + 1}", "exec") + + +def test_every_nitrostack_import_exists(): + imports = re.compile(r"^from (nitrostack[\w.]*) import (\([^)]*\)|[^\n]*)", re.M) + checked = 0 + for code in _blocks(README): + for mod_name, names in imports.findall(code): + mod = importlib.import_module(mod_name) + for name in re.split(r"[,\s()]+", names): + if not name or name.startswith("#"): + continue + assert hasattr(mod, name), f"README imports {name!r} from {mod_name}, which doesn't have it" + checked += 1 + assert checked >= 30 + + +def test_quick_start_runs(): + code = _blocks(_section("Quick Start"))[0] + app = types.ModuleType("readme_quick_start_app") + exec(compile(code, "README quick start", "exec"), app.__dict__) + + async def run(): + harness = await NitroTestingModule.create(app.AppModule) + assert await harness.call_tool("add", {"a": 5, "b": 10}) == 15.0 + assert await harness.read_resource("calc://info") == "Simple Add Calculator v1.0.0" + + asyncio.run(run()) + + +def test_building_blocks_run(monkeypatch): + monkeypatch.setenv("WEATHER_API_KEY", "test") + monkeypatch.setenv("API_KEY", "secret") + monkeypatch.delenv("OAUTH_REQUIRED", raising=False) + + # The section's blocks build on each other; keep every controller and + # service each block defines (several reuse the name WeatherController). + namespace: dict = {"__name__": "readme_building_blocks"} + controllers, providers = [], [] + for i, code in enumerate(_blocks(_section("Building Blocks"))): + before = dict(namespace) + exec(compile(code, f"README building block {i + 1}", "exec"), namespace) + for name, value in namespace.items(): + if not isinstance(value, type) or before.get(name) is value: + continue + if name.endswith("Controller"): + controllers.append(value) + elif name in ("WeatherService", "OrderService", "AuditLog"): + providers.append(value) + + @module(name="app", imports=[namespace["ApiKeyModule"].for_root()], controllers=controllers, providers=providers) + class AppModule: + pass + + async def run(): + h = await NitroTestingModule.create(AppModule) + assert await h.call_tool("get_weather", {"city": "Paris"}) == {"city": "Paris", "temp": 21, "units": "metric"} + assert await h.call_tool("whats_new", {}) == "Try get_weather." + assert await h.read_resource("weather://units") == "metric" + messages = await h.get_prompt("forecast_brief", {"city": "Oslo"}) + assert "Oslo" in str(messages) + + assert await h.call_tool("get_forecast", {"city": "Rome"}) == {"city": "Rome", "forecast": "sunny"} + assert "Access denied" in str(await h.call_tool("get_balance", {})) + assert "Not authenticated" in str(await h.call_tool("close_account", {})) + + assert [await h.call_tool("ping", {}) for _ in range(10)] == ["pong"] * 10 + assert "Rate limit exceeded" in str(await h.call_tool("ping", {})) + + service = DIContainer.get_instance().resolve(namespace["WeatherService"]) + assert await service.lookup("Paris") is await service.lookup("Paris") + + assert await h.call_tool("build_report", {"steps": 1}) == {"steps": 1} + + await DIContainer.get_instance().resolve(namespace["OrderService"]).place("A1") + assert DIContainer.get_instance().resolve(namespace["AuditLog"]).entries == ["A1"] + assert await h.read_resource("health://status") == {"audit": "healthy"} + + asyncio.run(run()) + + +def test_config_service_example(tmp_path, monkeypatch): + code = _blocks(_section("Quick Start"))[1] + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("WEATHER_API_KEY", "k") + monkeypatch.delenv("WEATHER_UNITS", raising=False) + namespace: dict = {"__name__": "readme_config"} + exec(compile(code, "README config example", "exec"), namespace) + + async def run(): + await NitroTestingModule.create(namespace["AppModule"]) + service = DIContainer.get_instance().resolve(namespace["WeatherService"]) + assert (service.units, service.api_key) == ("metric", "k") + + asyncio.run(run()) From e987335451b4fbf7edf36a243c1ffc044a34a32b Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Fri, 16 Oct 2026 06:18:47 +0530 Subject: [PATCH 07/34] docs: don't present upgrade as the way to refresh the vendored SDK Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 66b02cd..daca9bf 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ nitrostack-py dev --port 4000 --widget 4001 nitrostack-py start --port 4000 --widget 4001 ``` -`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies`; that breaks the cloud wheel metadata. Because the SDK is vendored, `nitrostack-py upgrade` (below) is how an existing project picks up a new SDK release. +`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies`; that breaks the cloud wheel metadata. The project runs that vendored copy, whatever the version spec says. Once scaffolded, follow the next steps the CLI prints. From f29cff07aadb15d0ab47e6f4e5aa31e64bb6259f Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Fri, 16 Oct 2026 06:55:28 +0530 Subject: [PATCH 08/34] Fix upgrade on vendored projects; correct init's NitroStudio note `nitrostack-py upgrade` failed on every project `init` creates: the dependency pattern also matched `nitrostack = { path = "vendor/nitrostack" }` in [tool.uv.sources] and produced an invalid pyproject.toml. Spec rewrites are now limited to [project].dependencies, and the pattern skips paths ending in /nitrostack. Fixing that alone isn't enough: a vendored project runs vendor/nitrostack whatever spec it declares, and uv accepts a spec the vendored copy doesn't satisfy. For vendored projects, upgrade now replaces vendor/nitrostack with the target release (copied from the running CLI when it is that release, otherwise the PyPI wheel, checked against its sha256). The new tree is built beside the old one and swapped in, so a failed download leaves the project as it was. init's next steps said NitroStudio can't open Python projects; it can. The pizzaz open-shops hint is printed only for the pizzaz template. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- nitrostack/cli/main.py | 6 +- nitrostack/cli/upgrade.py | 155 ++++++++++++++++++- nitrostack/cli/vendor.py | 130 ++++++++++++++-- tests/test_cli_upgrade_vendored.py | 234 +++++++++++++++++++++++++++++ 5 files changed, 508 insertions(+), 25 deletions(-) create mode 100644 tests/test_cli_upgrade_vendored.py diff --git a/README.md b/README.md index daca9bf..ff05e8d 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ nitrostack-py dev --port 4000 --widget 4001 nitrostack-py start --port 4000 --widget 4001 ``` -`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies`; that breaks the cloud wheel metadata. The project runs that vendored copy, whatever the version spec says. +`init` and `pack` vendor this SDK into `vendor/nitrostack` and pin it with `[tool.uv.sources]`. The dependency name stays `nitrostack` in `pyproject.toml` and `requirements.txt`, so `nitrostack-py install` and NitroCloud still run `uv sync`. Do not put a `file:` URL in `[project].dependencies`; that breaks the cloud wheel metadata. The project runs that vendored copy, whatever the version spec says; `nitrostack-py upgrade` replaces it with another release. Once scaffolded, follow the next steps the CLI prints. @@ -498,8 +498,8 @@ nitrostack-py pack # write dist/*.whl ### Upgrade, install, validate ```bash -nitrostack-py upgrade # latest nitrostack on PyPI (writes nitrostack>=latest) -nitrostack-py upgrade --version 0.4.1 # pin exactly this version (writes nitrostack==0.4.1) +nitrostack-py upgrade # move the project to the latest nitrostack on PyPI +nitrostack-py upgrade --version 0.4.1 # move it to exactly this version nitrostack-py upgrade --dry-run # print the change; do not edit files nitrostack-py upgrade --allow-downgrade --version 0.1.0 # required to pin an older version @@ -518,7 +518,7 @@ nitrostack = { path = "/path/to/nitrostack-python-sdk", editable = true } then `uv lock` / `uv sync`. Without `uv`, install falls back to `.venv` + `pip`. -`upgrade` updates the `nitrostack` dependency spec in `pyproject.toml` in place (and `requirements.txt` when it already pins nitrostack). `--version X` writes `nitrostack==X`. Without `--version`, the latest PyPI release is written as `nitrostack>=latest`. A target older than the currently declared version is rejected unless `--allow-downgrade` is passed. `validate` reports missing/conflicting dependencies, `@mcp_app` modules that fail to import, and `@module()` `imports`/`exports` that are not real classes. +`upgrade` in a project with `vendor/nitrostack` (every project `init` creates) replaces the vendored copy with the target release: the wheel is downloaded from PyPI and checked against its published sha256, or copied from the running CLI when it is that release. The dependency stays the plain name `nitrostack`. In other projects, `upgrade` updates the `nitrostack` spec in `pyproject.toml`'s `dependencies` (and `requirements.txt` when it already pins nitrostack): `--version X` writes `nitrostack==X`, and without `--version` the latest release is written as `nitrostack>=latest`. Either way, run `nitrostack-py install` afterwards, and a target older than the current version is rejected unless `--allow-downgrade` is passed. `validate` reports missing/conflicting dependencies, `@mcp_app` modules that fail to import, and `@module()` `imports`/`exports` that are not real classes. --- diff --git a/nitrostack/cli/main.py b/nitrostack/cli/main.py index 1ab03b3..6e5553c 100644 --- a/nitrostack/cli/main.py +++ b/nitrostack/cli/main.py @@ -1409,9 +1409,9 @@ def init_project(name: str = None, template: str = None, skip_install: bool = Fa 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.") + if template == "python-pizzaz": + print(" For open shops only set \033[34mopenNow=true\033[0m (list) or \033[34mfilter=open_now\033[0m (map)") + print(" 6. NitroStudio: open this folder as a project; Studio starts and connects it.") print("\nHappy coding! 🚀\n") def run_dev(port=None, widget=None): diff --git a/nitrostack/cli/upgrade.py b/nitrostack/cli/upgrade.py index 12a312a..64e600a 100644 --- a/nitrostack/cli/upgrade.py +++ b/nitrostack/cli/upgrade.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json import os import re @@ -19,13 +20,20 @@ write_text_atomic, ) from nitrostack.cli.skills import upgrade_agent_skills +from nitrostack.cli.vendor import ( + VENDOR_REL, + _distribution_version, + replace_vendored_nitrostack, + vendored_version, +) PYPI_JSON = "https://pypi.org/pypi/nitrostack/json" PYPI_VERSION_JSON = "https://pypi.org/pypi/nitrostack/{version}/json" -# Name must not be a prefix of nitrostack-studio / nitrostack_extras / nitrostack.contrib. +# Name must not be a prefix of nitrostack-studio / nitrostack_extras / nitrostack.contrib, +# nor the tail of a path such as ./vendor/nitrostack. _DEP_RE = re.compile( - r'(["\']?)(nitrostack)(?![\w.-])((?:\s*(?:===|==|!=|~=|>=|<=|>|<)\s*[^"\'\s,#]+)?)(\1)', + r'(?=|<=|>|<)\s*[^"\'\s,#]+)?)(\1)', re.IGNORECASE, ) @@ -75,6 +83,63 @@ def verify_nitrostack_version(version: str, timeout: float = 15.0) -> None: raise UpgradeError(f"Could not reach PyPI to verify nitrostack=={version}: {exc}") from exc +def fetch_nitrostack_wheel(version: str, timeout: float = 60.0) -> bytes: + """Download the nitrostack wheel for ``version`` from PyPI and check its sha256.""" + req = urllib.request.Request( + PYPI_VERSION_JSON.format(version=version), + headers={"Accept": "application/json", "User-Agent": "nitrostack-py"}, + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + payload = json.loads(resp.read().decode("utf-8")) + wheels = [ + f for f in payload.get("urls") or [] + if f.get("packagetype") == "bdist_wheel" + and str(f.get("filename", "")).endswith("-none-any.whl") + ] + if not wheels: + raise UpgradeError(f"PyPI has no wheel for nitrostack=={version}.") + wheel = wheels[0] + expected = (wheel.get("digests") or {}).get("sha256") + if not expected: + raise UpgradeError( + f"PyPI lists no sha256 for {wheel.get('filename')}; not installing it." + ) + download = urllib.request.Request(wheel["url"], headers={"User-Agent": "nitrostack-py"}) + with urllib.request.urlopen(download, timeout=timeout) as resp: + data = resp.read() + except urllib.error.HTTPError as exc: + if exc.code == 404: + raise UpgradeError(f"nitrostack=={version} was not found on PyPI.") from exc + raise UpgradeError(f"Downloading nitrostack=={version} failed: {exc}") from exc + except urllib.error.URLError as exc: + raise UpgradeError( + f"Could not reach PyPI to download nitrostack=={version}: {exc}" + ) from exc + except json.JSONDecodeError as exc: + raise UpgradeError(f"PyPI returned invalid JSON: {exc}") from exc + if hashlib.sha256(data).hexdigest() != expected: + raise UpgradeError(f"{wheel.get('filename')} failed its sha256 check; not installing it.") + return data + + +def _pyproject_dependencies(text: str) -> Tuple[int, int]: + """Span of `[project].dependencies`, or (0, 0). Specs elsewhere (e.g. a + `[tool.uv.sources]` entry named nitrostack) must not be rewritten.""" + return find_toml_array_inner(text, "dependencies") or (0, 0) + + +def _find_pyproject_spec(text: str) -> Optional[str]: + start, end = _pyproject_dependencies(text) + return find_current_spec(text[start:end]) + + +def _replace_pyproject_spec(text: str, spec: str) -> Tuple[str, int]: + start, end = _pyproject_dependencies(text) + inner, count = replace_nitrostack_spec(text[start:end], spec) + return text[:start] + inner + text[end:], count + + def find_current_spec(text: str) -> Optional[str]: match = _DEP_RE.search(text) if not match: @@ -145,6 +210,68 @@ def _commit_file_changes(changes: list) -> list: raise +def _upgrade_vendored( + root: str, + current: str, + *, + version: Optional[str], + dry_run: bool, + verify: bool, + allow_downgrade: bool, +) -> dict: + """Replace `vendor/nitrostack` with the target release. + + `init` vendors the SDK and points uv at it with `[tool.uv.sources]`, so the + project runs that copy whatever version spec it declares. The dependency + stays the plain name `nitrostack` (see `vendor.py`). + """ + target = version or fetch_latest_nitrostack_version() + if version and verify: + verify_nitrostack_version(target) + try: + target_ver = Version(target) + except InvalidVersion as exc: + raise UpgradeError(f"Invalid target version '{target}': {exc}") from exc + try: + current_ver: Optional[Version] = Version(current) + except InvalidVersion: + current_ver = None + if not allow_downgrade and current_ver is not None and target_ver < current_ver: + raise UpgradeError( + f"Target {target} is older than the vendored nitrostack {current}. " + "Re-run with --allow-downgrade if you intend to downgrade." + ) + + vendor_dir = VENDOR_REL.replace(os.sep, "/") + change = {"file": vendor_dir, "from": current, "to": target} + up_to_date = current_ver == target_ver + print("NITROSTACK — Upgrade" + (" (dry run)" if dry_run else "")) + print(f"Target version: {target}") + print(f" {vendor_dir}: {current} → {target}" + (" (already installed)" if up_to_date else "")) + + written: list = [] + if dry_run: + print("\nDry run — no files modified.") + elif not up_to_date: + # The running CLI is the target release: copy it rather than download it. + wheel = None if _distribution_version() == target else fetch_nitrostack_wheel(target) + replace_vendored_nitrostack(root, wheel) + written = [vendor_dir] + print(f"Updated {vendor_dir}") + print(f"\nUpgrade complete. The project now runs nitrostack {target}.") + print("Run `nitrostack-py install` to install it.") + + skills = upgrade_agent_skills(root, dry_run=dry_run) + return { + "version": target, + "spec": "nitrostack", + "changes": [] if up_to_date else [change], + "dry_run": dry_run, + "written": written, + "skills": skills, + } + + def upgrade_project( root: Optional[str] = None, *, @@ -153,7 +280,12 @@ def upgrade_project( verify: bool = True, allow_downgrade: bool = False, ) -> dict: - """Update the nitrostack dependency spec in pyproject.toml (and requirements.txt if present).""" + """Move the project to another nitrostack release. + + Vendored projects (`vendor/nitrostack`, as `init` creates) get the vendored copy + replaced. Others get the dependency spec in pyproject.toml (and requirements.txt + if present) rewritten. + """ root = os.path.abspath(root or os.getcwd()) pyproject = os.path.join(root, "pyproject.toml") requirements = os.path.join(root, "requirements.txt") @@ -164,6 +296,17 @@ def upgrade_project( "Run this command from a NitroStack project, or create pyproject.toml first." ) + vendored = vendored_version(root) + if vendored is not None: + return _upgrade_vendored( + root, + vendored, + version=version, + dry_run=dry_run, + verify=verify, + allow_downgrade=allow_downgrade, + ) + target = version or fetch_latest_nitrostack_version() if version and verify: verify_nitrostack_version(target) @@ -175,7 +318,7 @@ def upgrade_project( current_specs = [] if original_pyproject is not None: - current_specs.append(find_current_spec(original_pyproject)) + current_specs.append(_find_pyproject_spec(original_pyproject)) if original_reqs is not None: current_specs.append(find_current_spec(original_reqs)) @@ -194,8 +337,8 @@ def upgrade_project( ) if original_pyproject is not None: - current = find_current_spec(original_pyproject) - updated, n = replace_nitrostack_spec(original_pyproject, new_spec) + current = _find_pyproject_spec(original_pyproject) + updated, n = _replace_pyproject_spec(original_pyproject, new_spec) if n == 0: updated = _add_to_pyproject_dependencies(original_pyproject, new_spec) current = current or "(missing)" diff --git a/nitrostack/cli/vendor.py b/nitrostack/cli/vendor.py index af35dd7..08abbea 100644 --- a/nitrostack/cli/vendor.py +++ b/nitrostack/cli/vendor.py @@ -8,13 +8,18 @@ """ from __future__ import annotations +import email.parser +import io +import json import os import re import shutil +import tempfile +import zipfile from pathlib import Path -from typing import Optional +from typing import List, Optional -from nitrostack.cli._shared import write_text_atomic +from nitrostack.cli._shared import loads_toml, write_text_atomic VENDOR_REL = os.path.join("vendor", "nitrostack") _PLAIN_REQUIREMENT = "nitrostack" @@ -87,8 +92,25 @@ def _distribution_version() -> str: ) -def _write_minimal_pyproject(dest: Path) -> None: - version = _distribution_version() +_DEFAULT_DEPENDENCIES = ( + "mcp>=2,<3", + "pydantic>=2.0.0", + "starlette>=0.30.0", + "uvicorn>=0.20.0", + "watchfiles>=0.18.0", + "anyio>=4.0.0", + "packaging>=23.0.0", + "tomli>=2.0.0; python_version < '3.11'", +) + + +def _write_minimal_pyproject( + dest: Path, + version: Optional[str] = None, + dependencies: Optional[List[str]] = None, +) -> None: + version = version or _distribution_version() + deps = "".join(f" {json.dumps(dep)},\n" for dep in (dependencies or _DEFAULT_DEPENDENCIES)) dest.mkdir(parents=True, exist_ok=True) (dest / "pyproject.toml").write_text( "[build-system]\n" @@ -100,14 +122,7 @@ def _write_minimal_pyproject(dest: Path) -> None: 'description = "NitroStack Python SDK (vendored)"\n' 'requires-python = ">=3.10"\n' "dependencies = [\n" - ' "mcp>=2,<3",\n' - ' "pydantic>=2.0.0",\n' - ' "starlette>=0.30.0",\n' - ' "uvicorn>=0.20.0",\n' - ' "watchfiles>=0.18.0",\n' - ' "anyio>=4.0.0",\n' - ' "packaging>=23.0.0",\n' - ' "tomli>=2.0.0; python_version < \'3.11\'",\n' + f"{deps}" "]\n\n" "[project.scripts]\n" 'nitrostack-py = "nitrostack.cli.main:main"\n\n' @@ -142,6 +157,10 @@ def copy_running_nitrostack(dest: Path) -> None: else: _write_minimal_pyproject(dest) + _check_vendored_tree(dest) + + +def _check_vendored_tree(dest: Path) -> None: assets = dest / "nitrostack" / "transports" / "assets" / "landing.html" if not assets.is_file(): raise RuntimeError( @@ -150,6 +169,93 @@ def copy_running_nitrostack(dest: Path) -> None: ) +def extract_nitrostack_wheel(wheel: bytes, dest: Path) -> str: + """Unpack a nitrostack wheel into ``dest`` as a vendored tree; return its version. + + Skips the same directories as `copy_running_nitrostack` (templates, caches). + """ + with zipfile.ZipFile(io.BytesIO(wheel)) as archive: + metadata_name = next( + ( + n for n in archive.namelist() + if re.fullmatch(r"nitrostack-[^/]+\.dist-info/METADATA", n) + ), + None, + ) + if metadata_name is None: + raise RuntimeError("The downloaded file is not a nitrostack wheel (no METADATA).") + metadata = email.parser.Parser().parsestr(archive.read(metadata_name).decode("utf-8")) + version = metadata.get("Version") + if not version: + raise RuntimeError("The nitrostack wheel has no version in its METADATA.") + requires = [ + req for req in metadata.get_all("Requires-Dist") or [] + if not re.search(r"\bextra\s*==", req) + ] + + root = dest.resolve() + for name in archive.namelist(): + parts = name.split("/") + if parts[0] != "nitrostack" or name.endswith("/"): + continue + if any(part in _SKIP_DIR_NAMES or part.endswith(".egg-info") for part in parts[:-1]): + continue + target = (dest / name).resolve() + if root not in target.parents: + raise RuntimeError(f"Refusing to extract {name!r} outside {dest}.") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(archive.read(name)) + + _write_minimal_pyproject(dest, version=version, dependencies=requires) + _check_vendored_tree(dest) + return version + + +def vendored_version(project: str) -> Optional[str]: + """Version of the SDK in ``project/vendor/nitrostack``, or None if not vendored.""" + pyproject = Path(project) / VENDOR_REL / "pyproject.toml" + if not pyproject.is_file(): + return None + try: + data = loads_toml(pyproject.read_text(encoding="utf-8")) + version = data.get("project", {}).get("version") + except Exception: + return None + return str(version) if version else None + + +def replace_vendored_nitrostack(project: str, wheel: Optional[bytes] = None) -> str: + """Swap ``vendor/nitrostack`` for the running SDK, or for ``wheel`` when given. + + The new tree is built next to the old one and swapped in afterwards, so a + failed download or extraction leaves the project's current SDK in place. + Returns the vendored version. + """ + dest = Path(os.path.abspath(project)) / VENDOR_REL + dest.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix=".nitrostack-new-", dir=dest.parent)) + backup = dest.parent / f".nitrostack-old-{os.getpid()}" + try: + if wheel is None: + copy_running_nitrostack(staging) + version = _distribution_version() + else: + version = extract_nitrostack_wheel(wheel, staging) + if dest.exists(): + os.replace(dest, backup) + try: + os.replace(staging, dest) + except OSError: + if backup.exists(): + os.replace(backup, dest) + raise + finally: + shutil.rmtree(staging, ignore_errors=True) + shutil.rmtree(backup, ignore_errors=True) + pin_project_to_vendor(Path(os.path.abspath(project))) + return version + + def _pin_text(text: str) -> str: """Keep `[project].dependencies` as a plain name (valid wheel Requires-Dist).""" return _QUOTED_NITROSTACK.sub(lambda match: f"{match.group(1)}nitrostack{match.group(1)}", text) diff --git a/tests/test_cli_upgrade_vendored.py b/tests/test_cli_upgrade_vendored.py new file mode 100644 index 0000000..8cc09c8 --- /dev/null +++ b/tests/test_cli_upgrade_vendored.py @@ -0,0 +1,234 @@ +"""`nitrostack-py upgrade` on projects shaped like `init` creates them. + +`init` vendors the SDK into vendor/nitrostack and points uv at it with a +`[tool.uv.sources]` entry, so upgrade must replace that copy and must not +touch the source entry. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import zipfile +from pathlib import Path +from unittest.mock import patch + +import pytest + +from nitrostack.cli import vendor +from nitrostack.cli._shared import loads_toml +from nitrostack.cli.upgrade import ( + UpgradeError, + fetch_nitrostack_wheel, + replace_nitrostack_spec, + upgrade_project, +) +from nitrostack.cli.vendor import ( + ensure_vendored_nitrostack, + extract_nitrostack_wheel, + vendored_version, +) + +INIT_PYPROJECT = ( + "[project]\n" + 'name = "demo"\n' + 'version = "0.1.0"\n' + 'requires-python = ">=3.10"\n' + "dependencies = [\n" + ' "nitrostack",\n' + "]\n\n" + "[tool.uv.sources]\n" + 'nitrostack = { path = "vendor/nitrostack" }\n' +) + + +def _wheel(version: str, extra_files: dict | None = None) -> bytes: + files = { + "nitrostack/__init__.py": f"VERSION = {version!r}\n", + "nitrostack/transports/assets/landing.html": "", + "nitrostack/templates/starter/main.py": "print('template')\n", + f"nitrostack-{version}.dist-info/METADATA": ( + "Metadata-Version: 2.1\n" + "Name: nitrostack\n" + f"Version: {version}\n" + "Requires-Dist: mcp<3,>=2\n" + "Requires-Dist: pydantic>=2.0.0\n" + 'Requires-Dist: tomli>=2.0.0; python_version < "3.11"\n' + 'Requires-Dist: pytest>=7.4.0; extra == "dev"\n' + ), + } + files.update(extra_files or {}) + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + for name, content in files.items(): + archive.writestr(name, content) + return buffer.getvalue() + + +@pytest.fixture +def no_skills(): + with patch( + "nitrostack.cli.upgrade.upgrade_agent_skills", return_value={"skipped": True} + ) as mock: + yield mock + + +@pytest.fixture +def project(tmp_path: Path) -> Path: + (tmp_path / "pyproject.toml").write_text(INIT_PYPROJECT, encoding="utf-8") + (tmp_path / "requirements.txt").write_text("nitrostack\n", encoding="utf-8") + assert ensure_vendored_nitrostack(str(tmp_path), quiet=True) + return tmp_path + + +def test_spec_rewrite_skips_the_uv_source_entry(tmp_path: Path, no_skills): + # Not vendored, but the pyproject still names nitrostack in [tool.uv.sources]. + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text(INIT_PYPROJECT, encoding="utf-8") + with patch("nitrostack.cli.upgrade.verify_nitrostack_version"): + upgrade_project(str(tmp_path), version="1.2.3", verify=False, allow_downgrade=True) + parsed = loads_toml(pyproject.read_text(encoding="utf-8")) + assert parsed["project"]["dependencies"] == ["nitrostack==1.2.3"] + assert parsed["tool"]["uv"]["sources"]["nitrostack"] == {"path": "vendor/nitrostack"} + + +def test_spec_rewrite_skips_vendor_paths(): + text = "-e ./vendor/nitrostack\nnitrostack>=0.3.0\n" + updated, count = replace_nitrostack_spec(text, "nitrostack>=9.9.9") + assert count == 1 + assert updated == "-e ./vendor/nitrostack\nnitrostack>=9.9.9\n" + + +def test_upgrade_replaces_the_vendored_sdk_from_the_wheel(project: Path, no_skills): + pyproject_before = (project / "pyproject.toml").read_text(encoding="utf-8") + with ( + patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value="9.9.9"), + patch( + "nitrostack.cli.upgrade.fetch_nitrostack_wheel", return_value=_wheel("9.9.9") + ) as fetch, + ): + result = upgrade_project(str(project)) + + fetch.assert_called_once_with("9.9.9") + assert result["written"] == ["vendor/nitrostack"] + assert result["changes"][0]["to"] == "9.9.9" + assert vendored_version(str(project)) == "9.9.9" + sdk = project / "vendor" / "nitrostack" + assert (sdk / "nitrostack" / "__init__.py").read_text(encoding="utf-8") == "VERSION = '9.9.9'\n" + assert not (sdk / "nitrostack" / "templates").exists() + deps = loads_toml((sdk / "pyproject.toml").read_text(encoding="utf-8"))["project"][ + "dependencies" + ] + assert deps == ["mcp<3,>=2", "pydantic>=2.0.0", 'tomli>=2.0.0; python_version < "3.11"'] + # The project keeps the plain name; the vendored copy decides the version. + assert (project / "pyproject.toml").read_text(encoding="utf-8") == pyproject_before + assert (project / "requirements.txt").read_text(encoding="utf-8") == "nitrostack\n" + assert not [p for p in (project / "vendor").iterdir() if p.name.startswith(".nitrostack-")] + + +def test_upgrade_to_the_running_version_copies_it(project: Path, no_skills): + running = vendor._distribution_version() + (project / "vendor" / "nitrostack" / "pyproject.toml").write_text( + '[project]\nname = "nitrostack"\nversion = "0.0.1"\n', encoding="utf-8" + ) + with ( + patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value=running), + patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel") as fetch, + ): + upgrade_project(str(project)) + fetch.assert_not_called() + assert vendored_version(str(project)) == running + + +def test_upgrade_vendored_dry_run_same_version_and_downgrade(project: Path, no_skills): + current = vendored_version(str(project)) + snapshot = sorted(p.relative_to(project) for p in project.rglob("*")) + + with ( + patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value="9.9.9"), + patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel") as fetch, + ): + dry = upgrade_project(str(project), dry_run=True) + fetch.assert_not_called() + assert dry["changes"] == [{"file": "vendor/nitrostack", "from": current, "to": "9.9.9"}] + assert dry["written"] == [] + + with ( + patch("nitrostack.cli.upgrade.verify_nitrostack_version"), + patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel") as fetch, + ): + same = upgrade_project(str(project), version=current) + with pytest.raises(UpgradeError, match="allow-downgrade"): + upgrade_project(str(project), version="0.0.1") + fetch.assert_not_called() + assert same["changes"] == [] and same["written"] == [] + assert sorted(p.relative_to(project) for p in project.rglob("*")) == snapshot + + +def test_failed_download_or_bad_wheel_keeps_the_current_sdk(project: Path, no_skills): + current = vendored_version(str(project)) + with patch("nitrostack.cli.upgrade.fetch_latest_nitrostack_version", return_value="9.9.9"): + with patch( + "nitrostack.cli.upgrade.fetch_nitrostack_wheel", side_effect=UpgradeError("offline") + ): + with pytest.raises(UpgradeError, match="offline"): + upgrade_project(str(project)) + with patch("nitrostack.cli.upgrade.fetch_nitrostack_wheel", return_value=b"not a zip"): + with pytest.raises(zipfile.BadZipFile): + upgrade_project(str(project)) + assert vendored_version(str(project)) == current + assert ( + project / "vendor" / "nitrostack" / "nitrostack" / "transports" / "assets" / "landing.html" + ).is_file() + assert not [p for p in (project / "vendor").iterdir() if p.name.startswith(".nitrostack-")] + + +def test_extract_refuses_paths_outside_the_vendor_dir(tmp_path: Path): + evil = _wheel("9.9.9", {"nitrostack/../../escaped.py": "boom"}) + with pytest.raises(RuntimeError, match="outside"): + extract_nitrostack_wheel(evil, tmp_path / "sdk") + assert not (tmp_path / "escaped.py").exists() + + +class _Response(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def _pypi(wheel: bytes, digest: str): + payload = { + "urls": [ + { + "packagetype": "sdist", + "filename": "nitrostack-9.9.9.tar.gz", + "url": "https://x/sdist", + "digests": {}, + }, + { + "packagetype": "bdist_wheel", + "filename": "nitrostack-9.9.9-py3-none-any.whl", + "url": "https://x/wheel", + "digests": {"sha256": digest}, + }, + ] + } + + def urlopen(request, timeout=None): + url = request.full_url + return _Response(json.dumps(payload).encode() if url.endswith("/json") else wheel) + + return urlopen + + +def test_fetch_wheel_checks_sha256(): + wheel = _wheel("9.9.9") + good = hashlib.sha256(wheel).hexdigest() + with patch("urllib.request.urlopen", side_effect=_pypi(wheel, good)): + assert fetch_nitrostack_wheel("9.9.9") == wheel + with patch("urllib.request.urlopen", side_effect=_pypi(wheel, "0" * 64)): + with pytest.raises(UpgradeError, match="sha256"): + fetch_nitrostack_wheel("9.9.9") From 8b014eb89b96bed8e43539f2cd89959dcce26308 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:45:33 +0000 Subject: [PATCH 09/34] chore(release): 0.4.2 --- pyproject.toml | 2 +- uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 06867ee..59850ac 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nitrostack" -version = "0.4.1" +version = "0.4.2" description = "NitroStack Python SDK — A Python-idiomatic port of the NitroStack MCP framework" readme = "README.md" requires-python = ">=3.10" diff --git a/uv.lock b/uv.lock index bab7717..b4eb511 100644 --- a/uv.lock +++ b/uv.lock @@ -568,7 +568,7 @@ wheels = [ [[package]] name = "nitrostack" -version = "0.4.1" +version = "0.4.2" source = { editable = "." } dependencies = [ { name = "anyio" }, From b96606b5d84168ff073aba5969664d63e9c0bbaf Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Fri, 16 Oct 2026 12:05:02 +0530 Subject: [PATCH 10/34] validate: skip the vendored SDK `init` vendors the SDK into vendor/nitrostack. `validate` walked it as project code, and nitrostack/testing applies @mcp_app to a class defined inside a function, so every vendored project that imported nitrostack.testing failed with "uses @mcp_app but no decorated application class was found after import". Compose's typecheck runs `validate`, so a NitroStudio build could not get past it. Co-Authored-By: Claude Opus 5.5 --- nitrostack/cli/validators.py | 5 +++++ tests/test_cli.py | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/nitrostack/cli/validators.py b/nitrostack/cli/validators.py index 990b154..3015aa4 100644 --- a/nitrostack/cli/validators.py +++ b/nitrostack/cli/validators.py @@ -21,6 +21,7 @@ read_text, split_requirement, ) +from nitrostack.cli.vendor import VENDOR_REL @dataclass @@ -39,10 +40,14 @@ def format(self) -> str: def _iter_python_files(root: str) -> Iterable[str]: + # The vendored SDK is not project code; its testing helpers apply @mcp_app + # inside functions, which reads as an app with no decorated class. + vendored_sdk = os.path.join(os.path.abspath(root), VENDOR_REL) for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [ d for d in dirnames if d not in EXCLUDE_DIR_NAMES and not d.endswith(".egg-info") + and os.path.join(os.path.abspath(dirpath), d) != vendored_sdk ] for filename in filenames: if filename.endswith(".py"): diff --git a/tests/test_cli.py b/tests/test_cli.py index 2aaf2ed..95046d9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1154,6 +1154,33 @@ def test_validate_catches_broken_imports_and_module_refs(tmp_path: Path): assert "→" in messages or "Fix the import" in messages +def test_validate_skips_the_vendored_sdk(tmp_path: Path): + """`init` vendors the SDK; its testing helpers apply @mcp_app inside functions.""" + (tmp_path / "pyproject.toml").write_text( + "[project]\n" + 'name = "vendored"\n' + 'version = "0.1.0"\n' + "dependencies = [\n" + ' "nitrostack",\n' + "]\n", + encoding="utf-8", + ) + sdk = tmp_path / "vendor" / "nitrostack" / "nitrostack" / "testing" + sdk.mkdir(parents=True) + (sdk / "__init__.py").write_text( + "from nitrostack import mcp_app, ServerConfig\n\n" + "def create(module):\n" + " @mcp_app(module=module, server=ServerConfig(name='test'))\n" + " class TestApp:\n" + " pass\n" + " return TestApp\n", + encoding="utf-8", + ) + + issues = validate_project(str(tmp_path)) + assert not [issue for issue in issues if "vendor" in issue.path], [i.format() for i in issues] + + def test_validate_accepts_module_only_bootstrap(tmp_path: Path): """Init templates use @module + McpApplicationFactory.create — no @mcp_app.""" (tmp_path / "pyproject.toml").write_text( From 76f5bde56ebee887cffb752acc21d00d4f1c5770 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Fri, 16 Oct 2026 12:59:32 +0530 Subject: [PATCH 11/34] pack: add --include-env Align Python pack with the TypeScript CLI: optional inclusion of .env files in the wheel, with a warning that lists paths without printing values. --- README.md | 3 ++- nitrostack/cli/main.py | 9 +++++-- nitrostack/cli/pack.py | 60 +++++++++++++++++++++++++++++++++--------- tests/test_cli.py | 32 ++++++++++++++++++++++ 4 files changed, 88 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index ff05e8d..0f55682 100644 --- a/README.md +++ b/README.md @@ -491,9 +491,10 @@ Attach generated pipeline classes with `@use_guards`, `@use_pipes`, `@use_interc ```bash nitrostack-py pack --dry-run # list files; does not write an artifact nitrostack-py pack # write dist/*.whl +nitrostack-py pack --include-env # also pack .env files (use with caution!) ``` -`pack` builds a wheel with setuptools (the same backend as this SDK), refreshes `requirements.txt` from `pyproject.toml` when possible, and always includes `.env.example`. The real `.env` file and other secrets are never packed. Temporary build directories are deleted afterwards. +`pack` builds a wheel with setuptools (the same backend as this SDK), refreshes `requirements.txt` from `pyproject.toml` when possible, and always includes `.env.example`. `.env`, `.env.local`, and `.env.production` are excluded unless you pass `--include-env`. Temporary build directories are deleted afterwards. ### Upgrade, install, validate diff --git a/nitrostack/cli/main.py b/nitrostack/cli/main.py index 6e5553c..e570c03 100644 --- a/nitrostack/cli/main.py +++ b/nitrostack/cli/main.py @@ -1795,13 +1795,18 @@ def main(): # pack command pack_parser = subparsers.add_parser( "pack", - help="Build a deployable wheel of the current project (never includes .env/secrets)", + help="Build a deployable wheel of the current project (excludes .env by default)", ) pack_parser.add_argument( "--dry-run", action="store_true", help="Show files that would be packed without creating the artifact", ) + pack_parser.add_argument( + "--include-env", + action="store_true", + help="Include .env files in the wheel (use with caution!)", + ) # upgrade command upgrade_parser = subparsers.add_parser( @@ -1881,7 +1886,7 @@ def _run_command(fn, *fn_args, **fn_kwargs): else: generate_component(args.generator, args.name) elif args.command == "pack": - _run_command(pack_project, dry_run=args.dry_run) + _run_command(pack_project, dry_run=args.dry_run, include_env=args.include_env) elif args.command == "upgrade": _run_command( upgrade_project, diff --git a/nitrostack/cli/pack.py b/nitrostack/cli/pack.py index b2a805c..221a6bc 100644 --- a/nitrostack/cli/pack.py +++ b/nitrostack/cli/pack.py @@ -1,8 +1,9 @@ """Project packing for `nitrostack-py pack`. Builds a deployable wheel of the current project using the setuptools backend -already declared in NitroStack's packaging config. Secrets (``.env``) are never -included. Temporary build artifacts are cleaned up after packing. +already declared in NitroStack's packaging config. Secrets (``.env``) are excluded +by default; pass ``include_env`` to pack them. Temporary build artifacts are +cleaned up after packing. """ from __future__ import annotations @@ -110,10 +111,17 @@ def _matches_gitignore(rel_posix: str, patterns: Sequence[Tuple[str, bool]]) -> return ignored -def _should_exclude(rel_posix: str, name: str, is_dir: bool, gitignore: Sequence[Tuple[str, bool]]) -> bool: +def _should_exclude( + rel_posix: str, + name: str, + is_dir: bool, + gitignore: Sequence[Tuple[str, bool]], + *, + include_env: bool = False, +) -> bool: if name == ".env.example": return False - if _is_secret_env(name): + if _is_secret_env(name) and not include_env: return True if name in _EXCLUDE_DIR_NAMES and is_dir: return True @@ -128,7 +136,7 @@ def _should_exclude(rel_posix: str, name: str, is_dir: bool, gitignore: Sequence return False -def collect_pack_files(root: str) -> List[str]: +def collect_pack_files(root: str, *, include_env: bool = False) -> List[str]: """Return posix-relative paths that would be included in a pack.""" gitignore = _load_gitignore_patterns(root) included: List[str] = [] @@ -141,14 +149,14 @@ def collect_pack_files(root: str) -> List[str]: kept_dirs = [] for dirname in dirnames: child_rel = f"{rel_dir_posix}/{dirname}" if rel_dir_posix else dirname - if _should_exclude(child_rel, dirname, True, gitignore): + if _should_exclude(child_rel, dirname, True, gitignore, include_env=include_env): continue kept_dirs.append(dirname) dirnames[:] = kept_dirs for filename in filenames: child_rel = f"{rel_dir_posix}/{filename}" if rel_dir_posix else filename - if _should_exclude(child_rel, filename, False, gitignore): + if _should_exclude(child_rel, filename, False, gitignore, include_env=include_env): continue included.append(child_rel) @@ -348,14 +356,14 @@ def _is_valid_wheel(path: str) -> bool: return "Wheel-Version:" in body -def _collect_staging_bytes(src_root: str) -> dict: +def _collect_staging_bytes(src_root: str, *, include_env: bool = False) -> dict: contents = {} for dirpath, dirnames, filenames in os.walk(src_root): dirnames[:] = [d for d in dirnames if d not in _EXCLUDE_DIR_NAMES and not d.endswith(".egg-info")] for filename in filenames: if any(filename.endswith(suffix) for suffix in _EXCLUDE_SUFFIXES): continue - if _is_secret_env(filename): + if _is_secret_env(filename) and not include_env: continue full = os.path.join(dirpath, filename) rel = os.path.relpath(full, src_root).replace("\\", "/") @@ -370,6 +378,8 @@ def _write_purelib_wheel( name: str, version: str, deps: Sequence[str], + *, + include_env: bool = False, ) -> str: """Write a PEP 427 py3-none-any wheel from the staged project files.""" os.makedirs(wheel_dir, exist_ok=True) @@ -379,7 +389,7 @@ def _write_purelib_wheel( wheel_path = os.path.join(wheel_dir, wheel_filename) dist_info = f"{dist_name}-{version}.dist-info" - contents = _collect_staging_bytes(src_root) + contents = _collect_staging_bytes(src_root, include_env=include_env) metadata_lines = [ "Metadata-Version: 2.1", f"Name: {display_name}", @@ -441,18 +451,34 @@ def _build_wheel( name: str, version: str, deps: Sequence[str], + *, + include_env: bool = False, ) -> str: os.makedirs(wheel_dir, exist_ok=True) built = _build_wheel_with_setuptools(src_root, wheel_dir) if built: return built - return _write_purelib_wheel(src_root, wheel_dir, name, version, deps) + return _write_purelib_wheel( + src_root, wheel_dir, name, version, deps, include_env=include_env + ) + + +def _secret_env_paths_in_pack(files: Sequence[str]) -> List[str]: + return sorted(rel for rel in files if _is_secret_env(rel.rsplit("/", 1)[-1])) + + +def _warn_including_env_files(env_files: Sequence[str]) -> None: + if not env_files: + return + listed = ", ".join(env_files) + print(f"Warning: Including .env files in the wheel (use with caution!): {listed}") def pack_project( root: Optional[str] = None, *, dry_run: bool = False, + include_env: bool = False, output_dir: Optional[str] = None, ) -> dict: """Pack the project at ``root``. @@ -462,12 +488,15 @@ def pack_project( root = os.path.abspath(root or os.getcwd()) from nitrostack.cli.vendor import ensure_vendored_nitrostack ensure_vendored_nitrostack(root) - files = collect_pack_files(root) + files = collect_pack_files(root, include_env=include_env) name, version = _project_name_and_version(root) dist_name = _pep503_wheel_name(_normalize_dist_name(name)) planned_wheel = f"{dist_name}-{version}-py3-none-any.whl" dest_dir = os.path.abspath(output_dir or os.path.join(root, "dist")) + if include_env: + _warn_including_env_files(_secret_env_paths_in_pack(files)) + print("Files that would be packed:" if dry_run else "Packing files:") for rel in files: print(f" {rel}") @@ -486,12 +515,17 @@ def pack_project( write_requirements_txt(staging, deps) _ensure_pyproject(staging, name, version, deps) - wheel_path = _build_wheel(staging, wheel_tmp, name, version, deps) + wheel_path = _build_wheel( + staging, wheel_tmp, name, version, deps, include_env=include_env + ) extra = [] env_example = os.path.join(staging, ".env.example") reqs = os.path.join(staging, "requirements.txt") extra.append((".env.example", env_example)) extra.append(("requirements.txt", reqs)) + if include_env: + for rel in _secret_env_paths_in_pack(files): + extra.append((rel, os.path.join(staging, rel.replace("/", os.sep)))) _inject_into_wheel(wheel_path, extra) if not _is_valid_wheel(wheel_path): diff --git a/tests/test_cli.py b/tests/test_cli.py index 95046d9..40b218e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1072,6 +1072,38 @@ def test_pack_dry_run_lists_files_without_writing(tmp_path: Path): assert not (project / "dist").exists() +def test_pack_include_env_dry_run_lists_env_without_printing_contents(tmp_path: Path, capsys): + project = _mini_project(tmp_path) + (project / ".env.local").write_text("TOKEN=local-secret\n", encoding="utf-8") + result = pack_project(str(project), dry_run=True, include_env=True) + assert result["dry_run"] is True + assert ".env" in result["files"] + assert ".env.local" in result["files"] + captured = capsys.readouterr().out + assert "Warning: Including .env files in the wheel (use with caution!)" in captured + assert ".env" in captured + assert ".env.local" in captured + assert "SECRET=should-never-pack" not in captured + assert "TOKEN=local-secret" not in captured + + +def test_pack_include_env_puts_env_in_wheel_without_printing_contents(tmp_path: Path, capsys): + project = _mini_project(tmp_path) + result = pack_project(str(project), dry_run=False, include_env=True) + captured = capsys.readouterr().out + assert "Warning: Including .env files in the wheel (use with caution!)" in captured + assert "SECRET=should-never-pack" not in captured + + wheel = Path(result["wheel"]) + with zipfile.ZipFile(wheel) as zf: + names = zf.namelist() + assert any(n == ".env" or n.endswith("/.env") for n in names) + env_data = next( + zf.read(n).decode("utf-8") for n in names if n == ".env" or n.endswith("/.env") + ) + assert "SECRET=should-never-pack" in env_data + + def test_pack_creates_valid_wheel(tmp_path: Path): project = _mini_project(tmp_path) result = pack_project(str(project), dry_run=False) From 902d0ddcf7bd6de3978c382e486d4e05a3009ae0 Mon Sep 17 00:00:00 2001 From: Hemant Jadhav Date: Sat, 17 Oct 2026 20:29:06 +0530 Subject: [PATCH 12/34] docs: add Product Hunt featured badge to README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 0f55682..7deb60d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # NitroStack Python SDK +NitroStack - Build, test, and deploy MCP servers in one place | Product Hunt + Build Model Context Protocol (MCP) servers in Python with a NestJS-style structure: modules, dependency injection, decorators for tools, resources and prompts, and a pipeline of guards, middleware, interceptors, pipes and exception filters. It's the Python port of the [NitroStack](https://docs.nitrostack.ai/) TypeScript framework. - **Docs:** [docs.nitrostack.ai/python](https://docs.nitrostack.ai/python) From d51e202a5ec14b75308fcba09a60f91846fdf900 Mon Sep 17 00:00:00 2001 From: Hemant Jadhav Date: Sun, 18 Oct 2026 11:04:26 +0530 Subject: [PATCH 13/34] docs: update Product Hunt badge to #1 Product of the Day top-post badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7deb60d..c7285ec 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # NitroStack Python SDK -NitroStack - Build, test, and deploy MCP servers in one place | Product Hunt +NitroStack - Build, test, and deploy MCP servers in one place | Product Hunt Build Model Context Protocol (MCP) servers in Python with a NestJS-style structure: modules, dependency injection, decorators for tools, resources and prompts, and a pipeline of guards, middleware, interceptors, pipes and exception filters. It's the Python port of the [NitroStack](https://docs.nitrostack.ai/) TypeScript framework. From c9daf8c55a89e9f54f617fbb274c91a53648dd10 Mon Sep 17 00:00:00 2001 From: manish-wekan Date: Wed, 25 Nov 2026 16:21:43 +0530 Subject: [PATCH 14/34] 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 15/34] 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 16/34] 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 17/34] 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 18/34] 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 19/34] 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 20/34] 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 21/34] 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 22/34] 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 23/34] 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 24/34] 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 25/34] 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 26/34] 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 27/34] 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 28/34] 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 29/34] 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 30/34] 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 31/34] 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 32/34] 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 33/34] 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 34/34] 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