marona-cli 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
marona_cli/mcp.py ADDED
@@ -0,0 +1,158 @@
1
+ """MCP commands use the existing SDK authoring and platform APIs."""
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ from dataclasses import replace
7
+ from pathlib import Path
8
+ from urllib.parse import urlsplit
9
+
10
+ import httpx
11
+ from marona import MCPServer
12
+ from marona.mcp import (
13
+ DeveloperPlatformClient,
14
+ build_python_artifact,
15
+ build_wasm_artifact,
16
+ )
17
+ from marona.mcp.offline import write_artifact_manifest
18
+
19
+ from .agents import MAX_INPUT, load_object, read_input
20
+ from .auth import api_key
21
+ from .config import endpoint
22
+ from .output import emit
23
+
24
+
25
+ def identifier(value):
26
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", value):
27
+ raise ValueError(
28
+ "App and deployment IDs must contain only letters, digits, underscores or hyphens"
29
+ )
30
+ return value
31
+
32
+
33
+ def pairs(values, name):
34
+ result = {}
35
+ for item in values:
36
+ key, separator, value = item.partition("=")
37
+ if not separator or not key.strip():
38
+ raise ValueError(f"--{name} must use NAME=VALUE")
39
+ result[key.strip()] = value
40
+ return result
41
+
42
+
43
+ def json_object(value):
44
+ result = json.loads(value)
45
+ if not isinstance(result, dict):
46
+ raise TypeError("Expected a JSON object")
47
+ return result
48
+
49
+
50
+ def resource_url(value):
51
+ url = urlsplit(value)
52
+ endpoint(url._replace(query="").geturl())
53
+ return value
54
+
55
+
56
+ async def registration_payload(location):
57
+ if not location.startswith(("https://", "http://")):
58
+ return json_object(read_input(location))
59
+ # This fetch is separate from authenticated Platform calls. Never forward the developer key.
60
+ async with (
61
+ httpx.AsyncClient(timeout=30, follow_redirects=False) as client,
62
+ client.stream("GET", resource_url(location)) as response,
63
+ ):
64
+ response.raise_for_status()
65
+ content = bytearray()
66
+ async for chunk in response.aiter_bytes():
67
+ content.extend(chunk)
68
+ if len(content) > MAX_INPUT:
69
+ raise ValueError("Registration exceeds 4 MiB")
70
+ return json_object(content.decode("utf-8"))
71
+
72
+
73
+ def serve(args):
74
+ server = load_object(args.server)
75
+ if not isinstance(server, MCPServer):
76
+ raise TypeError("The selected object is not a marona.MCPServer")
77
+ server.run(host=args.host, port=args.port, transport=args.transport)
78
+
79
+
80
+ async def platform(args, config):
81
+ if args.hub_url and not getattr(args, "platform_url", None):
82
+ config = replace(config, platform_url=endpoint(args.hub_url))
83
+ client = DeveloperPlatformClient(
84
+ platform_url=config.platform_url,
85
+ token=args.token or api_key(config, platform=True),
86
+ )
87
+ if args.command == "publish":
88
+ registration = await registration_payload(args.registration)
89
+ result = await client.create_agent_app(registration)
90
+ if args.submit:
91
+ if not result.get("id"):
92
+ raise ValueError("Platform returned no App id; submission was not attempted")
93
+ result = await client.submit_agent_app(identifier(str(result["id"])))
94
+ elif args.command == "deploy":
95
+ secrets = pairs(args.secret, "secret")
96
+ for name in args.secret_env:
97
+ if name not in os.environ:
98
+ raise ValueError(f"Environment variable {name} is not set")
99
+ secrets[name] = os.environ[name]
100
+ result = await client.create_hosted_deployment(
101
+ identifier(args.app_id),
102
+ source_type=args.source_type,
103
+ source_url=resource_url(args.source_url),
104
+ version=args.version,
105
+ branch=args.branch,
106
+ entrypoint=args.entrypoint,
107
+ runtime=args.runtime,
108
+ region=args.region,
109
+ resource_class=args.resource_class,
110
+ replicas=args.replicas,
111
+ storage_gb=args.storage_gb,
112
+ monthly_price_cents=args.monthly_price_cents,
113
+ currency=args.currency,
114
+ environment=pairs(args.env, "env"),
115
+ secrets=secrets,
116
+ runtime_config=json_object(args.runtime_config),
117
+ )
118
+ elif args.action == "list":
119
+ result = await client.list_hosted_deployments(identifier(args.app_id))
120
+ else:
121
+ result = await client.get_hosted_deployment(
122
+ identifier(args.app_id), identifier(args.deployment_id)
123
+ )
124
+ emit(result, json_mode=True)
125
+
126
+
127
+ def validate_message(args):
128
+ from marona import B2AMessage, D2AMessage
129
+
130
+ from .agents import read_input
131
+
132
+ value = json.loads(read_input(args.input))
133
+ if not isinstance(value, dict):
134
+ raise TypeError("A protocol message must be a JSON object")
135
+ message = (B2AMessage if args.protocol_name == "b2a" else D2AMessage).from_dict(value)
136
+ emit(message.to_dict(), json_mode=True)
137
+
138
+
139
+ def build(args):
140
+ if args.target == "python":
141
+ entrypoint = args.entrypoint or "marona_offline:call_tool"
142
+ source = Path(args.source).resolve()
143
+ # Default to the entrypoint module. Additional assets must be included explicitly.
144
+ included = args.include or [entrypoint.split(":", 1)[0].replace(".", "/") + ".py"]
145
+ for item in included:
146
+ resolved = (source / item).resolve()
147
+ if not resolved.is_relative_to(source):
148
+ raise ValueError("Included paths must stay inside the source directory")
149
+ artifact = build_python_artifact(
150
+ args.source, args.output, entrypoint=entrypoint, include=included
151
+ )
152
+ else:
153
+ artifact = build_wasm_artifact(
154
+ args.source, args.output, entrypoint=args.entrypoint or "marona:tool-component/call@1"
155
+ )
156
+ if args.manifest:
157
+ write_artifact_manifest(artifact, args.manifest, package_url=args.package_url)
158
+ emit(artifact.descriptor(args.package_url), json_mode=True)
marona_cli/output.py ADDED
@@ -0,0 +1,44 @@
1
+ """Terminal-safe human output and machine-readable JSON."""
2
+
3
+ import dataclasses
4
+ import json
5
+ import re
6
+ import sys
7
+ from typing import Any
8
+
9
+
10
+ def plain(value: Any) -> Any:
11
+ if hasattr(value, "model_dump"):
12
+ return value.model_dump(mode="json")
13
+ if hasattr(value, "to_dict"):
14
+ return value.to_dict()
15
+ if hasattr(value, "to_json"):
16
+ return value.to_json()
17
+ if dataclasses.is_dataclass(value):
18
+ return {
19
+ field.name: plain(getattr(value, field.name)) for field in dataclasses.fields(value)
20
+ }
21
+ if isinstance(value, dict):
22
+ return {str(key): plain(item) for key, item in value.items()}
23
+ if isinstance(value, (list, tuple)):
24
+ return [plain(item) for item in value]
25
+ return value
26
+
27
+
28
+ def safe_text(value: str) -> str:
29
+ # Model/tool content must not execute terminal control sequences.
30
+ return re.sub(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]", "", value)
31
+
32
+
33
+ def emit(value: Any, *, json_mode: bool = False, end: str = "\n") -> None:
34
+ value = plain(value)
35
+ text = (
36
+ json.dumps(value, ensure_ascii=True)
37
+ if json_mode or not isinstance(value, str)
38
+ else safe_text(value)
39
+ )
40
+ print(text, end=end, flush=True)
41
+
42
+
43
+ def notice(value: str) -> None:
44
+ print(safe_text(value), file=sys.stderr, flush=True)
marona_cli/parser.py ADDED
@@ -0,0 +1,170 @@
1
+ """The public command interface; handlers live in the corresponding modules."""
2
+
3
+ import argparse
4
+
5
+
6
+ def positive(value):
7
+ number = int(value)
8
+ if number <= 0:
9
+ raise argparse.ArgumentTypeError("must be greater than zero")
10
+ return number
11
+
12
+
13
+ def port(value):
14
+ number = positive(value)
15
+ if number > 65535:
16
+ raise argparse.ArgumentTypeError("must be at most 65535")
17
+ return number
18
+
19
+
20
+ def parser():
21
+ common = argparse.ArgumentParser(add_help=False, argument_default=argparse.SUPPRESS)
22
+ common.add_argument("--profile", help="Named settings profile (default: default)")
23
+ common.add_argument("--runtime-url", help="Runtime endpoint; default https://edge.marona.ai")
24
+ common.add_argument(
25
+ "--platform-url", help="Platform API endpoint; default https://platform.marona.ai/api"
26
+ )
27
+ common.add_argument("--model", help="Registered marona/<alias>; default marona/auto")
28
+ common.add_argument("--user-id", help="Application user identity")
29
+ common.add_argument(
30
+ "--json", action="store_true", help="JSON output; streaming uses newline-delimited JSON"
31
+ )
32
+ root = argparse.ArgumentParser(
33
+ prog="marona",
34
+ description="Run Agents, connect protocols and build MCP services with Marona.",
35
+ parents=[common],
36
+ )
37
+ root.add_argument("--version", action="store_true", help="Print CLI and SDK versions")
38
+ commands = root.add_subparsers(dest="command")
39
+
40
+ def command(name, help):
41
+ return commands.add_parser(name, help=help, parents=[common])
42
+
43
+ command("version", "Print CLI and SDK versions")
44
+ config = command("config", "Inspect or save non-secret settings")
45
+ config.add_argument("action", choices=["show", "set"])
46
+ auth = command("auth", "Manage your own developer credential")
47
+ auth.add_argument("action", choices=["login", "status", "logout"])
48
+ auth.add_argument(
49
+ "--verify", action="store_true", help="Verify status with a read-only runtime request"
50
+ )
51
+ auth.add_argument(
52
+ "--key-stdin", action="store_true", help="Read the login key from standard input"
53
+ )
54
+ command("doctor", "Check local configuration, package versions and credential availability")
55
+ apps = command("apps", "List available Apps")
56
+ apps.add_argument("--limit", type=positive, default=20)
57
+ apps.add_argument("--cursor")
58
+ apps.add_argument("--search")
59
+ tools = command("tools", "List connected Hub capabilities")
60
+ tools.add_argument(
61
+ "--app", action="append", help="Scope to an App slug; repeat for multiple Apps"
62
+ )
63
+
64
+ for name, description in [
65
+ ("run", "Run one Agent request"),
66
+ ("chat", "Start an interactive Agent conversation"),
67
+ ("connect", "Receive realtime protocol events until Ctrl+C"),
68
+ ]:
69
+ cmd = command(name, description)
70
+ cmd.add_argument(
71
+ "--agent",
72
+ required=name == "connect",
73
+ help="Explicit trusted Python object, e.g. agent:agent (executes that module)",
74
+ )
75
+ cmd.add_argument(
76
+ "--app", action="append", help="Attach Hub tools for this App; repeat as needed"
77
+ )
78
+ cmd.add_argument("--instructions", help="Instructions for an inline Agent")
79
+ cmd.add_argument("--session-id", help="Resume a known session; omitted creates a new UUID")
80
+ cmd.add_argument("--protocol", help="Select one configured Agent protocol by name")
81
+ cmd.add_argument(
82
+ "--timeout",
83
+ type=positive,
84
+ default=60,
85
+ help="Agent run timeout in seconds (default: SDK 60); does not time-limit connect",
86
+ )
87
+ if name == "run":
88
+ group = cmd.add_mutually_exclusive_group()
89
+ group.add_argument("prompt", nargs="?")
90
+ group.add_argument(
91
+ "--input-json", metavar="PATH|-", help="Structured SDK input; '-' reads stdin"
92
+ )
93
+ cmd.add_argument("--stream", action="store_true", help="Stream text as it arrives")
94
+ elif name == "chat":
95
+ cmd.add_argument(
96
+ "--no-stream", action="store_false", dest="stream", help="Wait for complete output"
97
+ )
98
+ else:
99
+ cmd.add_argument(
100
+ "--input-json",
101
+ metavar="PATH|-",
102
+ help="Optional initial standard message or neural signal",
103
+ )
104
+ cmd.add_argument(
105
+ "--signal",
106
+ action="store_true",
107
+ help="Send the initial JSON through the B2A send_signal API",
108
+ )
109
+
110
+ init = command("init", "Create a small runnable SDK project in a new directory")
111
+ init.add_argument("template", choices=["agent", "mcp"])
112
+ init.add_argument("directory")
113
+ mcp = command("mcp", "Serve an MCPServer from your trusted Python project")
114
+ mcp.add_argument("action", choices=["serve"])
115
+ mcp.add_argument("server", help="Python reference, e.g. server:server (executes that module)")
116
+ mcp.add_argument("--host", default="127.0.0.1")
117
+ mcp.add_argument("--port", type=port, default=62900)
118
+ mcp.add_argument("--transport", choices=["http", "stdio"], default="http")
119
+ protocol = command("protocol", "Validate a standard B2A or D2A message without sending it")
120
+ protocol.add_argument("action", choices=["validate"])
121
+ protocol.add_argument("protocol_name", choices=["b2a", "d2a"])
122
+ protocol.add_argument("input", metavar="PATH|-")
123
+
124
+ build = command("build", "Build a portable offline artifact")
125
+ build.add_argument("--target", choices=["python", "wasm"], required=True)
126
+ build.add_argument("--source", required=True)
127
+ build.add_argument("--output", required=True)
128
+ build.add_argument("--entrypoint")
129
+ build.add_argument("--include", action="append", default=[])
130
+ build.add_argument("--package-url")
131
+ build.add_argument("--manifest")
132
+ publish = command("publish", "Register an MCP App on Marona Platform")
133
+ publish.add_argument(
134
+ "--registration", required=True, help="Registration JSON file or public HTTPS URL"
135
+ )
136
+ publish.add_argument("--submit", action="store_true", help="Also submit for review")
137
+ deploy = command("deploy", "Create a hosted MCP deployment")
138
+ deploy.add_argument("--app-id", required=True)
139
+ deploy.add_argument("--source-url", required=True)
140
+ deploy.add_argument(
141
+ "--source-type", choices=["repository", "source_archive"], default="repository"
142
+ )
143
+ deploy.add_argument("--version")
144
+ deploy.add_argument("--branch", default="main")
145
+ deploy.add_argument("--entrypoint")
146
+ deploy.add_argument("--runtime", choices=["python", "node", "rust", "custom"], default="python")
147
+ deploy.add_argument("--region")
148
+ deploy.add_argument("--resource-class", default="shared-small")
149
+ deploy.add_argument("--replicas", type=positive, default=1)
150
+ deploy.add_argument("--storage-gb", type=positive, default=1)
151
+ deploy.add_argument("--monthly-price-cents", type=int, default=0)
152
+ deploy.add_argument("--currency", default="USD")
153
+ deploy.add_argument("--runtime-config", default="{}")
154
+ deploy.add_argument("--env", action="append", default=[])
155
+ deploy.add_argument("--secret", action="append", default=[], help=argparse.SUPPRESS)
156
+ deploy.add_argument(
157
+ "--secret-env",
158
+ action="append",
159
+ default=[],
160
+ metavar="NAME",
161
+ help="Read a deployment secret from a named environment variable",
162
+ )
163
+ deployments = command("deployments", "Inspect hosted deployments")
164
+ deployments.add_argument("action", choices=["list", "get"])
165
+ deployments.add_argument("--app-id", required=True)
166
+ deployments.add_argument("--deployment-id")
167
+ for cmd in (publish, deploy, deployments):
168
+ cmd.add_argument("--hub-url", help=argparse.SUPPRESS)
169
+ cmd.add_argument("--token", help=argparse.SUPPRESS)
170
+ return root
marona_cli/projects.py ADDED
@@ -0,0 +1,174 @@
1
+ """Small, runnable projects with direct SDK objects and no generated wrappers."""
2
+
3
+ import json
4
+ import re
5
+ import shutil
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+ from .output import emit
10
+
11
+ # Keep deployed applications on a verified public SDK release, independently of
12
+ # the version of the developer CLI that generated them.
13
+ RUNTIME_SDK_VERSION = "2.12.1"
14
+
15
+
16
+ def initialize(args):
17
+ path = Path(args.directory).expanduser().absolute()
18
+ if path.exists():
19
+ raise ValueError("Destination already exists; choose a new directory")
20
+ if not path.parent.is_dir():
21
+ raise ValueError("Destination parent directory must exist")
22
+ slug = path.name
23
+ if not re.fullmatch(r"[a-z][a-z0-9-]{0,62}", slug):
24
+ raise ValueError(
25
+ "Project directory name must use lowercase letters, digits and hyphens, beginning with a letter"
26
+ )
27
+ name = json.dumps(slug.replace("-", " ").title())
28
+ files = {
29
+ "requirements.txt": f"marona=={RUNTIME_SDK_VERSION}\n",
30
+ ".gitignore": ".env\n.venv/\n__pycache__/\n*.pyc\n",
31
+ ".dockerignore": ".git\n.env\n.env.*\n.venv\n__pycache__\n",
32
+ }
33
+ if args.template == "agent":
34
+ files["agent.py"] = f"""from marona import Agent
35
+
36
+ agent = Agent(
37
+ name={name},
38
+ model="marona/auto",
39
+ instructions="Answer clearly and concisely.",
40
+ )
41
+ """
42
+ files["main.py"] = """import asyncio
43
+ import os
44
+ import sys
45
+ import uuid
46
+
47
+ from marona import Marona, Runner
48
+
49
+ from agent import agent
50
+
51
+
52
+ async def main():
53
+ prompt = " ".join(sys.argv[1:])
54
+ if not prompt and not sys.stdin.isatty():
55
+ prompt = sys.stdin.read()
56
+ if not prompt.strip():
57
+ raise SystemExit("Provide a prompt: python main.py 'Hello'")
58
+ key = os.environ.get("MARONA_API_KEY")
59
+ if not key:
60
+ raise SystemExit("Set MARONA_API_KEY in the environment")
61
+ async with Marona(
62
+ api_key=key,
63
+ base_url=os.environ.get("MARONA_RUNTIME_URL", "https://edge.marona.ai"),
64
+ ):
65
+ result = await Runner.run(
66
+ agent,
67
+ prompt,
68
+ user_id=os.environ.get("MARONA_USER_ID"),
69
+ session_id=os.environ.get("MARONA_SESSION_ID") or str(uuid.uuid4()),
70
+ )
71
+ print(result.output)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ asyncio.run(main())
76
+ """
77
+ files["README.md"] = f"""# {slug}
78
+
79
+ Install `requirements.txt` in a virtual environment and set `MARONA_API_KEY`.
80
+
81
+ ```sh
82
+ python -m pip install -r requirements.txt
83
+ python main.py 'Hello'
84
+ ```
85
+
86
+ Define your Agent in `agent.py`; `main.py` connects it to the Marona SDK.
87
+ Set `MARONA_SESSION_ID` to continue a session and `MARONA_USER_ID` for application
88
+ identity. The default runtime is `https://edge.marona.ai`; override it with
89
+ `MARONA_RUNTIME_URL` when needed.
90
+
91
+ ```sh
92
+ docker build -t {slug} .
93
+ docker run --rm -e MARONA_API_KEY {slug} 'Hello'
94
+ ```
95
+
96
+ The container runs Python directly and needs only the published Marona SDK.
97
+ If the full Marona CLI is installed in your development environment, you can also
98
+ use `marona chat --agent agent:agent` with this project.
99
+ """
100
+ command = '["python", "main.py"]'
101
+ service_environment = ""
102
+ else:
103
+ files["server.py"] = f'''import os
104
+ from marona import MCPServer
105
+
106
+ server = MCPServer(
107
+ name={name},
108
+ slug={json.dumps(slug)},
109
+ description="Tools for greeting users.",
110
+ category="Tools",
111
+ visibility="private",
112
+ api_key_env="MCP_API_KEY",
113
+ )
114
+
115
+ @server.tool()
116
+ def greet(name: str) -> dict:
117
+ """Return a greeting for the supplied name."""
118
+ return {{"message": f"Hello, {{name}}!"}}
119
+
120
+ if __name__ == "__main__":
121
+ server.run(
122
+ host=os.getenv("HOST", "127.0.0.1"),
123
+ port=int(os.getenv("PORT", "62900")),
124
+ transport=os.getenv("TRANSPORT", "http"),
125
+ )
126
+ '''
127
+ files["README.md"] = f"""# {slug}
128
+
129
+ Install `requirements.txt` in a virtual environment. Configure `MCP_API_KEY`
130
+ in your environment before serving HTTP.
131
+
132
+ ```sh
133
+ python -m pip install -r requirements.txt
134
+ python server.py
135
+ ```
136
+
137
+ Use `TRANSPORT=stdio` for an MCP stdio client. HTTP defaults to
138
+ `127.0.0.1:62900`; override with `HOST` and `PORT` when needed.
139
+
140
+ ```sh
141
+ docker build -t {slug} .
142
+ docker run --rm -p 127.0.0.1:62900:62900 -e MCP_API_KEY {slug}
143
+ ```
144
+
145
+ The container binds to `0.0.0.0` and runs Python directly. It needs only the
146
+ published Marona SDK; the CLI is a development tool, not a server dependency.
147
+ The SDK owns `/mcp`, `/health`, `/manifest` and `/hub-registration`.
148
+ Use explicit allowed hosts, origins and authentication at a public service boundary.
149
+ With the full Marona CLI installed locally, register your HTTPS service using
150
+ `marona publish --registration registration.json` and deploy the registered app
151
+ using `marona deploy --app-id APP_ID --source-url REPOSITORY_URL --branch main`.
152
+ """
153
+ command = '["python", "server.py"]'
154
+ service_environment = "ENV HOST=0.0.0.0 PORT=62900\nEXPOSE 62900\n"
155
+ files["Dockerfile"] = f"""FROM python:3.12-slim
156
+ WORKDIR /app
157
+ COPY requirements.txt .
158
+ RUN pip install --no-cache-dir -r requirements.txt && useradd --uid 10001 --create-home marona
159
+ COPY . .
160
+ ENV HOME=/home/marona PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
161
+ {service_environment}USER 10001
162
+ ENTRYPOINT {command}
163
+ """
164
+ temporary = Path(tempfile.mkdtemp(prefix=".marona-init-", dir=path.parent))
165
+ try:
166
+ for filename, content in files.items():
167
+ (temporary / filename).write_text(content, encoding="utf-8")
168
+ # mkdir prevents overwriting even if another process creates the target.
169
+ path.mkdir()
170
+ for item in temporary.iterdir():
171
+ item.rename(path / item.name)
172
+ finally:
173
+ shutil.rmtree(temporary)
174
+ emit({"created": str(path), "template": args.template, "files": sorted(files)})