agent2drive 0.4.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,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent2drive
3
+ Version: 0.4.0
4
+ Summary: One command connects an agent to Google Drive; one command per verified, reviewable upload (optional MCP server).
5
+ Author-email: Ansari Bilal <ansaribilal0709@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Ansari Bilal
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/Bilal140202/agent2drive
29
+ Project-URL: Repository, https://github.com/Bilal140202/agent2drive
30
+ Project-URL: Issues, https://github.com/Bilal140202/agent2drive/issues
31
+ Keywords: google-drive,agent,oauth,rclone,deliverables,mcp
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Environment :: Console
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3 :: Only
38
+ Classifier: Topic :: Utilities
39
+ Requires-Python: >=3.10
40
+ Description-Content-Type: text/markdown
41
+ License-File: LICENSE
42
+ Requires-Dist: cryptography>=41
43
+ Provides-Extra: mcp
44
+ Requires-Dist: mcp>=1.0; extra == "mcp"
45
+ Provides-Extra: dev
46
+ Requires-Dist: pytest>=7; extra == "dev"
47
+ Requires-Dist: build>=1; extra == "dev"
48
+ Dynamic: license-file
49
+
50
+ # agent2drive
51
+
52
+ **One command connects an agent to your Google Drive. One command per upload. That's the whole product.**
53
+
54
+ An agent writes files locally; you review them in Drive. No video-generation model, no stock footage, no public redirect server, no broad Drive access — just a narrow `drive.file` scope and a paste-back OAuth code.
55
+
56
+ ## Install
57
+
58
+ ```sh
59
+ pipx install agent2drive # recommended
60
+ # or
61
+ python3 -m pip install --user agent2drive
62
+ ```
63
+
64
+ One-line bootstrap for an agent to run for you:
65
+
66
+ ```sh
67
+ curl -fsSL https://raw.githubusercontent.com/Bilal140202/agent2drive/main/install.sh | sh
68
+ ```
69
+
70
+ See [AGENT_SETUP.md](AGENT_SETUP.md) for the exact prompt to give an agent; [skills/agent2drive/SKILL.md](skills/agent2drive/SKILL.md) is a drop-in skill for OpenCode/Claude-style agents.
71
+
72
+ ## Connect (one time)
73
+
74
+ Using your own OAuth client is strongly recommended — rclone's shared public client is being retired during 2026. Create a Desktop OAuth client in Google Cloud with redirect URI `http://127.0.0.1:53682/`, then:
75
+
76
+ ```sh
77
+ agent2drive client <client_id> <client_secret> # stored chmod 600, gitignored
78
+ agent2drive url
79
+ ```
80
+
81
+ 1. Give the user the printed consent URL.
82
+ 2. They click **Allow**. Google may warn " hasn't verified this app" → **Advanced → Go to rclone (unsafe) → Allow**.
83
+ 3. The browser fails to load `127.0.0.1:53682`. **That failure is expected** — it only runs on the user's machine. They copy the full address-bar URL and paste it back.
84
+ 4. You exchange it immediately (single-use, ~10-minute TTL):
85
+
86
+ ```sh
87
+ agent2drive connect '<PASTED_URL>'
88
+ # or: agent2drive connect --stdin (safer: keeps the code out of shell history)
89
+ agent2drive status
90
+ ```
91
+
92
+ If you skip `client`, the tool falls back to deriving rclone's published default client from its own binary. It works today but is rate-limit-prone and will stop working when Google retires that client.
93
+
94
+ ## Commands
95
+
96
+ | Command | What it does |
97
+ | --- | --- |
98
+ | `status` | Live token check (`AUTH_OK` / `AUTH_MISSING`, exit 0/2) |
99
+ | `url` | Print the consent URL and store a one-time state nonce |
100
+ | `client [ID] [SECRET]` | Set your own OAuth client (prompts if omitted) |
101
+ | `connect [URL]` / `connect --stdin` | Exchange the pasted redirect URL |
102
+ | `init <slot>` | Create a slot root and `MANIFEST.md` |
103
+ | `upload <slot> <file> [folder] [--replace]` | Upload, verify, and log to the manifest |
104
+ | `ls <slot>` | List everything in a slot |
105
+ | `manifest <slot>` | Print the delivery manifest |
106
+
107
+ ## Verified uploads — not just size
108
+
109
+ The original release claimed "byte-exact verification" but only compared file sizes. Now every upload is checked three ways:
110
+
111
+ - **size** from `rclone lsjson`
112
+ - **MD5** and **SHA-1** from `rclone hashsum` (both natively supported by Google Drive)
113
+
114
+ A mismatch deletes the remote copy, fails loudly, and writes nothing to the manifest. If hashes can't be read, the manifest records `SIZE-ONLY` and the command exits non-zero. These hashes detect accidental corruption; they are not a cryptographic authenticity guarantee.
115
+
116
+ Same-name uploads **fail by default**. Pass `--replace` to overwrite deliberately, so a reviewer isn't silently robbed of an earlier draft.
117
+
118
+ ## Slots and the manifest
119
+
120
+ Everything lives under one root (default `AgentDeliveries`, override with `GDRIVE_ROOT`), one folder per project:
121
+
122
+ ```
123
+ AgentDeliveries/
124
+ <slot>/
125
+ MANIFEST.md
126
+ <your folders>/ created on demand; one component, no traversal
127
+ ```
128
+
129
+ `init` creates only the slot root and manifest — no imposed category tree. Every successful upload appends a row with UTC time, filename, folder, bytes, MD5, SHA-1, and result. That gives you an audit trail of what the agent delivered and when. Slot names are restricted to lowercase letters, digits and hyphens; path traversal is rejected.
130
+
131
+ ## Self-restoring, cross-platform
132
+
133
+ A missing or wrong-architecture rclone binary is re-downloaded for the current platform (`linux-amd64`, `linux-arm64`, `osx-*`, `windows-*`), architecture-checked, and smoke-tested before use. Override with `RCLONE_ZIP=<url>` for unusual platforms.
134
+
135
+ The refresh token in `state/rclone/rclone.conf` (chmod 600, gitignored) is the only thing that can't be rebuilt. Lose it and one fresh consent click restores everything; nothing already on Drive is affected.
136
+
137
+ State lives beside the source in a checkout, and in `~/.config/agent2drive/` for a pip/pixi install (override with `A2D_HOME`, or `XDG_CONFIG_HOME`). Nothing is ever written into `site-packages`.
138
+
139
+ ## Security
140
+
141
+ - Scope is `drive.file`: the agent can only see files it created itself.
142
+ - `state/`, `bin/`, and `.tmp/` are gitignored; tokens and OAuth client secrets are chmod 600 and never printed.
143
+ - The OAuth `state` nonce is random, stored locally, and checked on `connect` (15-minute TTL).
144
+ - Prefer `connect --stdin` so single-use codes don't land in shell history.
145
+ - Revoke access any time at <https://myaccount.google.com/> → Security → Third-party apps → rclone.
146
+
147
+ ## MCP server
148
+
149
+ Available from 0.4.0:
150
+
151
+ ```sh
152
+ pipx install 'agent2drive[mcp]'
153
+ opencode mcp add agent2drive -- agent2drive-mcp
154
+ ```
155
+
156
+ Eight tools (`a2d_status`, `a2d_set_client`, `a2d_consent_url`, `a2d_connect`, `a2d_init_slot`, `a2d_upload`, `a2d_list`, `a2d_manifest`), two resources, and a `deliver-file` prompt. stdio only; path allowlisting (`A2D_ALLOWED_ROOTS`), overwrite confirmation, and secret redaction are built in. Full setup and security details: [docs/MCP.md](docs/MCP.md).
157
+
158
+ ## Development
159
+
160
+ ```sh
161
+ python3 -m pip install -r requirements-dev.txt
162
+ python3 -m pytest -q
163
+ ```
164
+
165
+ Tests cover pure logic plus injected-rclone failure paths (hash mismatch, missing hashes, collisions, retries, state replay, and the post-connect crash regression).
166
+
167
+ ## License
168
+
169
+ MIT. rclone is MIT-licensed; its published OAuth constants are used and credited per its license.
@@ -0,0 +1,8 @@
1
+ agent2drive.py,sha256=2qPuYugaY3oAlvma9QcQrY3JHPIDjghYG5EE-TapD1M,24857
2
+ agent2drive_mcp.py,sha256=Lf6vtPBrY97rN8IZrP5hllYOF1sXA9LSQq2n4qBuThY,7991
3
+ agent2drive-0.4.0.dist-info/licenses/LICENSE,sha256=FwCS904_nQ-H1C1TpsAtbtkautPiEOkmp00lcaVaUI8,1069
4
+ agent2drive-0.4.0.dist-info/METADATA,sha256=Pme18Op7aJzMWAqQMQAeBts2a09FVOl0HqL40GNt5mE,8173
5
+ agent2drive-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ agent2drive-0.4.0.dist-info/entry_points.txt,sha256=uGUu61GENfqfatWcT1DtBt8jmOCLb8xTOlE7rUl7Sr4,87
7
+ agent2drive-0.4.0.dist-info/top_level.txt,sha256=SvuzyYPxg-ePYq8aeWdpDINFqwGybWyKOEAQ0NH5orw,28
8
+ agent2drive-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ agent2drive = agent2drive:cli
3
+ agent2drive-mcp = agent2drive_mcp:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ansari Bilal
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,2 @@
1
+ agent2drive
2
+ agent2drive_mcp
agent2drive.py ADDED
@@ -0,0 +1,669 @@
1
+ #!/usr/bin/env python3
2
+ """agent2drive — connect an agent to the user's Google Drive, and upload
3
+ reviewable deliverables one command at a time.
4
+
5
+ agent2drive # status / connect recipe
6
+ agent2drive status
7
+ agent2drive url # print the consent URL
8
+ agent2drive client [ID] [SECRET] # use your own OAuth client (recommended)
9
+ agent2drive connect [PASTED_URL] # exchange the pasted redirect URL
10
+ agent2drive init <slot> # slot root + MANIFEST.md
11
+ agent2drive upload <slot> <file> [folder] [--replace]
12
+ agent2drive ls <slot>
13
+ agent2drive manifest <slot>
14
+
15
+ The paste-back OAuth flow keeps the redirect on the user's machine; the
16
+ agent only ever sees a single-use code. Scope is drive.file (least
17
+ privilege). Tokens are written to state/rclone/rclone.conf (chmod 600),
18
+ which is gitignored and never printed.
19
+
20
+ Self-restoring: a missing or wrong-architecture rclone binary is
21
+ re-downloaded for the current platform. Only the refresh token is
22
+ irreplaceable — losing it means one fresh consent click, and nothing on
23
+ Drive is affected.
24
+ """
25
+ import argparse
26
+ import base64
27
+ import binascii
28
+ import getpass
29
+ import hashlib
30
+ import json
31
+ import os
32
+ import platform
33
+ import re
34
+ import secrets
35
+ import subprocess
36
+ import sys
37
+ import time
38
+ import urllib.error
39
+ import urllib.parse
40
+ import urllib.request
41
+ import zipfile
42
+ from pathlib import Path
43
+
44
+ BASE = Path(__file__).resolve().parent
45
+
46
+
47
+ def _default_home():
48
+ """Source checkouts keep state beside the code; pip installs use XDG."""
49
+ override = os.environ.get("A2D_HOME")
50
+ if override:
51
+ return Path(override).expanduser()
52
+ if (BASE / "pyproject.toml").exists():
53
+ return BASE
54
+ config = os.environ.get("XDG_CONFIG_HOME")
55
+ root = Path(config).expanduser() if config else Path.home() / ".config"
56
+ return root / "agent2drive"
57
+
58
+
59
+ HOME = _default_home()
60
+ STATE = HOME / "state/rclone"
61
+ CONF = STATE / "rclone.conf"
62
+ CLIENT = STATE / "client.json"
63
+ OAUTH_STATE = STATE / "oauth_state.json"
64
+ BIN = HOME / ("bin/rclone.exe" if os.name == "nt" else "bin/rclone")
65
+ STAGING = HOME / ".tmp/rclone-selfrestore"
66
+ ROOT = os.environ.get("GDRIVE_ROOT", "AgentDeliveries")
67
+
68
+ REDIRECT = "http://127.0.0.1:53682/"
69
+ SCOPE = "https://www.googleapis.com/auth/drive.file"
70
+ TOKEN_URL = "https://oauth2.googleapis.com/token"
71
+ STATE_TTL = 15 * 60 # seconds; OAuth codes expire in ~10 minutes
72
+
73
+ # rclone's published default OAuth client (open source constants, not secrets).
74
+ # Prefer your own client via `agent2drive client` — see README.
75
+ CID_PREFIX = "202264815644-"
76
+ OBS_PREFIX = "eX8GpZTV"
77
+ AES_KEY = bytes([
78
+ 0x9c, 0x93, 0x5b, 0x48, 0x73, 0x0a, 0x55, 0x4d,
79
+ 0x6b, 0xfd, 0x7c, 0x63, 0xc8, 0x86, 0xa9, 0x2b,
80
+ 0xd3, 0x90, 0x19, 0x8e, 0xb8, 0x12, 0x8a, 0xfb,
81
+ 0xf4, 0xde, 0x16, 0x2b, 0x8b, 0x95, 0xf6, 0x38,
82
+ ])
83
+
84
+ _ARCH = {
85
+ "x86_64": "amd64", "amd64": "amd64", "i386": "386", "i686": "386",
86
+ "aarch64": "arm64", "arm64": "arm64",
87
+ }
88
+
89
+
90
+ # ---------------------------------------------------------------- platform
91
+ def platform_suffix():
92
+ """rclone download suffix for this machine, e.g. linux-arm64."""
93
+ system = platform.system().lower()
94
+ arch = _ARCH.get(platform.machine().lower())
95
+ if not arch:
96
+ raise SystemExit(f"[agent2drive] unsupported CPU: "
97
+ f"{platform.machine()!r} — set RCLONE_ZIP to a "
98
+ "rclone zip URL for your platform")
99
+ if system == "linux":
100
+ return f"linux-{arch}"
101
+ if system == "darwin":
102
+ return f"osx-{arch}"
103
+ if system == "windows":
104
+ return f"windows-{arch}"
105
+ raise SystemExit(f"[agent2drive] unsupported OS: {system!r}")
106
+
107
+
108
+ def rclone_zip_url():
109
+ override = os.environ.get("RCLONE_ZIP")
110
+ return override or ("https://downloads.rclone.org/"
111
+ f"rclone-current-{platform_suffix()}.zip")
112
+
113
+
114
+ RCLONE_ZIP = rclone_zip_url() # kept for compatibility; use rclone_zip_url()
115
+
116
+
117
+ def _expected_arch_tokens():
118
+ arch = _ARCH.get(platform.machine().lower(), "")
119
+ if arch == "arm64":
120
+ return ("aarch64", "arm64")
121
+ if arch == "amd64":
122
+ return ("x86-64", "x86_64", "amd64")
123
+ return ()
124
+
125
+
126
+ def _binary_ok(path):
127
+ """Reject a cached/downloaded binary for the wrong CPU."""
128
+ if os.name == "nt":
129
+ return True
130
+ try:
131
+ out = subprocess.run(["file", "-b", str(path)],
132
+ capture_output=True, text=True,
133
+ timeout=15).stdout.lower()
134
+ except (OSError, subprocess.TimeoutExpired):
135
+ return True # no `file` available: fall back to the version probe
136
+ tokens = _expected_arch_tokens()
137
+ return not tokens or any(t in out for t in tokens)
138
+
139
+
140
+ def _runs(path):
141
+ try:
142
+ return subprocess.run([str(path), "version"], capture_output=True,
143
+ timeout=20).returncode == 0
144
+ except (OSError, subprocess.TimeoutExpired):
145
+ return False
146
+
147
+
148
+ # ---------------------------------------------------------------- restore
149
+ def _ensure_rclone():
150
+ if BIN.exists() and _binary_ok(BIN) and _runs(BIN):
151
+ return BIN
152
+ if BIN.exists():
153
+ print("[agent2drive] cached rclone is unusable or wrong-architecture "
154
+ "- replacing it")
155
+ BIN.unlink()
156
+ print(f"[agent2drive] rclone missing - restoring for "
157
+ f"{platform_suffix() if not os.environ.get('RCLONE_ZIP') else 'RCLONE_ZIP'}…")
158
+ STAGING.mkdir(parents=True, exist_ok=True)
159
+ zip_path = STAGING / "rclone.zip"
160
+ req = urllib.request.Request(rclone_zip_url(),
161
+ headers={"User-Agent": "agent2drive/0.3.0"})
162
+ with urllib.request.urlopen(req, timeout=300) as r:
163
+ zip_path.write_bytes(r.read())
164
+ with zipfile.ZipFile(zip_path) as z:
165
+ suffix = "/rclone.exe" if os.name == "nt" else "/rclone"
166
+ member = next(n for n in z.namelist() if n.endswith(suffix))
167
+ data = z.read(member)
168
+ BIN.parent.mkdir(parents=True, exist_ok=True)
169
+ tmp = BIN.with_suffix(".new")
170
+ tmp.write_bytes(data)
171
+ tmp.chmod(0o755)
172
+ if not _binary_ok(tmp) or not _runs(tmp):
173
+ tmp.unlink()
174
+ raise SystemExit("[agent2drive] downloaded rclone failed its "
175
+ "architecture/startup check — check RCLONE_ZIP")
176
+ tmp.replace(BIN)
177
+ print(f"[agent2drive] restored {BIN}")
178
+ return BIN
179
+
180
+
181
+ def _rc(*args, timeout=900, check=True, stdin_data=None, retries=0):
182
+ """Single choke point for every rclone call (also makes tests easy)."""
183
+ _ensure_rclone()
184
+ last = None
185
+ for attempt in range(retries + 1):
186
+ try:
187
+ p = subprocess.run([str(BIN), "--config", str(CONF), *args],
188
+ capture_output=True, text=True,
189
+ timeout=timeout, input=stdin_data)
190
+ except subprocess.TimeoutExpired:
191
+ last = RuntimeError(f"rclone {' '.join(args[:2])} timed out "
192
+ f"after {timeout}s")
193
+ except OSError as e:
194
+ last = RuntimeError(f"cannot run rclone: {e}")
195
+ else:
196
+ if not check or p.returncode == 0:
197
+ return p
198
+ last = RuntimeError(f"rclone {' '.join(args[:2])} failed: "
199
+ f"{p.stderr.strip()[-400:]}")
200
+ if attempt < retries:
201
+ time.sleep(2 ** attempt)
202
+ raise last
203
+
204
+
205
+ # ------------------------------------------------------- OAuth client
206
+ def reveal(obscured):
207
+ """Reverse rclone's 'obscure' encoding (AES-256-CTR, base64url)."""
208
+ if len(obscured) % 4 == 1:
209
+ return None
210
+ try:
211
+ raw = base64.urlsafe_b64decode(obscured + "=" * (-len(obscured) % 4))
212
+ except (ValueError, binascii.Error):
213
+ return None
214
+ if not 16 <= len(raw) <= 120:
215
+ return None
216
+ from cryptography.hazmat.primitives.ciphers import ( # noqa: PLC0415
217
+ Cipher, algorithms, modes)
218
+ enc = Cipher(algorithms.AES(AES_KEY), modes.CTR(raw[:16])).encryptor()
219
+ out = bytes(enc.update(raw[16:]) + enc.finalize())
220
+ try:
221
+ return out.decode("utf-8", "strict")
222
+ except UnicodeDecodeError:
223
+ return None
224
+
225
+
226
+ def _binary_strings():
227
+ _ensure_rclone()
228
+ return subprocess.run(["strings", "-a", str(BIN)],
229
+ capture_output=True, text=True).stdout
230
+
231
+
232
+ def _client_secret_from_binary(client_id):
233
+ """Last-resort fallback: derive rclone's public default client secret."""
234
+ out = _binary_strings()
235
+ lines = out.splitlines()
236
+ tok_re = re.compile(r"[A-Za-z0-9_\-]{40,}")
237
+ budget = 300_000
238
+ seen, cands = set(), []
239
+ for s in lines:
240
+ for tok in tok_re.findall(s):
241
+ for end in range(len(tok), 39, -1):
242
+ if budget <= 0:
243
+ break
244
+ budget -= 1
245
+ pt = reveal(tok[:end])
246
+ if (pt and 20 <= len(pt) <= 60 and pt.isprintable()
247
+ and " " not in pt and pt not in seen):
248
+ seen.add(pt)
249
+ cands.append(pt)
250
+ cands.sort(key=len)
251
+ for cand in cands:
252
+ if _google_accepts_client(client_id, cand):
253
+ return cand
254
+ raise SystemExit("[agent2drive] could not derive the OAuth client "
255
+ "secret from the rclone binary — run `agent2drive "
256
+ "client <id> <secret>` with your own client instead")
257
+
258
+
259
+ def _google_accepts_client(client_id, secret):
260
+ data = urllib.parse.urlencode({
261
+ "code": "4/0INVALID-on-purpose", "client_id": client_id,
262
+ "client_secret": secret, "redirect_uri": REDIRECT,
263
+ "grant_type": "authorization_code"}).encode()
264
+ req = urllib.request.Request(TOKEN_URL, data=data, method="POST")
265
+ try:
266
+ with urllib.request.urlopen(req, timeout=30) as r:
267
+ body = r.read().decode()
268
+ except urllib.error.HTTPError as e:
269
+ body = e.read().decode()
270
+ except Exception:
271
+ return False
272
+ return "invalid_grant" in body # client auth passed, code rejected
273
+
274
+
275
+ def load_client():
276
+ if CLIENT.exists():
277
+ try:
278
+ d = json.loads(CLIENT.read_text())
279
+ if d["client_id"] and d["client_secret"]:
280
+ return d["client_id"], d["client_secret"]
281
+ except (ValueError, KeyError, OSError):
282
+ print("[agent2drive] client.json is unreadable; deriving again")
283
+ out = _binary_strings()
284
+ cid_re = re.compile(r"[0-9A-Za-z_\-]{20,}\.apps\.googleusercontent\.com")
285
+ m = cid_re.search(out)
286
+ if not m:
287
+ raise SystemExit("[agent2drive] client id not found in binary — "
288
+ "run `agent2drive client <id> <secret>`")
289
+ client_id = m.group(0)
290
+ print(f"[agent2drive] deriving shared OAuth client ({client_id[:24]}…) — "
291
+ "rclone's shared client is being retired; set your own with "
292
+ "`agent2drive client`")
293
+ secret = _client_secret_from_binary(client_id)
294
+ set_client(client_id, secret)
295
+ return client_id, secret
296
+
297
+
298
+ def set_client(client_id, secret):
299
+ if not client_id or not secret or not isinstance(client_id, str) \
300
+ or not isinstance(secret, str):
301
+ raise SystemExit("[agent2drive] both client id and secret are required")
302
+ STATE.mkdir(parents=True, exist_ok=True)
303
+ CLIENT.write_text(json.dumps({"client_id": client_id.strip(),
304
+ "client_secret": secret.strip()}))
305
+ CLIENT.chmod(0o600)
306
+ print("[agent2drive] CLIENT_WRITTEN (chmod 600)")
307
+
308
+
309
+ # ------------------------------------------------------------ OAuth flow
310
+ def new_oauth_state():
311
+ """Generate and store a one-time nonce for the paste-back flow."""
312
+ token = secrets.token_urlsafe(24)
313
+ STATE.mkdir(parents=True, exist_ok=True)
314
+ OAUTH_STATE.write_text(json.dumps({"state": token, "ts": time.time()}))
315
+ OAUTH_STATE.chmod(0o600)
316
+ return token
317
+
318
+
319
+ def check_oauth_state(pasted):
320
+ """Verify the state in the pasted redirect; allow bare codes with warning."""
321
+ m = re.search(r"[?&]state=([^&]+)", pasted or "")
322
+ if not m:
323
+ print("[agent2drive] warning: no state in pasted text (bare code "
324
+ "accepted for compatibility)")
325
+ return True
326
+ pasted_state = urllib.parse.unquote(m.group(1))
327
+ try:
328
+ saved = json.loads(OAUTH_STATE.read_text())
329
+ ok = (saved.get("state") == pasted_state
330
+ and time.time() - saved.get("ts", 0) < STATE_TTL)
331
+ except (OSError, ValueError, TypeError):
332
+ ok = False
333
+ if not ok:
334
+ raise SystemExit("[agent2drive] OAuth state mismatch or expired — "
335
+ "run `agent2drive url` again and paste the fresh "
336
+ "redirect")
337
+ OAUTH_STATE.unlink(missing_ok=True)
338
+ return True
339
+
340
+
341
+ def consent_url(client_id, state=None):
342
+ state = state if state is not None else "agent2drive"
343
+ return "https://accounts.google.com/o/oauth2/v2/auth?" + \
344
+ urllib.parse.urlencode({
345
+ "client_id": client_id, "redirect_uri": REDIRECT,
346
+ "response_type": "code", "scope": SCOPE,
347
+ "access_type": "offline", "prompt": "consent", "state": state})
348
+
349
+
350
+ def parse_code(pasted):
351
+ m = re.search(r"[?&]code=([^&]+)", pasted or "")
352
+ code = urllib.parse.unquote(m.group(1)) if m else (pasted or "").strip()
353
+ code = code.strip().strip("'\"")
354
+ if not code:
355
+ raise SystemExit("[agent2drive] no code found in the pasted text")
356
+ return code
357
+
358
+
359
+ def exchange(pasted):
360
+ """Single-use OAuth code -> refresh token -> rclone.conf (chmod 600)."""
361
+ check_oauth_state(pasted)
362
+ client_id, client_secret = load_client()
363
+ data = urllib.parse.urlencode({
364
+ "code": parse_code(pasted), "client_id": client_id,
365
+ "client_secret": client_secret, "redirect_uri": REDIRECT,
366
+ "grant_type": "authorization_code"}).encode()
367
+ req = urllib.request.Request(TOKEN_URL, data=data, method="POST")
368
+ try:
369
+ with urllib.request.urlopen(req, timeout=60) as r:
370
+ tok = json.loads(r.read())
371
+ except urllib.error.HTTPError as e:
372
+ raise SystemExit(f"[agent2drive] token exchange failed: "
373
+ f"{e.code} {e.read().decode()[:300]}") from None
374
+ except (urllib.error.URLError, OSError, ValueError) as e:
375
+ raise SystemExit(f"[agent2drive] token exchange failed: {e}") from None
376
+ if "refresh_token" not in tok:
377
+ raise SystemExit("[agent2drive] no refresh_token — the consent URL "
378
+ "must include prompt=consent; re-run `url`")
379
+ tok["expiry"] = time.strftime(
380
+ "%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() +
381
+ tok.get("expires_in", 3600)))
382
+ token_json = json.dumps({k: tok[k] for k in
383
+ ("access_token", "token_type",
384
+ "refresh_token", "expiry") if k in tok})
385
+ STATE.mkdir(parents=True, exist_ok=True)
386
+ CONF.write_text(f"[gdrive]\ntype = drive\nscope = drive.file\n"
387
+ f"client_id = {client_id}\n"
388
+ f"client_secret = {client_secret}\n"
389
+ f"token = {token_json}\n")
390
+ CONF.chmod(0o600)
391
+ print("[agent2drive] CONF_WRITTEN (chmod 600)")
392
+ try:
393
+ result = status(retries=2, quiet=True)
394
+ except Exception as e: # never lose a good token to a flaky verify
395
+ print(f"[agent2drive] credentials saved, but verification failed: {e}")
396
+ return "SAVED_UNVERIFIED"
397
+ if result != "AUTH_OK":
398
+ print("[agent2drive] credentials saved, but live verification "
399
+ "failed — check `agent2drive status`")
400
+ return "SAVED_UNVERIFIED"
401
+ return result
402
+
403
+
404
+ # ----------------------------------------------------------------- cmds
405
+ def status(retries=0, quiet=False):
406
+ if not CONF.exists():
407
+ if not quiet:
408
+ print("AUTH_MISSING — run `agent2drive url`, then "
409
+ "`agent2drive connect <pasted-url>`")
410
+ return "AUTH_MISSING"
411
+ try:
412
+ line = (_rc("about", "gdrive:", timeout=120, retries=retries)
413
+ .stdout.strip().splitlines() or [""])[-1]
414
+ if not quiet:
415
+ print(f"AUTH_OK — {line.strip()}")
416
+ return "AUTH_OK"
417
+ except (RuntimeError, OSError) as e:
418
+ if not quiet:
419
+ print(f"AUTH_MISSING ({e})")
420
+ return "AUTH_MISSING"
421
+
422
+
423
+ def _check_slot(slot):
424
+ if (not slot or slot in (".", "..") or "/" in slot or "\\" in slot
425
+ or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", slot)):
426
+ raise SystemExit(f"[agent2drive] invalid slot name: {slot!r} "
427
+ "(lowercase letters, digits and hyphens, "
428
+ "max 64 chars)")
429
+ return slot
430
+
431
+
432
+ def _check_folder(folder):
433
+ """No imposed structure; any single path component is valid."""
434
+ if folder is None:
435
+ return None
436
+ if (not folder or folder in (".", "..") or "/" in folder
437
+ or "\\" in folder or folder.strip() != folder):
438
+ raise SystemExit(f"[agent2drive] invalid folder name: {folder!r} "
439
+ "(one path component; no /, \\, '..', "
440
+ "surrounding spaces)")
441
+ return folder
442
+
443
+
444
+ def _remote_dir(slot, folder=None):
445
+ slot = _check_slot(slot)
446
+ folder = _check_folder(folder)
447
+ return f"{ROOT}/{slot}" + (f"/{folder}" if folder else "")
448
+
449
+
450
+ def _manifest_remote(slot):
451
+ return f"gdrive:{ROOT}/{_check_slot(slot)}/MANIFEST.md"
452
+
453
+
454
+ def _manifest_header(slot):
455
+ return (f"# {slot} — delivery manifest\n\n"
456
+ "UTC | File | Folder | Bytes | MD5 | SHA-1 | Result\n"
457
+ "--- | --- | --- | --- | --- | --- | ---\n")
458
+
459
+
460
+ def _read_manifest(slot):
461
+ p = _rc("cat", _manifest_remote(slot), check=False, timeout=120)
462
+ text = p.stdout if p.returncode == 0 else ""
463
+ # Migrate the legacy prose-only MANIFEST.md written by <= 0.2.0.
464
+ if "UTC | File | Folder" not in text:
465
+ return _manifest_header(slot)
466
+ return text
467
+
468
+
469
+ def _append_manifest(slot, row):
470
+ text = _read_manifest(slot)
471
+ if not text.endswith("\n"):
472
+ text += "\n"
473
+ _rc("rcat", _manifest_remote(slot), stdin_data=text + row + "\n",
474
+ timeout=120)
475
+
476
+
477
+ def cmd_init(slot):
478
+ _check_slot(slot)
479
+ _rc("mkdir", f"gdrive:{ROOT}/{slot}")
480
+ _rc("rcat", _manifest_remote(slot),
481
+ stdin_data=_manifest_header(slot), timeout=120)
482
+ print(f"[agent2drive] slot ready: gdrive:{ROOT}/{slot}/")
483
+
484
+
485
+ def _local_hashes(path):
486
+ md5, sha1 = hashlib.md5(), hashlib.sha1()
487
+ with open(path, "rb") as f:
488
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
489
+ md5.update(chunk)
490
+ sha1.update(chunk)
491
+ return md5.hexdigest(), sha1.hexdigest()
492
+
493
+
494
+ def _remote_hashes(remote):
495
+ """Drive serves MD5/SHA-1 natively; return whatever rclone can read."""
496
+ out = {}
497
+ for algo, length in (("MD5", 32), ("SHA-1", 40)):
498
+ p = _rc("hashsum", algo, remote, check=False, timeout=300)
499
+ if p.returncode:
500
+ continue
501
+ m = re.search(r"\b([0-9a-fA-F]{%d})\b" % length, p.stdout)
502
+ if m:
503
+ out[algo] = m.group(1).lower()
504
+ return out
505
+
506
+
507
+ def _remote_files(remote_dir):
508
+ p = _rc("lsjson", "--files-only", f"gdrive:{remote_dir}",
509
+ check=False, timeout=300)
510
+ if p.returncode:
511
+ return []
512
+ try:
513
+ return json.loads(p.stdout)
514
+ except ValueError:
515
+ return []
516
+
517
+
518
+ def cmd_upload(slot, path, folder=None, replace=False):
519
+ remote_dir = _remote_dir(slot, folder)
520
+ src = Path(path)
521
+ if not src.is_file():
522
+ raise SystemExit(f"[agent2drive] not a file: {src}")
523
+ remote = f"gdrive:{remote_dir}/{src.name}"
524
+ size = src.stat().st_size
525
+ md5, sha1 = _local_hashes(src)
526
+
527
+ existing = next((i for i in _remote_files(remote_dir)
528
+ if i.get("Name") == src.name), None)
529
+ if existing and not replace:
530
+ raise SystemExit(f"[agent2drive] {remote} already exists — "
531
+ "use --replace to overwrite it")
532
+
533
+ print(f"[agent2drive] uploading {src.name} ({size} B) -> {remote}")
534
+ _rc("copyto", str(src), remote, retries=1)
535
+
536
+ remote_hashes = _remote_hashes(remote)
537
+ remote_size = next((i["Size"] for i in _remote_files(remote_dir)
538
+ if i.get("Name") == src.name), None)
539
+ def matches(remote, local):
540
+ return None if remote is None else remote == local
541
+
542
+ checks = {
543
+ "size": matches(remote_size, size),
544
+ "MD5": matches(remote_hashes.get("MD5"), md5),
545
+ "SHA-1": matches(remote_hashes.get("SHA-1"), sha1),
546
+ }
547
+ if any(v is False for v in checks.values()):
548
+ _rc("deletefile", remote, check=False)
549
+ raise SystemExit(f"[agent2drive] verification FAILED for {src.name}: "
550
+ f"size={size}/{remote_size} "
551
+ f"md5={md5}/{remote_hashes.get('MD5')} "
552
+ f"sha1={sha1}/{remote_hashes.get('SHA-1')} "
553
+ "— remote copy removed; retry the upload")
554
+ if any(v is None for v in checks.values()):
555
+ result = "SIZE-ONLY"
556
+ print("[agent2drive] warning: remote hashes unavailable; only size "
557
+ "was verified")
558
+ else:
559
+ result = "OK"
560
+ print(f"[agent2drive] verified: size {checks['size']} · "
561
+ f"md5 {checks['MD5']} · sha1 {checks['SHA-1']} -> {result}")
562
+
563
+ safe_name = src.name.replace("|", "\\|")
564
+ row = "| " + " | ".join([
565
+ time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
566
+ safe_name, folder or "-", str(size), md5, sha1, result]) + " |"
567
+ _append_manifest(slot, row)
568
+ print(f"[agent2drive] manifest updated: gdrive:{ROOT}/{slot}/MANIFEST.md")
569
+ return 0 if result == "OK" else 1
570
+
571
+
572
+ def cmd_ls(slot):
573
+ _check_slot(slot)
574
+ p = _rc("lsf", "-R", "--files-only", f"gdrive:{ROOT}/{slot}/",
575
+ timeout=300)
576
+ print(p.stdout or "(empty)")
577
+ return 0
578
+
579
+
580
+ def cmd_manifest(slot):
581
+ print(_read_manifest(slot), end="")
582
+ return 0
583
+
584
+
585
+ CONNECT_RECIPE = """AUTH_MISSING — one-time connect:
586
+ 1. agent2drive url -> give the user the printed URL
587
+ 2. user: open URL -> Allow -> browser fails on 127.0.0.1:53682
588
+ (EXPECTED) -> copy the full address-bar URL
589
+ 3. agent2drive connect '<PASTED_URL>'
590
+ (recommended: agent2drive client <id> <secret> first, with your own client)"""
591
+
592
+
593
+ def cli(argv=None):
594
+ parser = argparse.ArgumentParser(
595
+ prog="agent2drive",
596
+ description="Connect an agent to Google Drive and upload reviewable files.")
597
+ sub = parser.add_subparsers(dest="cmd")
598
+
599
+ sub.add_parser("status", help="check the live connection (exit 0/2)")
600
+ sub.add_parser("url", help="print the Google consent URL")
601
+
602
+ c = sub.add_parser("connect", help="exchange a pasted redirect URL/code")
603
+ c.add_argument("pasted", nargs="?", help="full pasted URL, or '-' for stdin")
604
+ c.add_argument("--stdin", action="store_true", help="read the code from stdin")
605
+
606
+ cl = sub.add_parser("client", help="set your own OAuth client id/secret")
607
+ cl.add_argument("client_id", nargs="?")
608
+ cl.add_argument("client_secret", nargs="?")
609
+
610
+ i = sub.add_parser("init", help="create a slot root + MANIFEST.md")
611
+ i.add_argument("slot")
612
+
613
+ u = sub.add_parser("upload", help="upload and verify a file into a slot")
614
+ u.add_argument("slot")
615
+ u.add_argument("file")
616
+ u.add_argument("folder", nargs="?")
617
+ u.add_argument("--replace", action="store_true",
618
+ help="overwrite an existing file of the same name")
619
+
620
+ ls = sub.add_parser("ls", help="list a slot's files")
621
+ ls.add_argument("slot")
622
+
623
+ m = sub.add_parser("manifest", help="print a slot's delivery manifest")
624
+ m.add_argument("slot")
625
+
626
+ args = parser.parse_args(argv)
627
+ if not args.cmd:
628
+ status(quiet=True)
629
+ print(CONNECT_RECIPE)
630
+ return 2
631
+
632
+ if args.cmd == "status":
633
+ return 0 if status() == "AUTH_OK" else 2
634
+ if args.cmd == "url":
635
+ client_id, _ = load_client()
636
+ print(consent_url(client_id, new_oauth_state()))
637
+ return 0
638
+ if args.cmd == "connect":
639
+ pasted = args.pasted
640
+ if args.stdin or pasted == "-":
641
+ pasted = sys.stdin.read().strip()
642
+ if not pasted:
643
+ parser.error("connect needs a pasted URL/code (or --stdin)")
644
+ result = exchange(pasted)
645
+ return 0 if result in ("AUTH_OK", "SAVED_UNVERIFIED") else 1
646
+ if args.cmd == "client":
647
+ cid = args.client_id or input("OAuth client id: ").strip()
648
+ secret = args.client_secret or getpass.getpass("OAuth client secret: ")
649
+ set_client(cid, secret)
650
+ return 0
651
+ if args.cmd == "init":
652
+ cmd_init(args.slot)
653
+ return 0
654
+ if args.cmd == "upload":
655
+ return cmd_upload(args.slot, args.file, args.folder, args.replace)
656
+ if args.cmd == "ls":
657
+ return cmd_ls(args.slot)
658
+ if args.cmd == "manifest":
659
+ return cmd_manifest(args.slot)
660
+ parser.print_help()
661
+ return 1
662
+
663
+
664
+ def main(argv=None):
665
+ return cli(argv)
666
+
667
+
668
+ if __name__ == "__main__":
669
+ sys.exit(cli())
agent2drive_mcp.py ADDED
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env python3
2
+ """MCP stdio server for agent2drive.
3
+
4
+ Exposes the delivery workflow as MCP tools without ever returning tokens or
5
+ client secrets to the model. All core calls are wrapped so their print()
6
+ output becomes structured tool output instead of corrupting the stdio
7
+ JSON-RPC stream.
8
+
9
+ pip install 'agent2drive[mcp]'
10
+ agent2drive-mcp
11
+ """
12
+ import io
13
+ import json
14
+ import os
15
+ from contextlib import redirect_stdout
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from pydantic import BaseModel, Field
20
+
21
+ import agent2drive as a2d
22
+
23
+ try: # MCP SDK v2
24
+ from mcp.server.mcpserver import MCPServer
25
+ _V2 = True
26
+ except ImportError: # MCP SDK v1
27
+ from mcp.server.fastmcp import FastMCP as MCPServer # type: ignore
28
+ _V2 = False
29
+
30
+ VERSION = "0.4.0"
31
+
32
+
33
+ class A2DResult(BaseModel):
34
+ """Structured result schema for MCP v2; instances stay dicts at runtime."""
35
+
36
+ ok: bool
37
+ code: str
38
+ message: str = ""
39
+ data: dict[str, Any] = Field(default_factory=dict)
40
+
41
+
42
+ mcp = MCPServer(
43
+ name="agent2drive",
44
+ version=VERSION,
45
+ instructions=(
46
+ "Deliver files into the user's Google Drive for review. "
47
+ "OAuth is user-mediated: a2d_consent_url gives a link the user must "
48
+ "open; only after they paste the redirect URL may a2d_connect be "
49
+ "called. Uploads verify size, MD5 and SHA-1. Never overwrite a file "
50
+ "without an explicit confirm='REPLACE'."),
51
+ )
52
+
53
+
54
+ # ------------------------------------------------------------- helpers
55
+ def tool(name, description):
56
+ """Register a tool with structured output where the SDK supports it."""
57
+ kwargs = {"name": name, "description": description}
58
+ if _V2:
59
+ kwargs["structured_output"] = True
60
+ return mcp.tool(**kwargs)
61
+
62
+
63
+ def _result(ok, code, message="", data=None):
64
+ return {"ok": bool(ok), "code": code, "message": message,
65
+ "data": data if data is not None else {}}
66
+
67
+
68
+ def _jsonable(value):
69
+ if isinstance(value, (str, int, float, bool)) or value is None:
70
+ return value
71
+ if isinstance(value, (list, tuple)):
72
+ return [_jsonable(v) for v in value]
73
+ if isinstance(value, dict):
74
+ return {str(k): _jsonable(v) for k, v in value.items()}
75
+ return str(value)
76
+
77
+
78
+ def _call(fn, *args, code="call", **kwargs):
79
+ """Run a core function, capturing its stdout for the tool response."""
80
+ buf = io.StringIO()
81
+ try:
82
+ with redirect_stdout(buf):
83
+ value = fn(*args, **kwargs)
84
+ except SystemExit as e:
85
+ return _result(False, f"{code}_error", str(e), {"log": buf.getvalue()})
86
+ except Exception as e: # noqa: BLE001 - report, never leak a traceback
87
+ return _result(False, f"{code}_error",
88
+ f"{type(e).__name__}: {e}", {"log": buf.getvalue()})
89
+ return _result(True, code, buf.getvalue().strip() or "ok",
90
+ {"result": _jsonable(value), "log": buf.getvalue()})
91
+
92
+
93
+ def _allowed_roots():
94
+ raw = os.environ.get("A2D_ALLOWED_ROOTS", "")
95
+ roots = [Path(p).expanduser().resolve() for p in raw.split(os.pathsep)
96
+ if p.strip()]
97
+ return roots or [Path.cwd().resolve()]
98
+
99
+
100
+ def _is_allowed(path):
101
+ """Resolve symlinks so a link can't escape an allowed directory."""
102
+ target = Path(path).expanduser().resolve()
103
+ return any(target == root or root in target.parents
104
+ for root in _allowed_roots())
105
+
106
+
107
+ def _build_consent_url():
108
+ client_id, _ = a2d.load_client()
109
+ return a2d.consent_url(client_id, a2d.new_oauth_state())
110
+
111
+
112
+ def _read(slot, kind):
113
+ buf = io.StringIO()
114
+ with redirect_stdout(buf):
115
+ text = (a2d._read_manifest(slot) if kind == "manifest"
116
+ else a2d.cmd_ls(slot) or "")
117
+ lines = buf.getvalue().strip().splitlines()
118
+ return (text or "\n".join(lines)).strip()
119
+
120
+
121
+ # ----------------------------------------------------------------- tools
122
+ @tool(name="a2d_status", description="Check the live Google Drive connection.")
123
+ def a2d_status() -> A2DResult:
124
+ result = _call(a2d.status, quiet=True, code="status")
125
+ result["ok"] = result["data"].get("result") == "AUTH_OK"
126
+ return result
127
+
128
+
129
+ @tool(name="a2d_set_client",
130
+ description="Store your own Google OAuth client id and secret (secret is never returned).")
131
+ def a2d_set_client(client_id: str, client_secret: str) -> A2DResult:
132
+ if not client_id or not client_secret:
133
+ return _result(False, "validation_error", "client_id and client_secret are required")
134
+ result = _call(a2d.set_client, client_id, client_secret, code="client")
135
+ result["message"] = "OAuth client stored (secret redacted)"
136
+ return result
137
+
138
+
139
+ @tool(name="a2d_consent_url",
140
+ description="Print the Google consent URL the user must open; stores a one-time state nonce.")
141
+ def a2d_consent_url() -> A2DResult:
142
+ return _call(_build_consent_url, code="consent_url")
143
+
144
+
145
+ @tool(name="a2d_connect",
146
+ description="Exchange the user's pasted redirect URL for a Drive token. Do this immediately.")
147
+ def a2d_connect(pasted_url: str) -> A2DResult:
148
+ if not pasted_url or not pasted_url.strip():
149
+ return _result(False, "validation_error", "pasted_url is required")
150
+ return _call(a2d.exchange, pasted_url.strip(), code="connect")
151
+
152
+
153
+ @tool(name="a2d_init_slot",
154
+ description="Create a Drive slot root and its MANIFEST.md.")
155
+ def a2d_init_slot(slot: str) -> A2DResult:
156
+ return _call(a2d.cmd_init, slot, code="init_slot")
157
+
158
+
159
+ @tool(name="a2d_upload",
160
+ description="Upload and verify a file into a slot; writes a manifest row. Overwrites require confirm='REPLACE'.")
161
+ def a2d_upload(slot: str, path: str, folder: str | None = None,
162
+ replace: bool = False, confirm: str | None = None) -> A2DResult:
163
+ if not _is_allowed(path):
164
+ return _result(False, "path_denied",
165
+ "path is outside A2D_ALLOWED_ROOTS",
166
+ {"allowed_roots": [str(p) for p in _allowed_roots()]})
167
+ if replace and confirm != "REPLACE":
168
+ return _result(False, "confirmation_required",
169
+ "overwriting needs confirm='REPLACE'")
170
+ return _call(a2d.cmd_upload, slot, path, folder, replace, code="upload")
171
+
172
+
173
+ @tool(name="a2d_list", description="List all files in a Drive slot.")
174
+ def a2d_list(slot: str) -> A2DResult:
175
+ result = _call(a2d.cmd_ls, slot, code="list")
176
+ result["message"] = _read(slot, "list") or result["message"]
177
+ return result
178
+
179
+
180
+ @tool(name="a2d_manifest", description="Read a slot's delivery manifest / audit trail.")
181
+ def a2d_manifest(slot: str) -> A2DResult:
182
+ result = _call(a2d.cmd_manifest, slot, code="manifest")
183
+ result["message"] = _read(slot, "manifest") or result["message"]
184
+ return result
185
+
186
+
187
+ # ------------------------------------------------------------- resources
188
+ @mcp.resource("a2d://config")
189
+ def config_resource() -> str:
190
+ """Non-secret configuration of this server."""
191
+ return json.dumps({
192
+ "version": VERSION,
193
+ "drive_root": a2d.ROOT,
194
+ "state_home": str(a2d.HOME),
195
+ "allowed_roots": [str(p) for p in _allowed_roots()],
196
+ }, indent=2)
197
+
198
+
199
+ @mcp.resource("a2d://slot/{slot}/manifest")
200
+ def manifest_resource(slot: str) -> str:
201
+ """Delivery manifest for a slot."""
202
+ return _read(slot, "manifest")
203
+
204
+
205
+ # --------------------------------------------------------------- prompts
206
+ @mcp.prompt(name="deliver-file",
207
+ description="Deliver a created file to the review canvas.")
208
+ def deliver_file_prompt(slot: str) -> str:
209
+ return (
210
+ f"Deliver the file you just created into Drive slot '{slot}'. "
211
+ "1) call a2d_upload with the absolute path and a short folder name "
212
+ "(e.g. 'drafts' or 'final'); 2) if it reports SIZE-ONLY, tell the user; "
213
+ "3) if a file with that name already exists, ask before passing "
214
+ "replace=True and confirm='REPLACE'; 4) report the verified result "
215
+ "and where to review it (Google Drive -> AgentDeliveries/"
216
+ f"{slot}/).")
217
+
218
+
219
+ def main():
220
+ mcp.run(transport="stdio")
221
+
222
+
223
+ if __name__ == "__main__":
224
+ main()