retina-api 0.1.0__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.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.1
2
+ Name: retina-api
3
+ Version: 0.1.0
4
+ Summary: Retina's public API: a Python client, the `retina` CLI and the `retina-mcp` MCP server.
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: httpx>=0.27
7
+ Requires-Dist: typer>=0.12
8
+ Requires-Dist: mcp<2.0,>=1.27
9
+ Description-Content-Type: text/markdown
10
+
11
+ # retina-api
12
+
13
+ Retina's public API for Python, in one package:
14
+
15
+ - `retina_sdk.RetinaClient`, an async client with one method per `/v1` operation.
16
+ - `retina`, a command line tool with one command per method.
17
+ - `retina-mcp`, an MCP server with one tool per method.
18
+
19
+ All three are made from the same operation table, so they always offer the same things.
20
+ The package depends only on `httpx`, `typer` and `mcp`.
21
+
22
+ ## Quickstart: your own Claude Code on Retina
23
+
24
+ You bring the agent.
25
+ Retina gives it tools: research, generation, posting, and the numbers back.
26
+ Your agent runs where you run it; Retina only answers the calls it makes.
27
+
28
+ ### 1. Install
29
+
30
+ ```bash
31
+ pip install retina-api
32
+ ```
33
+
34
+ This gives you two commands: `retina` and `retina-mcp`.
35
+
36
+ ### 2. Set the key
37
+
38
+ Make a workspace key (it starts with `rk_`) in the Retina console.
39
+ Every command and tool reads it from `RETINA_API_KEY`.
40
+
41
+ ```bash
42
+ export RETINA_API_KEY=rk_...
43
+ retina me
44
+ ```
45
+
46
+ `retina me` prints your workspace and its credit balance.
47
+ `RETINA_API_BASE` changes the API address, and the default is `https://api.retina.dev`.
48
+
49
+ ### 3. Add the server to Claude Code
50
+
51
+ ```bash
52
+ claude mcp add retina --env RETINA_API_KEY=rk_... -- uvx --from retina-api retina-mcp
53
+ ```
54
+
55
+ Or use the `retina-mcp` from the venv where you installed the package:
56
+
57
+ ```bash
58
+ claude mcp add retina --env RETINA_API_KEY=rk_... -- /path/to/venv/bin/retina-mcp
59
+ ```
60
+
61
+ Run `claude mcp list` to check that `retina` is connected.
62
+
63
+ Any other MCP client takes the same command in its JSON config:
64
+
65
+ ```json
66
+ {
67
+ "mcpServers": {
68
+ "retina": {
69
+ "command": "uvx",
70
+ "args": ["--from", "retina-api", "retina-mcp"],
71
+ "env": {"RETINA_API_KEY": "rk_..."}
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ The server has one tool per `/v1` operation, named `retina_<method>`.
78
+ A tool that fails returns the API's error object (`success: false`, `error.code`) instead of raising.
79
+ It still starts when it cannot reach the API; the tools then answer `network_error`.
80
+
81
+ ### 4. A worked example
82
+
83
+ Ask Claude Code, in plain words:
84
+
85
+ > Read retina_guide. Then use retina_research_outliers to find what beats the usual views for "home espresso" in the last 30 days, with a budget of $0.50. Tell me the three best outliers and what they have in common.
86
+
87
+ Claude calls `retina_guide`, then `retina_research_outliers`, and reads the answer back to you.
88
+ The search is charged on success; `retina_me` shows what it cost.
89
+
90
+ The same steps from the shell:
91
+
92
+ ```bash
93
+ retina guide
94
+ retina research-outliers --keywords "home espresso" --days 30 --budget-usd 0.5
95
+ retina me
96
+ ```
97
+
98
+ From there the loop is `retina_generate_media` (or `retina_upload_file`) to make a post, `retina_create_post` to publish it to a linked account (`retina_connect_social` links one), and `retina_post_stats` to read how it did.
99
+
100
+ ## The command line
101
+
102
+ ```bash
103
+ retina catalog
104
+ retina generate-media --operation text_to_image --model <model> --prompt "a cat on a skateboard"
105
+ retina --help
106
+ ```
107
+
108
+ Each command prints JSON.
109
+ `--jq <filter>` filters the output when `jq` is installed.
110
+ An API error exits 1 and prints the error JSON on stderr.
111
+ An API it cannot reach is the same, with the code `network_error`.
112
+ A missing key exits 2.
113
+
114
+ ## The client
115
+
116
+ ```python
117
+ import asyncio
118
+ from retina_sdk import RetinaClient
119
+
120
+ async def main() -> None:
121
+ retina = RetinaClient.from_env()
122
+ print(await retina.me())
123
+
124
+ asyncio.run(main())
125
+ ```
126
+
127
+ ## For Retina developers
128
+
129
+ The client is checked against `src/retina_sdk/v1_contract.json`.
130
+ That file is generated from the backend's own `/v1` spec by `backend/tests/test_the_v1_contract_the_clients_are_checked_against_is_current.py` with `RECORD_V1_CONTRACT=1`.
131
+ Do not edit it by hand.
132
+ When a `/v1` route changes, record the contract again, then add or change the method in `src/retina_sdk/client.py`.
133
+ The tests in `tests/` fail until the client matches.
134
+
135
+ `scripts/prove_the_wheel_installs.sh` builds the wheel, installs it into a clean venv, and starts `retina` and `retina-mcp` with only `RETINA_API_KEY` set.
136
+ It calls no real API.
@@ -0,0 +1,9 @@
1
+ retina_api-0.1.0.dist-info/METADATA,sha256=6eQaCFXsG5KR25OdrwPXx3y-DzW34XqvbIPWxTPfyro,4283
2
+ retina_api-0.1.0.dist-info/WHEEL,sha256=IuIk3wbaEnFH1cx75iM2R1CmliRI3dFLXTbRakgvgFQ,90
3
+ retina_api-0.1.0.dist-info/entry_points.txt,sha256=TUCHptL_va_-DwgposH2ORwh--Uzp2mXqMXDEfz8Ph8,101
4
+ retina_sdk/__init__.py,sha256=z7H0QoQCIjDbMQKlLj3xXzX87vOk8xYXRvP0F5J9Kss,1053
5
+ retina_sdk/cli.py,sha256=SO1-3ncOBiUnUMFTLakkr-x0hKwckmyVyH4xE1C24Ww,6719
6
+ retina_sdk/client.py,sha256=Ph_dBHOEAJqKFx3MBXYMV9gkvA3QfoL06U-OOvrD5Co,41266
7
+ retina_sdk/mcp_server.py,sha256=-p_jLc1sp2iB1OfXFWjHYYjH7YNbzQzw6DYVpMt0Xjs,6107
8
+ retina_sdk/v1_contract.json,sha256=IicIUz8iGfFU_kBhbtyU38wtOHo90bIz-MzdoHEgnSY,11192
9
+ retina_api-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.5.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,6 @@
1
+ [console_scripts]
2
+ retina = retina_sdk.cli:app
3
+ retina-mcp = retina_sdk.mcp_server:run
4
+
5
+ [gui_scripts]
6
+
retina_sdk/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Retina's public API for Python: the client, the `retina` CLI and the `retina-mcp` server.
2
+
3
+ Three layers over one table. `client.RetinaClient` has one method per `/v1`
4
+ operation; `cli` makes one command per method and `mcp_server` one tool per
5
+ method. Nothing else in this package knows a path, a payload or an error rule.
6
+
7
+ Depends only on httpx, typer and mcp. It imports nothing from the Retina
8
+ monorepo, which imports this package rather than keeping its own copy.
9
+
10
+ The import name is `retina_sdk`, not `retina_api`: the backend's own package is
11
+ already `retina_api`, and the monorepo's test paths hold both.
12
+ """
13
+
14
+ #: The distribution name, in one place. Not final: the owner confirms it before
15
+ #: anything is published. pyproject.toml must agree (a test checks it).
16
+ DIST_NAME = "retina-api"
17
+ __version__ = "0.1.0"
18
+
19
+ from retina_sdk.client import ( # noqa: E402
20
+ OPERATIONS,
21
+ RetinaAPIError,
22
+ RetinaClient,
23
+ RetinaConfigError,
24
+ )
25
+
26
+ __all__ = ["DIST_NAME", "OPERATIONS", "RetinaAPIError", "RetinaClient", "RetinaConfigError", "__version__"]
retina_sdk/cli.py ADDED
@@ -0,0 +1,173 @@
1
+ """`retina ...`: the command line over Retina's public API, on a workspace key.
2
+
3
+ THIS IS A THIN LAYER. Every command is made from one `RetinaClient` method
4
+ (`retina_sdk.client.OPERATIONS`): its name with dashes, its summary as help,
5
+ its parameters as arguments and options, and the spec's fixed values as the
6
+ allowed choices. No path, payload or error rule is written here, so the CLI
7
+ cannot say something the client does not. Retina's own internal command line
8
+ mounts this same app as a subcommand.
9
+
10
+ How a parameter becomes a flag:
11
+ - a path parameter (`post_id`) is a positional argument;
12
+ - a string, number or flag is `--name`;
13
+ - a list of strings is `--name`, repeated;
14
+ - anything else (an object, a list of objects) is `--name` with a JSON value.
15
+
16
+ Output is the API's own JSON on stdout. A failure is one JSON line on stderr
17
+ with the `/v1` error code and exit 1 (`network_error` when the API cannot
18
+ be reached); a missing key or a bad flag is exit 2. A
19
+ streamed completion prints its text to stderr as it arrives.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import inspect
26
+ import json
27
+ import sys
28
+ import types
29
+ import typing
30
+ from typing import Any
31
+
32
+ import httpx
33
+ import typer
34
+
35
+ from retina_sdk.client import (
36
+ OPERATIONS,
37
+ RetinaAPIError,
38
+ RetinaClient,
39
+ RetinaConfigError,
40
+ parameters,
41
+ spec_fields,
42
+ )
43
+
44
+
45
+ def _fail(message: str, *, code: str, hint: str | None = None, exit_code: int = 1) -> typing.NoReturn:
46
+ payload = {"error": message, "code": code, **({"hint": hint} if hint else {})}
47
+ print(json.dumps(payload), file=sys.stderr)
48
+ raise typer.Exit(exit_code)
49
+
50
+
51
+ def _emit(result: Any, jq: str | None) -> None:
52
+ if isinstance(result, str) and not jq:
53
+ # A document (the guide is markdown): print it as it is, not as a JSON string.
54
+ print(result)
55
+ return
56
+ text = json.dumps(result, default=str, indent=2)
57
+ if not jq:
58
+ print(text)
59
+ return
60
+ import subprocess
61
+
62
+ try:
63
+ out = subprocess.run(["jq", jq], input=text, capture_output=True, text=True, check=False)
64
+ except FileNotFoundError:
65
+ _fail("--jq needs the jq binary (https://jqlang.github.io/jq/)", code="misuse", exit_code=2)
66
+ if out.returncode:
67
+ _fail(out.stderr.strip() or "jq failed", code="misuse", exit_code=2)
68
+ print(out.stdout, end="")
69
+
70
+
71
+ app = typer.Typer(
72
+ name="retina",
73
+ help=(
74
+ "Retina's public API on a workspace key. Set RETINA_API_KEY (rk_...), and RETINA_API_BASE to point "
75
+ "elsewhere. Every command is one /v1 call."
76
+ ),
77
+ no_args_is_help=True,
78
+ )
79
+
80
+ #: Test seam: an httpx transport every command's client uses. None is the network.
81
+ TRANSPORT: Any = None
82
+
83
+
84
+ def command_name(operation_name: str) -> str:
85
+ return operation_name.replace("_", "-")
86
+
87
+
88
+ def _kind(annotation: Any) -> str:
89
+ """scalar, list (of strings) or json, from a parameter's type."""
90
+ args = [a for a in typing.get_args(annotation) if a is not type(None)]
91
+ origin = typing.get_origin(annotation)
92
+ if origin in (typing.Union, types.UnionType) and len(args) == 1:
93
+ return _kind(args[0])
94
+ if annotation in (str, int, float, bool):
95
+ return "scalar"
96
+ if origin is list and args == [str]:
97
+ return "list"
98
+ return "json"
99
+
100
+
101
+ def _scalar(annotation: Any) -> Any:
102
+ args = [a for a in typing.get_args(annotation) if a is not type(None)]
103
+ return args[0] if args else annotation
104
+
105
+
106
+ def _client() -> RetinaClient:
107
+ try:
108
+ return RetinaClient.from_env(transport=TRANSPORT,
109
+ on_delta=lambda piece: print(piece, end="", file=sys.stderr, flush=True))
110
+ except RetinaConfigError as e:
111
+ _fail(str(e), code="misuse", hint="Make a key in the console, then `export RETINA_API_KEY=rk_...`.",
112
+ exit_code=2)
113
+
114
+
115
+ def _make_command(name: str) -> None:
116
+ op = OPERATIONS[name]
117
+ params = parameters(name)
118
+ json_params = {p.name for p in params if _kind(p.annotation) == "json"}
119
+ cli_params: list[inspect.Parameter] = []
120
+ for p in params:
121
+ required = p.default is inspect.Parameter.empty
122
+ kind = _kind(p.annotation)
123
+ flag = "--" + p.name.replace("_", "-")
124
+ if p.name in op.path_params:
125
+ default, annotation = typer.Argument(...), str
126
+ elif kind == "scalar":
127
+ annotation = _scalar(p.annotation) if required else _scalar(p.annotation) | None
128
+ choices = (spec_fields(name).get(p.name) or {}).get("enum")
129
+ default = typer.Option(... if required else None, flag,
130
+ help=f"One of: {', '.join(map(str, choices))}." if choices else None)
131
+ elif kind == "list":
132
+ annotation = list[str] if required else list[str] | None
133
+ default = typer.Option(... if required else None, flag, help="Repeat for more than one.")
134
+ else:
135
+ annotation = str if required else str | None
136
+ default = typer.Option(... if required else None, flag, help="JSON.")
137
+ cli_params.append(inspect.Parameter(p.name, inspect.Parameter.KEYWORD_ONLY, default=default,
138
+ annotation=annotation))
139
+ cli_params.append(inspect.Parameter("jq", inspect.Parameter.KEYWORD_ONLY, annotation=str | None,
140
+ default=typer.Option(None, "--jq", help="Filter the JSON through jq.")))
141
+
142
+ def run(**kwargs: Any) -> None:
143
+ jq = kwargs.pop("jq", None)
144
+ for key in json_params & kwargs.keys():
145
+ if kwargs[key] is not None:
146
+ try:
147
+ kwargs[key] = json.loads(kwargs[key])
148
+ except ValueError as e:
149
+ _fail(f"--{key.replace('_', '-')} is not JSON: {e}", code="misuse", exit_code=2)
150
+ client = _client()
151
+ try:
152
+ result = asyncio.run(getattr(client, name)(**kwargs))
153
+ except RetinaAPIError as e:
154
+ _fail(e.message, code=e.code, hint=f"request {e.request_id}" if e.request_id else None)
155
+ except ValueError as e:
156
+ _fail(str(e), code="misuse", exit_code=2)
157
+ except httpx.TransportError as e:
158
+ _fail(f"could not reach {client.base_url}: {e or type(e).__name__}", code="network_error",
159
+ hint="Check the network, and RETINA_API_BASE if you set it.")
160
+ except KeyboardInterrupt:
161
+ print("retina: interrupted", file=sys.stderr)
162
+ sys.exit(130)
163
+ if name == "complete_stream":
164
+ print(file=sys.stderr)
165
+ _emit(result, jq)
166
+
167
+ run.__signature__ = inspect.Signature(cli_params) # type: ignore[attr-defined]
168
+ run.__name__ = name
169
+ app.command(command_name(name), help=op.summary)(run)
170
+
171
+
172
+ for _name in OPERATIONS:
173
+ _make_command(_name)