Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# NitroStack Python SDK / CLI — analytics (see docs/analytics-events.md)
# Optional: override the built-in public PostHog project key (never commit non-public values).
NITROSTACK_POSTHOG_KEY=
# Optional: PostHog ingest host (default US Cloud).
NITROSTACK_POSTHOG_HOST=https://us.i.posthog.com
# production | staging | development (default: inferred from NODE_ENV / CI).
NITROSTACK_ENVIRONMENT=
# Set to 0/false/off to disable CLI telemetry (DO_NOT_TRACK=1 also disables).
NITROSTACK_TELEMETRY=
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ Once scaffolded, follow the next steps printed by the CLI to run your server, co

The CLI is installed with the SDK (`nitrostack-py`, or `python -m nitrostack.cli.main`). Run `nitrostack-py --help` to list commands.

**Usage telemetry** — The CLI sends anonymous usage events to PostHog using a built-in public project key (same CLI/SDK project as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` to override that key, `NITROSTACK_POSTHOG_HOST` to override the ingest URL (default `https://us.i.posthog.com`). Disable with `DO_NOT_TRACK=1` or `NITROSTACK_TELEMETRY=0`. Exit runs a best-effort flush (up to 2s); see [`docs/analytics-events.md`](docs/analytics-events.md) for events, opt-out, and delivery notes.

### Project lifecycle

```bash
Expand Down Expand Up @@ -265,6 +267,10 @@ The SDK reads standard settings from the environment or `.env` files:
| `NITROSTACK_LOG_LEVEL` | Log level (`DEBUG`, `INFO`, `WARNING`, `ERROR`). |
| `NITROSTACK_LOG_TO_STDOUT` | Set to `true` to allow logging to stdout under stdio transport (Caution: may corrupt protocol stream). |
| `NITROSTACK_HTTP_DEBUG` | Set to `1` to log every HTTP request (method, path, headers, body) and response status to stderr. Use when diagnosing a client that fails to connect: uvicorn's access log shows neither headers nor timestamps. |
| `NITROSTACK_POSTHOG_KEY` | Optional. Override the PostHog project key used for CLI telemetry (see `docs/analytics-events.md`); if unset, a built-in public key is used. |
| `NITROSTACK_POSTHOG_HOST` | Optional. PostHog ingest host (default `https://us.i.posthog.com`). |
| `NITROSTACK_ENVIRONMENT` | `production`, `staging`, or `development` for analytics super-properties. |
| `NITROSTACK_TELEMETRY` | Set to `0` / `false` / `off` to disable CLI telemetry (in addition to `DO_NOT_TRACK=1`). |

### Keeping secrets out of logs (`SecretValue`)

Expand Down
44 changes: 44 additions & 0 deletions docs/analytics-events.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# NitroStack Python SDK CLI — analytics events

Telemetry uses a **built-in public PostHog project key** (same ingest as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` only if you need to override that key. Telemetry is **off** when `DO_NOT_TRACK=1`, when `NITROSTACK_TELEMETRY=0` (or `false`/`off`/`no`), during pytest (`PYTEST_CURRENT_TEST`), and in CI when `NITROSTACK_TELEMETRY` is unset (set it to a truthy value to allow capture in CI).

On process exit the CLI runs a **best-effort flush** (PostHog `shutdown` on a background thread, joined for up to **2 seconds**). Events still in the queue after that window may not be delivered; command completion is never blocked longer than that timeout.

`pack --dry-run` lists files that would be packed but does **not** emit `cli_deploy_completed` or `cli_deploy_failed`.

## Super properties

Sent on every captured event:

| Property | Description |
|----------|-------------|
| `product` | `python_sdk` |
| `surface` | `terminal` |
| `environment` | `production`, `staging`, or `development` (from `NITROSTACK_ENVIRONMENT` or heuristics) |
| `app_version` | Installed `nitrostack` package version |
| `python_version` | Interpreter version |
| `sdk_version` | Same as `app_version` |
| `os_platform` | `sys.platform` |
| `os_arch` | `platform.machine()` |

## Events

| Event | When | Properties |
|-------|------|------------|
| `cli_command_invoked` | Every subcommand after parse | `command`: subcommand name (`init`, `pack`, …) |
| `cli_init_completed` | `init` finishes successfully | `template`, `skip_install`, `duration_ms`, `has_custom_description` |
| `cli_login_completed` | After `nitrostack-py login` succeeds (identity helper) | `user_email`, `cloud_user_id` (+ super properties) |
| `cli_deploy_completed` | `pack` writes a valid wheel | none beyond super properties |
| `cli_deploy_failed` | `pack` raises before success | `error_code`: exception type name (truncated) |

## Identity

- **Anonymous:** distinct id = first 16 hex chars of SHA-256(`hostname`:`username`), same scheme as the TypeScript CLI.
- **Login:** `login` runs `alias(anonymous, user_id)`, `identify(user_id, { email })`, optional `group_identify('organization', org_id)`, then `cli_login_completed`. Subsequent events use the Cloud user id as distinct id.

## Code locations

- Module: `nitrostack/cli/telemetry.py`
- CLI wiring: `nitrostack/cli/main.py` (`track_command_invoked`, `login`, `shutdown_telemetry`)
- Init: `nitrostack/cli/_project_init.py` (`cli_init_completed`)
- Deploy: `nitrostack/cli/pack.py` (`cli_deploy_*`)
25 changes: 25 additions & 0 deletions nitrostack/cli/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,29 @@ def build_parser(*, _add_port_flags, OFFICIAL_TEMPLATES):
help="Lint project config, @mcp_app imports, and @module() class references",
)

login_parser = subparsers.add_parser(
"login",
help=(
"Record NitroCloud user identity for analytics "
"(alias anonymous id to Cloud user id)"
),
)
login_parser.add_argument(
"--user-id",
required=True,
dest="user_id",
help="Stable NitroCloud user id",
)
login_parser.add_argument(
"--email",
required=True,
help="User email (e.g. user@example.com)",
)
login_parser.add_argument(
"--org-id",
default=None,
dest="org_id",
help="Organization id for group analytics (optional)",
)

return parser, gen_parser
18 changes: 18 additions & 0 deletions nitrostack/cli/_project_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import sys
import shutil
import subprocess
import time

from nitrostack.cli.telemetry import track_init_completed


def init_project(
Expand Down Expand Up @@ -34,6 +37,7 @@ def init_project(
run_skills_flow,
):
print_banner()
init_started = time.monotonic()

# 1. Project name — optional CLI arg, otherwise the next readline
if not name:
Expand Down Expand Up @@ -204,6 +208,13 @@ def init_project(
else:
print(" Try search_tools with 'overdue invoices', then invoke it through call_tool")
print("\nHappy coding! 🚀\n")
duration_ms = int((time.monotonic() - init_started) * 1000)
track_init_completed(
template=template,
skip_install=skip_install,
duration_ms=duration_ms,
has_custom_description=description.strip() != "My awesome MCP server",
)
return
if template == "python-oauth":
print(" 2. Configure OAuth credentials in your \033[34m.env\033[0m file")
Expand All @@ -220,3 +231,10 @@ def init_project(
print(" 6. NitroStudio cannot folder-connect a Python project (it looks for @nitrostack/core).")
print(" Use Inspector HTTP as above, or Studio's custom MCP URL if it offers Streamable HTTP.")
print("\nHappy coding! 🚀\n")
duration_ms = int((time.monotonic() - init_started) * 1000)
track_init_completed(
template=template,
skip_install=skip_install,
duration_ms=duration_ms,
has_custom_description=description.strip() != "My awesome MCP server",
)
123 changes: 73 additions & 50 deletions nitrostack/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
from nitrostack.cli.install import install_dependencies, lock_with_uv, rewrite_pyproject_identity
from nitrostack.cli.pack import pack_project
from nitrostack.cli.skills import run_skills_flow
from nitrostack.cli.telemetry import (
identify_from_cloud_login,
maybe_print_first_run_notice,
shutdown_telemetry,
track_command_invoked,
)
from nitrostack.cli.upgrade import upgrade_project
from nitrostack.cli.validators import format_report, validate_project
from nitrostack.cli._parser import build_parser
Expand Down Expand Up @@ -186,6 +192,15 @@ def init_project(name: str = None, template: str = None, skip_install: bool = Fa
)


def run_login(user_id: str, email: str, org_id: str | None = None):
"""Associate the anonymous CLI distinct id with a NitroCloud user (analytics)."""
identify_from_cloud_login(
user_id=(user_id or "").strip(),
email=(email or "").strip(),
organization_id=(org_id or "").strip() or None,
)


def run_dev(port=None, widget=None):
return _servers.run_dev(
port,
Expand Down Expand Up @@ -272,56 +287,64 @@ def main():
parser.print_help()
sys.exit(1)

def _run_command(fn, *fn_args, **fn_kwargs):
try:
return fn(*fn_args, **fn_kwargs)
except Exception as exc:
print(f"Error: {exc}")
sys.exit(1)

if args.command == "init":
init_project(
args.name,
args.template,
skip_install=args.skip_install,
port=args.port,
widget=args.widget,
force=args.force,
)
elif args.command == "dev":
run_dev(port=args.port, widget=args.widget)
elif args.command == "start":
run_start(port=args.port, widget=args.widget)
elif args.command == "register":
register_server(args.name, args.file)
elif args.command == "cursor":
register_cursor_server(args.name, args.file, global_config=args.global_config, transport=args.transport)
elif args.command == "generate":
if not args.generator:
gen_parser.print_help()
sys.exit(1)
if args.generator == "tool":
generate_tool(args.name)
elif args.generator == "module":
generate_module(args.name)
else:
generate_component(args.generator, args.name)
elif args.command == "pack":
_run_command(pack_project, dry_run=args.dry_run)
elif args.command == "upgrade":
_run_command(
upgrade_project,
version=args.target_version,
dry_run=args.dry_run,
allow_downgrade=args.allow_downgrade,
)
elif args.command == "install":
_run_command(install_dependencies, production=args.production)
elif args.command == "validate":
issues = _run_command(validate_project)
print(format_report(issues))
if any(issue.severity == "error" for issue in issues):
sys.exit(1)
try:
maybe_print_first_run_notice()
track_command_invoked(args.command)

def _run_command(fn, *fn_args, **fn_kwargs):
try:
return fn(*fn_args, **fn_kwargs)
except Exception as exc:
print(f"Error: {exc}")
sys.exit(1)

if args.command == "init":
init_project(
args.name,
args.template,
skip_install=args.skip_install,
port=args.port,
widget=args.widget,
force=args.force,
)
elif args.command == "dev":
run_dev(port=args.port, widget=args.widget)
elif args.command == "start":
run_start(port=args.port, widget=args.widget)
elif args.command == "register":
register_server(args.name, args.file)
elif args.command == "cursor":
register_cursor_server(args.name, args.file, global_config=args.global_config, transport=args.transport)
elif args.command == "generate":
if not args.generator:
gen_parser.print_help()
sys.exit(1)
if args.generator == "tool":
generate_tool(args.name)
elif args.generator == "module":
generate_module(args.name)
else:
generate_component(args.generator, args.name)
elif args.command == "pack":
_run_command(pack_project, dry_run=args.dry_run)
elif args.command == "upgrade":
_run_command(
upgrade_project,
version=args.target_version,
dry_run=args.dry_run,
allow_downgrade=args.allow_downgrade,
)
elif args.command == "install":
_run_command(install_dependencies, production=args.production)
elif args.command == "validate":
issues = _run_command(validate_project)
print(format_report(issues))
if any(issue.severity == "error" for issue in issues):
sys.exit(1)
elif args.command == "login":
_run_command(run_login, args.user_id, args.email, args.org_id)
finally:
shutdown_telemetry()


if __name__ == "__main__":
Expand Down
51 changes: 29 additions & 22 deletions nitrostack/cli/pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
read_text,
requirement_name,
)
from nitrostack.cli.telemetry import track_deploy_completed, track_deploy_failed

# Keep the original import surface while implementations live by responsibility.
from nitrostack.cli._pack_files import (
Expand Down Expand Up @@ -97,28 +98,34 @@ def pack_project(
staging = tempfile.mkdtemp(prefix="nitrostack-pack-")
wheel_tmp = tempfile.mkdtemp(prefix="nitrostack-wheel-")
try:
_copy_selected(root, staging, files)
_ensure_env_example(staging)
deps = requirements_from_project(root)
write_requirements_txt(staging, deps)
_ensure_pyproject(staging, name, version, deps)

wheel_path = _build_wheel(staging, wheel_tmp, name, version, deps)
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))
_inject_into_wheel(wheel_path, extra)

if not _is_valid_wheel(wheel_path):
raise RuntimeError(f"Built file is not a valid wheel: {wheel_path}")

os.makedirs(dest_dir, exist_ok=True)
final_path = os.path.join(dest_dir, os.path.basename(wheel_path))
shutil.copy2(wheel_path, final_path)
print(f"\nCreated wheel: {final_path}")
return {"files": files, "wheel": final_path, "dry_run": False}
try:
_copy_selected(root, staging, files)
_ensure_env_example(staging)
deps = requirements_from_project(root)
write_requirements_txt(staging, deps)
_ensure_pyproject(staging, name, version, deps)

wheel_path = _build_wheel(staging, wheel_tmp, name, version, deps)
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))
_inject_into_wheel(wheel_path, extra)

if not _is_valid_wheel(wheel_path):
raise RuntimeError(f"Built file is not a valid wheel: {wheel_path}")

os.makedirs(dest_dir, exist_ok=True)
final_path = os.path.join(dest_dir, os.path.basename(wheel_path))
shutil.copy2(wheel_path, final_path)
print(f"\nCreated wheel: {final_path}")
track_deploy_completed()
return {"files": files, "wheel": final_path, "dry_run": False}
except Exception as exc:
name_t = type(exc).__name__
track_deploy_failed(error_code=name_t[:80])
raise
finally:
_rmtree(staging)
_rmtree(wheel_tmp)
Loading
Loading