t4l-server 0.1.0__tar.gz

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,78 @@
1
+ name: Publish Python package
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ target:
7
+ description: "Package index target"
8
+ required: true
9
+ default: "testpypi"
10
+ type: choice
11
+ options:
12
+ - testpypi
13
+ push:
14
+ tags:
15
+ - "v*.*.*"
16
+
17
+ permissions:
18
+ contents: read
19
+
20
+ jobs:
21
+ build:
22
+ name: Build and check package
23
+ runs-on: ubuntu-latest
24
+ steps:
25
+ - uses: actions/checkout@v5
26
+ - uses: actions/setup-python@v6
27
+ with:
28
+ python-version: "3.11"
29
+ - name: Install build dependencies
30
+ run: python -m pip install --upgrade build twine
31
+ - name: Build distributions
32
+ run: python -m build
33
+ - name: Check distributions
34
+ run: twine check dist/*
35
+ - uses: actions/upload-artifact@v5
36
+ with:
37
+ name: dist
38
+ path: dist/*
39
+
40
+ publish-testpypi:
41
+ name: Publish to TestPyPI
42
+ needs: build
43
+ runs-on: ubuntu-latest
44
+ if: github.event_name == 'workflow_dispatch' && inputs.target == 'testpypi'
45
+ environment:
46
+ name: testpypi
47
+ url: https://test.pypi.org/project/t4l-server/
48
+ permissions:
49
+ id-token: write
50
+ contents: read
51
+ steps:
52
+ - uses: actions/download-artifact@v5
53
+ with:
54
+ name: dist
55
+ path: dist
56
+ - name: Publish to TestPyPI
57
+ uses: pypa/gh-action-pypi-publish@release/v1
58
+ with:
59
+ repository-url: https://test.pypi.org/legacy/
60
+
61
+ publish-pypi:
62
+ name: Publish to PyPI
63
+ needs: build
64
+ runs-on: ubuntu-latest
65
+ if: startsWith(github.ref, 'refs/tags/v')
66
+ environment:
67
+ name: pypi
68
+ url: https://pypi.org/project/t4l-server/
69
+ permissions:
70
+ id-token: write
71
+ contents: read
72
+ steps:
73
+ - uses: actions/download-artifact@v5
74
+ with:
75
+ name: dist
76
+ path: dist
77
+ - name: Publish to PyPI
78
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,8 @@
1
+ .mypy_cache/
2
+ .pytest_cache/
3
+ .ruff_cache/
4
+ .venv/
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+ __pycache__/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 T4L Trainer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: t4l-server
3
+ Version: 0.1.0
4
+ Summary: Self-hosted REST and MCP server for T4L Trainer agent workflows.
5
+ Project-URL: Homepage, https://github.com/BigSlikTobi/t4l-server
6
+ Project-URL: Repository, https://github.com/BigSlikTobi/t4l-server
7
+ Project-URL: Issues, https://github.com/BigSlikTobi/t4l-server/issues
8
+ Author: T4L Trainer
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
21
+ Requires-Python: >=3.11
22
+ Provides-Extra: dev
23
+ Requires-Dist: build>=1.3; extra == 'dev'
24
+ Requires-Dist: mypy>=1.18; extra == 'dev'
25
+ Requires-Dist: pytest>=8.0; extra == 'dev'
26
+ Requires-Dist: ruff>=0.14; extra == 'dev'
27
+ Requires-Dist: twine>=6.2; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # T4L Server
31
+
32
+ Self-hosted REST and MCP server for exchanging T4L Trainer JSON artifacts
33
+ between the iPhone app and a coaching agent.
34
+
35
+ The phone remains the source of truth for accepted training state. The server
36
+ stores synced context and pending agent results in SQLite so local agents,
37
+ home-server agents, and private VPS agents can work through the same protocol.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pipx install t4l-server
43
+ t4l-server serve --data-dir ~/T4LServerData
44
+ ```
45
+
46
+ The command prints the server URL, MCP URL, and API key. Enter the server URL
47
+ and API key in the T4L Trainer Settings screen.
48
+
49
+ ## Agent setup
50
+
51
+ Agents should read the public instruction repo first:
52
+
53
+ ```text
54
+ https://github.com/BigSlikTobi/t4l-agent-instructions
55
+ ```
56
+
57
+ Those instructions explain how to start or verify this server, connect through
58
+ MCP, wait for fresh phone context, and write app-consumed results safely.
59
+
60
+ ## Compatibility
61
+
62
+ The old command remains available for one transition cycle:
63
+
64
+ ```bash
65
+ t4l-bridge serve --dir ~/CodexFitnessExchange
66
+ ```
67
+
68
+ New setups should use `t4l-server serve --data-dir ~/T4LServerData`.
69
+
70
+ ## Safety model
71
+
72
+ - REST, MCP, and compatibility file endpoints require the API key.
73
+ - JSON artifacts are stored in `t4l.sqlite`.
74
+ - Image blobs are stored under `blobs/`.
75
+ - Only known exchange files and `meal_images/` are accessible through
76
+ compatibility endpoints.
77
+ - Path traversal and arbitrary file access are rejected.
78
+
79
+ ## Development
80
+
81
+ ```bash
82
+ python -m venv .venv
83
+ . .venv/bin/activate
84
+ python -m pip install -e ".[dev]"
85
+ ruff format --check .
86
+ ruff check .
87
+ mypy
88
+ pytest
89
+ python -m build
90
+ twine check dist/*
91
+ ```
@@ -0,0 +1,62 @@
1
+ # T4L Server
2
+
3
+ Self-hosted REST and MCP server for exchanging T4L Trainer JSON artifacts
4
+ between the iPhone app and a coaching agent.
5
+
6
+ The phone remains the source of truth for accepted training state. The server
7
+ stores synced context and pending agent results in SQLite so local agents,
8
+ home-server agents, and private VPS agents can work through the same protocol.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pipx install t4l-server
14
+ t4l-server serve --data-dir ~/T4LServerData
15
+ ```
16
+
17
+ The command prints the server URL, MCP URL, and API key. Enter the server URL
18
+ and API key in the T4L Trainer Settings screen.
19
+
20
+ ## Agent setup
21
+
22
+ Agents should read the public instruction repo first:
23
+
24
+ ```text
25
+ https://github.com/BigSlikTobi/t4l-agent-instructions
26
+ ```
27
+
28
+ Those instructions explain how to start or verify this server, connect through
29
+ MCP, wait for fresh phone context, and write app-consumed results safely.
30
+
31
+ ## Compatibility
32
+
33
+ The old command remains available for one transition cycle:
34
+
35
+ ```bash
36
+ t4l-bridge serve --dir ~/CodexFitnessExchange
37
+ ```
38
+
39
+ New setups should use `t4l-server serve --data-dir ~/T4LServerData`.
40
+
41
+ ## Safety model
42
+
43
+ - REST, MCP, and compatibility file endpoints require the API key.
44
+ - JSON artifacts are stored in `t4l.sqlite`.
45
+ - Image blobs are stored under `blobs/`.
46
+ - Only known exchange files and `meal_images/` are accessible through
47
+ compatibility endpoints.
48
+ - Path traversal and arbitrary file access are rejected.
49
+
50
+ ## Development
51
+
52
+ ```bash
53
+ python -m venv .venv
54
+ . .venv/bin/activate
55
+ python -m pip install -e ".[dev]"
56
+ ruff format --check .
57
+ ruff check .
58
+ mypy
59
+ pytest
60
+ python -m build
61
+ twine check dist/*
62
+ ```
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "t4l-server"
7
+ version = "0.1.0"
8
+ description = "Self-hosted REST and MCP server for T4L Trainer agent workflows."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ authors = [{ name = "T4L Trainer" }]
13
+ dependencies = []
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: End Users/Desktop",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/BigSlikTobi/t4l-server"
29
+ Repository = "https://github.com/BigSlikTobi/t4l-server"
30
+ Issues = "https://github.com/BigSlikTobi/t4l-server/issues"
31
+
32
+ [project.optional-dependencies]
33
+ dev = [
34
+ "build>=1.3",
35
+ "mypy>=1.18",
36
+ "pytest>=8.0",
37
+ "ruff>=0.14",
38
+ "twine>=6.2",
39
+ ]
40
+
41
+ [project.scripts]
42
+ t4l-server = "t4l_server.cli:main"
43
+ t4l-bridge = "t4l_server.cli:_bridge_main"
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/t4l_server"]
47
+
48
+ [tool.ruff]
49
+ line-length = 88
50
+ target-version = "py311"
51
+
52
+ [tool.ruff.lint]
53
+ select = ["E", "F", "I", "UP", "B", "SIM"]
54
+
55
+ [tool.mypy]
56
+ python_version = "3.11"
57
+ strict = true
58
+ files = ["src", "tests"]
@@ -0,0 +1,5 @@
1
+ """Self-hosted REST and MCP server for T4L Trainer."""
2
+
3
+ __all__ = ["__version__"]
4
+
5
+ __version__ = "0.1.0"
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import secrets
5
+ import socket
6
+ from pathlib import Path
7
+
8
+ from .server import ServerConfig, run_server
9
+
10
+
11
+ def main(argv: list[str] | None = None) -> int:
12
+ parser = argparse.ArgumentParser(prog="t4l-server")
13
+ subparsers = parser.add_subparsers(dest="command", required=True)
14
+
15
+ serve = subparsers.add_parser("serve", help="Start the self-hosted T4L server.")
16
+ serve.add_argument(
17
+ "--data-dir",
18
+ type=Path,
19
+ help="Server data directory. Stores t4l.sqlite and blobs.",
20
+ )
21
+ serve.add_argument(
22
+ "--dir",
23
+ type=Path,
24
+ help="Compatibility alias for --data-dir.",
25
+ )
26
+ serve.add_argument("--host", default="0.0.0.0", help="Bind host.")
27
+ serve.add_argument("--port", default=8787, type=int, help="Bind port.")
28
+ serve.add_argument(
29
+ "--api-key",
30
+ default=None,
31
+ help="API key. Defaults to a new key for every start.",
32
+ )
33
+ serve.add_argument(
34
+ "--token",
35
+ default=None,
36
+ help="Compatibility alias for --api-key.",
37
+ )
38
+
39
+ args = parser.parse_args(argv)
40
+ if args.command == "serve":
41
+ data_dir = args.data_dir or args.dir
42
+ if data_dir is None:
43
+ parser.error("serve requires --data-dir")
44
+ token = args.api_key or args.token or _new_api_key()
45
+ config = ServerConfig(
46
+ exchange_dir=data_dir.expanduser().resolve(),
47
+ host=args.host,
48
+ port=args.port,
49
+ token=token,
50
+ )
51
+ _print_startup(config)
52
+ run_server(config)
53
+ return 0
54
+ return 1
55
+
56
+
57
+ def _bridge_main(argv: list[str] | None = None) -> int:
58
+ if argv is None:
59
+ import sys
60
+
61
+ argv = sys.argv[1:]
62
+ translated = ["serve" if item == "serve" else item for item in argv]
63
+ if "--data-dir" not in translated and "--dir" in translated:
64
+ # The parser accepts --dir directly; this keeps the old command shape.
65
+ pass
66
+ return main(translated)
67
+
68
+
69
+ def _new_api_key() -> str:
70
+ return secrets.token_urlsafe(24)
71
+
72
+
73
+ def _print_startup(config: ServerConfig) -> None:
74
+ lan_host = _lan_ip() if config.host in {"0.0.0.0", "::"} else config.host
75
+ print("T4L Self-Hosted Server")
76
+ print(f"Data dir: {config.data_dir}")
77
+ print(f"Server URL: http://{lan_host}:{config.port}")
78
+ print(f"MCP URL: http://{lan_host}:{config.port}/mcp")
79
+ print(f"API key: {config.token}")
80
+ print("Enter the server URL and API key in the T4L Trainer Settings screen.")
81
+
82
+
83
+ def _lan_ip() -> str:
84
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
85
+ try:
86
+ sock.connect(("8.8.8.8", 80))
87
+ return str(sock.getsockname()[0])
88
+ except OSError:
89
+ return "127.0.0.1"
90
+
91
+
92
+ if __name__ == "__main__":
93
+ raise SystemExit(main())
@@ -0,0 +1,154 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from . import __version__
6
+ from .store import Artifact, ArtifactStore
7
+
8
+
9
+ def handle_mcp_message(store: ArtifactStore, message: dict[str, Any]) -> dict[str, Any]:
10
+ method = str(message.get("method") or "")
11
+ request_id = message.get("id")
12
+ if method == "initialize":
13
+ return _result(
14
+ request_id,
15
+ {
16
+ "protocolVersion": "2025-06-18",
17
+ "serverInfo": {"name": "t4l-server", "version": __version__},
18
+ "capabilities": {"tools": {}},
19
+ },
20
+ )
21
+ if method == "tools/list":
22
+ return _result(request_id, {"tools": _tools()})
23
+ if method == "tools/call":
24
+ params = message.get("params")
25
+ if not isinstance(params, dict):
26
+ return _error(request_id, -32602, "Invalid params.")
27
+ return _call_tool(store, request_id, params)
28
+ return _error(request_id, -32601, f"Unsupported MCP method: {method}")
29
+
30
+
31
+ def _call_tool(
32
+ store: ArtifactStore,
33
+ request_id: object,
34
+ params: dict[str, Any],
35
+ ) -> dict[str, Any]:
36
+ name = str(params.get("name") or "")
37
+ arguments = params.get("arguments")
38
+ args = arguments if isinstance(arguments, dict) else {}
39
+ if name == "get_day_context":
40
+ return _artifact_result(request_id, store.latest("day_context"))
41
+ if name == "get_app_snapshot":
42
+ return _artifact_result(request_id, store.latest("app_snapshot"))
43
+ if name == "get_profile":
44
+ return _artifact_result(request_id, store.latest("athlete_profile"))
45
+ if name == "get_pending_requests":
46
+ return _payload_result(
47
+ request_id,
48
+ {
49
+ "requests": [
50
+ artifact.summary()
51
+ for artifact in [
52
+ store.latest("training_block_request"),
53
+ store.latest("nutrition_analysis_request"),
54
+ ]
55
+ if artifact is not None
56
+ ]
57
+ },
58
+ )
59
+ write_kinds = {
60
+ "write_training_block_plan": "training_block_plan",
61
+ "write_fuel_guidance": "fuel_guidance",
62
+ "write_nutrition_analysis_result": "nutrition_analysis_result",
63
+ }
64
+ if name in write_kinds:
65
+ payload = args.get("payload")
66
+ if not isinstance(payload, dict):
67
+ return _error(request_id, -32602, "Tool requires object argument: payload.")
68
+ artifact = store.upsert_artifact(write_kinds[name], payload, status="pending")
69
+ return _payload_result(request_id, {"stored": artifact.summary()})
70
+ return _error(request_id, -32602, f"Unknown tool: {name}")
71
+
72
+
73
+ def _artifact_result(request_id: object, artifact: Artifact | None) -> dict[str, Any]:
74
+ if artifact is None:
75
+ return _payload_result(request_id, None)
76
+ return _payload_result(request_id, artifact.payload)
77
+
78
+
79
+ def _payload_result(request_id: object, payload: object) -> dict[str, Any]:
80
+ return _result(
81
+ request_id,
82
+ {
83
+ "content": [
84
+ {
85
+ "type": "text",
86
+ "text": _json_text(payload),
87
+ }
88
+ ],
89
+ "structuredContent": payload,
90
+ },
91
+ )
92
+
93
+
94
+ def _json_text(payload: object) -> str:
95
+ import json
96
+
97
+ return json.dumps(payload, ensure_ascii=False, indent=2)
98
+
99
+
100
+ def _tools() -> list[dict[str, Any]]:
101
+ object_schema = {
102
+ "type": "object",
103
+ "properties": {"payload": {"type": "object"}},
104
+ "required": ["payload"],
105
+ }
106
+ return [
107
+ {
108
+ "name": "get_day_context",
109
+ "description": "Read latest day context.",
110
+ "inputSchema": {"type": "object"},
111
+ },
112
+ {
113
+ "name": "get_app_snapshot",
114
+ "description": "Read latest full app snapshot.",
115
+ "inputSchema": {"type": "object"},
116
+ },
117
+ {
118
+ "name": "get_profile",
119
+ "description": "Read latest athlete profile.",
120
+ "inputSchema": {"type": "object"},
121
+ },
122
+ {
123
+ "name": "get_pending_requests",
124
+ "description": "List pending app requests.",
125
+ "inputSchema": {"type": "object"},
126
+ },
127
+ {
128
+ "name": "write_training_block_plan",
129
+ "description": "Write a pending training block plan.",
130
+ "inputSchema": object_schema,
131
+ },
132
+ {
133
+ "name": "write_fuel_guidance",
134
+ "description": "Write pending fuel guidance.",
135
+ "inputSchema": object_schema,
136
+ },
137
+ {
138
+ "name": "write_nutrition_analysis_result",
139
+ "description": "Write a pending nutrition result.",
140
+ "inputSchema": object_schema,
141
+ },
142
+ ]
143
+
144
+
145
+ def _result(request_id: object, result: dict[str, Any]) -> dict[str, Any]:
146
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
147
+
148
+
149
+ def _error(request_id: object, code: int, message: str) -> dict[str, Any]:
150
+ return {
151
+ "jsonrpc": "2.0",
152
+ "id": request_id,
153
+ "error": {"code": code, "message": message},
154
+ }