@protonurl/mcp 0.0.0-stage → 0.1.0

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.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # protonURL MCP server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Let AI agents share secrets the safe way: through [protonURL](https://protonurl.com) one-time links,
4
+ **end-to-end encrypted on your machine**, and designed so that **the secret never enters the model's context**.
5
+
6
+ - Share a local file (`.env`, key file…) without the agent reading it.
7
+ - Generate a password locally, save it to your `.env` and send it to a colleague — the model never sees it.
8
+ - Receive a secret and write it straight into a file or a `.env` variable.
9
+ - Check whether the recipient has opened the link (public deletion proof).
10
+
11
+ protonURL only ever receives an encrypted blob. The key stays after the `#` of the link, which is never sent to the server.
12
+ Links are compatible with the website: a link created here opens in the browser, and vice versa.
13
+
14
+ ## Tools
15
+
16
+ | Tool | What it does | API calls |
17
+ |---|---|---|
18
+ | `create_secret_link` | Create a one-time link from a file (`file_path`), a locally generated secret (`generate_length`, optionally saved with `save_generated_to` / `save_generated_as_env`) or text. Optional password and lifetime (1 h to 1 year). | 1 |
19
+ | `read_secret_link_to_file` | Open a link and write its content to a file (mode 600) or append it as `NAME=value`. Returns only sizes and names. **Opening destroys the link.** | 1 |
20
+ | `secret_link_status` | Opened, expired or still pending? | 0 |
21
+ | `protonurl_quota` | Plan and remaining calls. | 0 |
22
+
23
+ ## Setup
24
+
25
+ Get an API key (free: 20 calls/month) at <https://protonurl.com/free-trial.html>, then:
26
+
27
+ **Claude Code**
28
+
29
+ ```bash
30
+ claude mcp add protonurl -e PROTONURL_API_KEY=your-key -- npx -y @protonurl/mcp
31
+ ```
32
+
33
+ **Claude Desktop, Cursor and other MCP clients**
34
+
35
+ ```json
36
+ {
37
+ "mcpServers": {
38
+ "protonurl": {
39
+ "command": "npx",
40
+ "args": ["-y", "@protonurl/mcp"],
41
+ "env": { "PROTONURL_API_KEY": "your-key" }
42
+ }
43
+ }
44
+ }
45
+ ```
46
+
47
+ ## Examples
48
+
49
+ - *"Generate a 32-character database password, add it as DB_PASSWORD to .env and give me a protonURL link for Alice."*
50
+ - *"Send ./certs/client.key to Bob with a protonURL link that expires in 1 hour."*
51
+ - *"Here is the API key link from Carol: https://protonurl.com/en/…#… — put it in .env as STRIPE_KEY."*
52
+ - *"Has Alice opened the link yet?"*
53
+
54
+ ## Good to know
55
+
56
+ - The link itself grants access: give it only to its recipient. If someone else opens it first, the recipient will see it is gone — that is the point of one-time links.
57
+ - If you set a password, send it through another channel than the link. A wrong password when opening destroys the secret.
58
+ - Content passed as `text` has, by definition, already been seen by the model: prefer `file_path` or `generate_length` for real secrets.
59
+
60
+ ## Development
61
+
62
+ ```bash
63
+ npm install
64
+ npm test # crypto compatibility with the website + full flow against a local mock API
65
+ ```
66
+
67
+ Requires Node.js 20+. Environment: `PROTONURL_API_KEY`, `PROTONURL_API_URL` (default `https://api.protonurl.com`).
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@protonurl/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MCP server for protonURL: share secrets through end-to-end encrypted one-time links, without the secret ever entering the model's context.",
5
+ "type": "module",
6
+ "bin": {
7
+ "protonurl-mcp": "src/index.js"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "scripts": {
17
+ "test": "node --test test/*.test.js"
18
+ },
19
+ "keywords": [
20
+ "mcp",
21
+ "protonurl",
22
+ "secrets",
23
+ "one-time-link",
24
+ "e2e",
25
+ "encryption"
26
+ ],
27
+ "homepage": "https://protonurl.com/api-docs.html",
28
+ "license": "MIT",
29
+ "dependencies": {
30
+ "@modelcontextprotocol/sdk": "^1.32.2",
31
+ "zod": "^4.6.7"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }
package/src/api.js ADDED
@@ -0,0 +1,56 @@
1
+ // Client minimal de l'API protonURL (https://protonurl.com/api-docs.html).
2
+ // create et view consomment un appel du quota de la clé ; deletion_proof et quota non.
3
+
4
+ const VERSION = '0.1.0'
5
+
6
+ export class ApiError extends Error {
7
+ constructor(status, message) {
8
+ super(message)
9
+ this.status = status
10
+ }
11
+ }
12
+
13
+ export function createClient({ apiKey, baseUrl = 'https://api.protonurl.com' } = {}) {
14
+ const base = baseUrl.replace(/\/+$/, '')
15
+
16
+ async function request(path, { method = 'GET', body, headers = {}, auth = true } = {}) {
17
+ if (auth && !apiKey) {
18
+ throw new ApiError(401, 'PROTONURL_API_KEY is not set. Get a free key at https://protonurl.com/free-trial.html')
19
+ }
20
+ const res = await fetch(base + path, {
21
+ method,
22
+ headers: {
23
+ 'User-Agent': `protonurl-mcp/${VERSION}`,
24
+ Accept: 'application/json',
25
+ ...(auth ? { Authorization: `Bearer ${apiKey}` } : {}),
26
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
27
+ ...headers,
28
+ },
29
+ body: body ? JSON.stringify(body) : undefined,
30
+ })
31
+ let data = null
32
+ try { data = await res.json() } catch { /* réponse vide ou non JSON */ }
33
+ if (!res.ok) {
34
+ throw new ApiError(res.status, data?.message || `HTTP ${res.status}`)
35
+ }
36
+ return data
37
+ }
38
+
39
+ return {
40
+ /** Envoie un blob déjà chiffré. Le serveur ne reçoit ni le contenu, ni la clé, ni le mot de passe. */
41
+ createE2e: ({ blob, duration, hasPassword }) =>
42
+ request('/create', {
43
+ method: 'POST',
44
+ body: { e2e: true, data: Buffer.from(blob).toString('base64'), duration, key: hasPassword ? 1 : 0 },
45
+ }),
46
+
47
+ /** Lit et DÉTRUIT le secret. */
48
+ view: (id, { secretKey } = {}) =>
49
+ request(`/view/${id}`, { headers: secretKey ? { 'X-Secret-Key': secretKey } : {} }),
50
+
51
+ /** Preuve de suppression : existe seulement une fois le lien lu ou expiré. */
52
+ deletionProof: (id) => request(`/deletion_proof/${id}`, { auth: false }),
53
+
54
+ quota: () => request('/quota'),
55
+ }
56
+ }
package/src/crypto.js ADDED
@@ -0,0 +1,74 @@
1
+ // Chiffrement de bout en bout, identique à celui du site (resources/js/e2e.js) :
2
+ // un lien créé ici s'ouvre dans le navigateur, et inversement.
3
+ //
4
+ // Blob envoyé au serveur : [version 1 octet][IV 12 octets][données chiffrées + tag GCM]
5
+ // Contenu chiffré : [longueur de l'en-tête, 4 octets big-endian][en-tête JSON][octets du fichier]
6
+ // Clé : 32 octets aléatoires, en base64url (43 caractères) après le « # » du lien.
7
+ // Avec un mot de passe : clé AES = PBKDF2-SHA-256(mot de passe, sel = clé du lien, 310 000 itérations).
8
+
9
+ const VERSION = 1
10
+ const PBKDF2_ITERATIONS = 310000
11
+ const { subtle } = globalThis.crypto
12
+
13
+ export const toBase64Url = (bytes) => Buffer.from(bytes).toString('base64url')
14
+
15
+ export function fromBase64Url(str) {
16
+ if (!/^[A-Za-z0-9_-]{43}$/.test(str)) return null
17
+ return new Uint8Array(Buffer.from(str, 'base64url'))
18
+ }
19
+
20
+ async function deriveKey(raw, password) {
21
+ if (!password) {
22
+ return subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])
23
+ }
24
+ const base = await subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey'])
25
+ return subtle.deriveKey(
26
+ { name: 'PBKDF2', salt: raw, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
27
+ base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'],
28
+ )
29
+ }
30
+
31
+ /** Chiffre un texte et/ou un fichier. Renvoie le blob à envoyer et la clé à mettre après le « # ». */
32
+ export async function encryptPayload({ text = '', fileBytes = null, fileName = null, fileType = null, password = '' }) {
33
+ const raw = globalThis.crypto.getRandomValues(new Uint8Array(32))
34
+ const header = new TextEncoder().encode(JSON.stringify({
35
+ v: VERSION, text, name: fileBytes ? fileName : null, type: fileBytes ? fileType : null,
36
+ }))
37
+ const body = fileBytes ?? new Uint8Array(0)
38
+
39
+ const plain = new Uint8Array(4 + header.length + body.length)
40
+ new DataView(plain.buffer).setUint32(0, header.length)
41
+ plain.set(header, 4)
42
+ plain.set(body, 4 + header.length)
43
+
44
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12))
45
+ const key = await deriveKey(raw, password)
46
+ const cipher = new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv }, key, plain))
47
+
48
+ const blob = new Uint8Array(1 + 12 + cipher.length)
49
+ blob[0] = VERSION
50
+ blob.set(iv, 1)
51
+ blob.set(cipher, 13)
52
+ return { blob, keyText: toBase64Url(raw) }
53
+ }
54
+
55
+ /** Déchiffre un blob. Lève une erreur si la clé ou le mot de passe ne correspondent pas. */
56
+ export async function decryptPayload(blob, raw, password = '') {
57
+ const bytes = new Uint8Array(blob)
58
+ if (bytes[0] !== VERSION) throw new Error('Unsupported payload version')
59
+ const key = await deriveKey(raw, password)
60
+ const plain = new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: bytes.slice(1, 13) }, key, bytes.slice(13)))
61
+ const headerLength = new DataView(plain.buffer).getUint32(0)
62
+ const header = JSON.parse(new TextDecoder().decode(plain.slice(4, 4 + headerLength)))
63
+ return { header, fileBytes: plain.slice(4 + headerLength) }
64
+ }
65
+
66
+ /**
67
+ * Découpe un lien protonURL : identifiant (24 caractères pour un lien de bout en bout,
68
+ * 64 hexadécimaux pour un ancien lien chiffré côté serveur) et clé éventuelle après le « # ».
69
+ */
70
+ export function parseLink(link) {
71
+ const m = String(link).trim().match(/^(?:https?:\/\/)?(?:www\.)?protonurl\.com\/(?:[a-z]{2}\/)?([a-z0-9]{24}|[a-f0-9]{64})(?:#([A-Za-z0-9_-]+))?$/)
72
+ if (!m) return null
73
+ return { id: m[1], keyText: m[2] ?? null }
74
+ }
package/src/index.js ADDED
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ // Serveur MCP protonURL (stdio).
3
+ //
4
+ // Principe : le chiffrement et le déchiffrement se font ici, sur la machine de l'utilisateur.
5
+ // protonURL ne reçoit qu'un blob chiffré, et les outils sont conçus pour que le secret
6
+ // n'entre jamais dans le contexte du modèle : on partage un fichier ou un secret généré
7
+ // localement, et on lit un lien directement dans un fichier.
8
+ //
9
+ // Configuration : PROTONURL_API_KEY (obligatoire pour créer et lire), PROTONURL_API_URL (facultatif).
10
+
11
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
12
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
13
+ import { z } from 'zod'
14
+ import { readFile, writeFile, appendFile, stat } from 'node:fs/promises'
15
+ import { homedir } from 'node:os'
16
+ import { resolve, basename } from 'node:path'
17
+ import { encryptPayload, decryptPayload, fromBase64Url, parseLink } from './crypto.js'
18
+ import { createClient, ApiError } from './api.js'
19
+
20
+ const DURATIONS = [1, 72, 168, 744, 4464, 8760]
21
+ const PASSWORD_CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789-_.!@#%+='
22
+
23
+ const api = createClient({
24
+ apiKey: process.env.PROTONURL_API_KEY,
25
+ baseUrl: process.env.PROTONURL_API_URL || undefined,
26
+ })
27
+
28
+ const ok = (text, structured) => ({ content: [{ type: 'text', text }], ...(structured ? { structuredContent: structured } : {}) })
29
+ const fail = (text) => ({ content: [{ type: 'text', text }], isError: true })
30
+ const expandPath = (p) => resolve(p.startsWith('~/') ? homedir() + p.slice(1) : p)
31
+ const exists = (p) => stat(p).then(() => true, () => false)
32
+
33
+ /** Ajoute NAME=valeur à un fichier .env, en commençant une nouvelle ligne si besoin. */
34
+ async function appendEnvLine(path, name, value) {
35
+ let prefix = ''
36
+ if (await exists(path)) {
37
+ const current = await readFile(path, 'utf8')
38
+ if (current !== '' && !current.endsWith('\n')) prefix = '\n'
39
+ }
40
+ await appendFile(path, `${prefix}${name}=${value}\n`, { mode: 0o600 })
41
+ }
42
+
43
+ function generateSecret(length) {
44
+ // Tirage sans biais : on rejette les octets au-delà du plus grand multiple de l'alphabet
45
+ const max = 256 - (256 % PASSWORD_CHARS.length)
46
+ let out = ''
47
+ while (out.length < length) {
48
+ for (const b of globalThis.crypto.getRandomValues(new Uint8Array(length * 2))) {
49
+ if (b < max && out.length < length) out += PASSWORD_CHARS[b % PASSWORD_CHARS.length]
50
+ }
51
+ }
52
+ return out
53
+ }
54
+
55
+ function describeError(e) {
56
+ if (e instanceof ApiError) {
57
+ if (e.status === 401 || e.status === 403) return `protonURL refused the API key: ${e.message}`
58
+ if (e.status === 404) return 'This link does not exist anymore: it was already opened, or it expired.'
59
+ if (e.status === 429) return `API quota exceeded: ${e.message}`
60
+ return `protonURL API error (${e.status}): ${e.message}`
61
+ }
62
+ return `Error: ${e?.message || e}`
63
+ }
64
+
65
+ const server = new McpServer({ name: 'protonurl', version: '0.1.0' })
66
+
67
+ // ── Créer un lien ────────────────────────────────────────────────────────────
68
+ server.registerTool('create_secret_link', {
69
+ title: 'Create a one-time secret link',
70
+ description: [
71
+ 'Share a secret (password, API key, credentials, file) with a person through a protonURL link that can be opened only once,',
72
+ 'then self-destructs. The content is end-to-end encrypted on this machine: protonURL never sees it.',
73
+ 'Give exactly one source:',
74
+ '- file_path: share a local file (e.g. a .env or a key file) WITHOUT reading it into the conversation. Preferred for existing secrets.',
75
+ '- generate_length: generate a random secret locally; with save_generated_to, it is also written to a local file (e.g. to configure a service), so the secret never appears in the conversation.',
76
+ '- text: only when the secret is already in the conversation.',
77
+ 'Returns the link to give to the recipient. The link itself grants access: send it only to the intended person.',
78
+ 'If a password is set, tell the user to send it through a different channel than the link.',
79
+ ].join('\n'),
80
+ inputSchema: {
81
+ text: z.string().optional().describe('Secret text, if it is already in the conversation.'),
82
+ file_path: z.string().optional().describe('Local file to share; it is read and encrypted locally, never shown to the model.'),
83
+ generate_length: z.number().int().min(12).max(128).optional().describe('Generate a random secret of this length instead.'),
84
+ save_generated_to: z.string().optional().describe('With generate_length: also write the generated secret to this local file.'),
85
+ save_generated_as_env: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).optional()
86
+ .describe('With save_generated_to: append it as NAME=value (for .env files) instead of overwriting the file.'),
87
+ duration_hours: z.number().int().refine((d) => DURATIONS.includes(d), `One of ${DURATIONS.join(', ')}`).default(72)
88
+ .describe(`Lifetime if never opened, in hours: ${DURATIONS.join(', ')}. Default 72.`),
89
+ password: z.string().max(64).optional().describe('Optional extra password required to open the link.'),
90
+ },
91
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
92
+ }, async ({ text, file_path, generate_length, save_generated_to, save_generated_as_env, duration_hours, password }) => {
93
+ const sources = [text !== undefined, !!file_path, !!generate_length].filter(Boolean).length
94
+ if (sources !== 1) return fail('Give exactly one of: text, file_path, generate_length.')
95
+ if (save_generated_to && !generate_length) return fail('save_generated_to only works with generate_length.')
96
+ if (save_generated_as_env && !save_generated_to) return fail('save_generated_as_env needs save_generated_to.')
97
+
98
+ try {
99
+ let payload
100
+ let summary
101
+ if (file_path) {
102
+ const path = expandPath(file_path)
103
+ const bytes = new Uint8Array(await readFile(path))
104
+ payload = { text: '', fileBytes: bytes, fileName: basename(path), fileType: 'application/octet-stream' }
105
+ summary = `file ${basename(path)} (${bytes.length} bytes)`
106
+ } else if (generate_length) {
107
+ const secret = generateSecret(generate_length)
108
+ if (save_generated_to && !save_generated_as_env && await exists(expandPath(save_generated_to))) {
109
+ return fail(`${expandPath(save_generated_to)} already exists; choose another path or use save_generated_as_env.`)
110
+ }
111
+ payload = { text: secret }
112
+ summary = `generated secret of ${generate_length} characters` + (save_generated_to ? `, also saved to ${expandPath(save_generated_to)}` : '')
113
+ } else {
114
+ if (text.trim() === '') return fail('text is empty.')
115
+ payload = { text }
116
+ summary = `text (${text.length} characters)`
117
+ }
118
+
119
+ const { blob, keyText } = await encryptPayload({ ...payload, password: password || '' })
120
+ const res = await api.createE2e({ blob, duration: duration_hours, hasPassword: !!password })
121
+ const link = `${res.url}#${keyText}`
122
+
123
+ // Copie locale du secret généré, une fois le lien créé (pas de secret orphelin si l'API échoue)
124
+ if (generate_length && save_generated_to) {
125
+ const path = expandPath(save_generated_to)
126
+ if (save_generated_as_env) {
127
+ await appendEnvLine(path, save_generated_as_env, payload.text)
128
+ } else {
129
+ await writeFile(path, payload.text, { mode: 0o600, flag: 'wx' })
130
+ }
131
+ }
132
+
133
+ return ok(
134
+ `One-time link created for the ${summary}. It can be opened once; if never opened it expires in ${duration_hours} h.\n${link}` +
135
+ (password ? '\nA password is required to open it: the user must send it through another channel.' : ''),
136
+ { url: link, expires_in_hours: duration_hours, password_protected: !!password },
137
+ )
138
+ } catch (e) {
139
+ return fail(describeError(e))
140
+ }
141
+ })
142
+
143
+ // ── Lire un lien dans un fichier ─────────────────────────────────────────────
144
+ server.registerTool('read_secret_link_to_file', {
145
+ title: 'Open a one-time secret link into a local file',
146
+ description: [
147
+ 'Open a protonURL link and write its content to a local file, without showing the secret to the model',
148
+ '(only the size and file name are returned). Use it when a person sent a secret to configure something,',
149
+ 'e.g. write an API key into a .env file with env_var.',
150
+ 'WARNING: opening DESTROYS the link; nobody can open it again. If the link has a password, ask the user for it',
151
+ 'first: a wrong password also destroys the secret.',
152
+ ].join('\n'),
153
+ inputSchema: {
154
+ url: z.string().describe('The protonURL link, including the part after "#".'),
155
+ output_path: z.string().describe('Local file to write the secret to (created with permissions 600).'),
156
+ env_var: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).optional()
157
+ .describe('Append the secret as NAME=value to output_path (for .env files) instead of creating the file.'),
158
+ overwrite: z.boolean().default(false).describe('Allow replacing an existing output_path.'),
159
+ password: z.string().max(64).optional().describe('Password of the link, if it has one.'),
160
+ },
161
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
162
+ }, async ({ url, output_path, env_var, overwrite, password }) => {
163
+ const link = parseLink(url)
164
+ if (!link) return fail('This is not a protonURL link.')
165
+ const path = expandPath(output_path)
166
+
167
+ // Toutes les vérifications avant d'ouvrir le lien : l'ouverture le détruit
168
+ if (!env_var && !overwrite && await exists(path)) {
169
+ return fail(`${path} already exists. Choose another path, or set overwrite (or env_var to append).`)
170
+ }
171
+ const isE2e = link.id.length === 24
172
+ const raw = isE2e ? fromBase64Url(link.keyText || '') : null
173
+ if (isE2e && !raw) return fail('The link is incomplete: the key after "#" is missing or damaged. Ask for the full link.')
174
+
175
+ try {
176
+ const res = await api.view(link.id, { secretKey: isE2e ? undefined : password })
177
+ let text = ''
178
+ let fileBytes = null
179
+ let fileName = null
180
+
181
+ if (res.e2e) {
182
+ let out
183
+ try {
184
+ out = await decryptPayload(Buffer.from(res.data, 'base64'), raw, password || '')
185
+ } catch {
186
+ return fail('The link was opened (and is now destroyed) but could not be decrypted: wrong password or damaged key.')
187
+ }
188
+ text = out.header.text || ''
189
+ if (out.header.name || out.fileBytes.length) {
190
+ fileBytes = out.fileBytes
191
+ fileName = out.header.name
192
+ }
193
+ } else {
194
+ text = res.text || ''
195
+ if (res.file) {
196
+ fileBytes = new Uint8Array(Buffer.from(res.file.data, 'base64'))
197
+ fileName = res.file.name
198
+ }
199
+ }
200
+
201
+ const written = []
202
+ if (env_var) {
203
+ if (fileBytes) return fail('The link contains a file, which cannot be stored as an environment variable. Nothing was written; the link is now destroyed.')
204
+ if (/[\r\n]/.test(text)) return fail('The secret spans several lines and cannot be stored as NAME=value. Nothing was written; the link is now destroyed.')
205
+ await appendEnvLine(path, env_var, text)
206
+ written.push(`${env_var} appended to ${path}`)
207
+ } else if (fileBytes) {
208
+ await writeFile(path, fileBytes, { mode: 0o600 })
209
+ written.push(`file "${fileName ?? 'unnamed'}" (${fileBytes.length} bytes) written to ${path}`)
210
+ if (text.trim() !== '') {
211
+ await writeFile(`${path}.note.txt`, text, { mode: 0o600 })
212
+ written.push(`accompanying text written to ${path}.note.txt`)
213
+ }
214
+ } else {
215
+ await writeFile(path, text, { mode: 0o600 })
216
+ written.push(`secret (${text.length} characters) written to ${path}`)
217
+ }
218
+ return ok(`Link opened and destroyed. ${written.join('; ')}. The content was not shown here.`)
219
+ } catch (e) {
220
+ return fail(describeError(e))
221
+ }
222
+ })
223
+
224
+ // ── Statut d'un lien ─────────────────────────────────────────────────────────
225
+ server.registerTool('secret_link_status', {
226
+ title: 'Check whether a link was opened',
227
+ description: 'Tell whether a protonURL link has been opened or has expired, using its public deletion proof. Does not open the link and does not use API quota.',
228
+ inputSchema: { url: z.string().describe('The protonURL link (the part after "#" is ignored and never sent).') },
229
+ annotations: { readOnlyHint: true, openWorldHint: true },
230
+ }, async ({ url }) => {
231
+ const link = parseLink(url)
232
+ if (!link) return fail('This is not a protonURL link.')
233
+ try {
234
+ const res = await api.deletionProof(link.id)
235
+ if (res?.status === 'success') {
236
+ const { reason, deleted_at } = res.data
237
+ const state = reason === 'read' ? 'opened' : reason
238
+ return ok(`The link was ${state === 'opened' ? 'opened' : 'deleted (' + state + ')'} on ${deleted_at} (server time, Europe/Paris). It cannot be opened anymore.`,
239
+ { state, deleted_at })
240
+ }
241
+ return ok('No deletion proof yet: the link has not been opened and has not expired (or it never existed).', { state: 'pending' })
242
+ } catch (e) {
243
+ if (e instanceof ApiError && e.status === 404) {
244
+ return ok('No deletion proof yet: the link has not been opened and has not expired (or it never existed).', { state: 'pending' })
245
+ }
246
+ return fail(describeError(e))
247
+ }
248
+ })
249
+
250
+ // ── Quota ────────────────────────────────────────────────────────────────────
251
+ server.registerTool('protonurl_quota', {
252
+ title: 'protonURL API quota',
253
+ description: 'Show the plan and remaining API calls of the configured key. Creating and opening a link each use one call.',
254
+ inputSchema: {},
255
+ annotations: { readOnlyHint: true, openWorldHint: true },
256
+ }, async () => {
257
+ try {
258
+ const q = await api.quota()
259
+ const remaining = q.remaining === null ? 'unlimited' : `${q.remaining} of ${q.quota}`
260
+ return ok(`Plan ${q.plan}: ${remaining} calls remaining (${q.used} used), resets on ${q.reset_date}.`, q)
261
+ } catch (e) {
262
+ return fail(describeError(e))
263
+ }
264
+ })
265
+
266
+ await server.connect(new StdioServerTransport())