@pallino.me/mcp 0.0.0-stage → 0.2.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gorlix
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.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ # pallino-mcp
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
+ MCP server for [Pallino Cloud](https://cloud.pallino.me): lets an AI client read and manage your spaces, projects, notes and tasks through the Pallino agent API (`/v1/agent/*`).
4
+
5
+ - Transports: stdio (local) and stateless Streamable HTTP (remote, `/mcp`).
6
+ - Auth: your Pallino API key, passed as env var (stdio), as a Bearer token, or through a built-in OAuth 2.1 facade (for claude.ai connectors).
7
+ - What the agent can do is limited by the grants of the key you give it.
8
+
9
+ ## Tools
10
+
11
+ | Tool | What it does |
12
+ | --- | --- |
13
+ | `pallino_list_spaces` | Spaces the key reaches, members and granted actions |
14
+ | `pallino_list_projects` | Projects of a space |
15
+ | `pallino_create_project` | Create a project |
16
+ | `pallino_rename_project` | Rename a project |
17
+ | `pallino_delete_project` | Delete a project (notes and tasks stay) |
18
+ | `pallino_list_notes` | List/search notes (no body) |
19
+ | `pallino_get_note` | One note with body |
20
+ | `pallino_create_note` | Create a note, list, template or bookmark |
21
+ | `pallino_update_note` | Update fields; omitted fields unchanged |
22
+ | `pallino_delete_note` | Delete a note |
23
+ | `pallino_list_tasks` | List/search tasks, filter by done, due range, project |
24
+ | `pallino_get_task` | One task |
25
+ | `pallino_create_task` | Create a task |
26
+ | `pallino_update_task` | Update fields; `null` clears |
27
+ | `pallino_complete_task` | Mark done (or reopen with `done: false`) |
28
+ | `pallino_delete_task` | Delete a task |
29
+
30
+ It also exposes the resource `pallino://capabilities` (server limits and supported actions).
31
+
32
+ ## Quick start (local, stdio)
33
+
34
+ 1. Create a Pallino API key with the minimum grants you need (in the app, or `POST /v1/keys`). Give it only the spaces and actions the agent should have.
35
+ 2. Add the server to your client.
36
+
37
+ Claude Code:
38
+
39
+ ```sh
40
+ claude mcp add pallino -e PALLINO_API_KEY=pallino_xxx -- npx -y @pallino.me/mcp
41
+ ```
42
+
43
+ Claude Desktop (`claude_desktop_config.json`), Cursor and most other clients:
44
+
45
+ ```json
46
+ {
47
+ "mcpServers": {
48
+ "pallino": {
49
+ "command": "npx",
50
+ "args": ["-y", "@pallino.me/mcp"],
51
+ "env": { "PALLINO_API_KEY": "pallino_xxx", "PALLINO_TIMEZONE": "Europe/Rome" }
52
+ }
53
+ }
54
+ }
55
+ ```
56
+
57
+ Set `PALLINO_TIMEZONE` (IANA name) so "today" is computed in your zone; it falls back to `TZ`, then the server zone.
58
+
59
+ ## Remote / self-host
60
+
61
+ ```sh
62
+ docker run -d -p 3000:3000 \
63
+ -e OAUTH_SECRET="$(openssl rand -hex 32)" \
64
+ -e PUBLIC_URL=https://mcp.example.com \
65
+ -e TRUST_PROXY=1 \
66
+ ghcr.io/gorlix/pallino-mcp:latest
67
+ ```
68
+
69
+ Generate `OAUTH_SECRET` once and keep it stable: a new value logs every connected client out.
70
+
71
+ Or use [`docker-compose.example.yml`](docker-compose.example.yml). Without Docker: `npx -y @pallino.me/mcp --transport http --port 3000`.
72
+
73
+ Put a reverse proxy with HTTPS in front. OAuth clients require HTTPS, and `PUBLIC_URL` must be the exact public origin.
74
+
75
+ **claude.ai custom connector:** add a connector with URL `https://mcp.example.com/mcp`. During the OAuth flow a page asks you to paste your Pallino API key; the server checks it against Pallino and seals it into the tokens.
76
+
77
+ **Clients that support headers:** skip OAuth and send `Authorization: Bearer pallino_xxx` to `/mcp`. This works with or without `OAUTH_SECRET`.
78
+
79
+ **Self-hosted Pallino:** set `PALLINO_BASE_URL` to your Pallino server (default `https://cloud.pallino.me`).
80
+
81
+ Health check: `GET /healthz`.
82
+
83
+ ## Configuration
84
+
85
+ | Variable | Default | Description |
86
+ | --- | --- | --- |
87
+ | `MCP_TRANSPORT` | `stdio` | `stdio` or `http` (flag `--transport`) |
88
+ | `PALLINO_API_KEY` | | Key for stdio; for HTTP only used with `ALLOW_ENV_KEY` |
89
+ | `PALLINO_BASE_URL` | `https://cloud.pallino.me` | Pallino server |
90
+ | `PALLINO_TIMEZONE` / `TZ` | server zone | IANA zone used for "today" |
91
+ | `HOST` | `127.0.0.1` | HTTP bind address (flag `--host`); Docker image uses `0.0.0.0` |
92
+ | `PORT` | `3000` | HTTP port (flag `--port`) |
93
+ | `PUBLIC_URL` | `http://HOST:PORT` | Public origin, used by OAuth metadata and host checks |
94
+ | `OAUTH_SECRET` | | 32+ chars; enables the OAuth facade |
95
+ | `ALLOW_ENV_KEY` | `false` | HTTP: use `PALLINO_API_KEY` when a request has no Authorization header |
96
+ | `TRUST_PROXY` | | Express `trust proxy` (`true`, a hop count, or a subnet) |
97
+
98
+ ## Security notes
99
+
100
+ - API keys are never logged and never put in URLs.
101
+ - OAuth is stateless: client ids, codes and tokens are AES-256-GCM sealed blobs holding the Pallino key. There is no database.
102
+ - Changing `OAUTH_SECRET` revokes every client and token.
103
+ - To cut an agent's access for good, revoke the key in Pallino.
104
+ - Authorization codes are single-use per process only (they also expire after 2 minutes and need PKCE S256). Access tokens last 1 hour, refresh tokens 90 days.
105
+ - Keep `ALLOW_ENV_KEY` off on a public server: it lets anonymous callers use your key.
106
+
107
+ ## Development
108
+
109
+ ```sh
110
+ npm ci
111
+ npm run dev # tsx src/index.ts
112
+ npm run typecheck
113
+ npm test # PALLINO_LIVE_KEY=... enables the read-only live test
114
+ npm run build
115
+ ```
116
+
117
+ MIT License.
package/dist/client.js ADDED
@@ -0,0 +1,79 @@
1
+ export const DEFAULT_BASE_URL = "https://cloud.pallino.me";
2
+ export class PallinoError extends Error {
3
+ status;
4
+ code;
5
+ field;
6
+ constructor(status, code, message, field) {
7
+ super(message);
8
+ this.status = status;
9
+ this.code = code;
10
+ this.field = field;
11
+ this.name = "PallinoError";
12
+ }
13
+ }
14
+ /** Thin wrapper over the Pallino Cloud agent API (`/v1/agent/*`), authenticated with one API key. */
15
+ export class PallinoClient {
16
+ apiKey;
17
+ baseUrl;
18
+ fetchImpl;
19
+ timeoutMs;
20
+ constructor(apiKey, baseUrl = DEFAULT_BASE_URL, fetchImpl = fetch, timeoutMs = 30_000) {
21
+ this.apiKey = apiKey;
22
+ this.baseUrl = baseUrl;
23
+ this.fetchImpl = fetchImpl;
24
+ this.timeoutMs = timeoutMs;
25
+ }
26
+ async request(method, path, opts = {}) {
27
+ const url = new URL(path, this.baseUrl.endsWith("/") ? this.baseUrl : this.baseUrl + "/");
28
+ for (const [k, v] of Object.entries(opts.query ?? {})) {
29
+ if (v !== undefined && v !== null)
30
+ url.searchParams.set(k, String(v));
31
+ }
32
+ const headers = { Accept: "application/json", "User-Agent": "pallino-mcp" };
33
+ if (this.apiKey)
34
+ headers.Authorization = `Bearer ${this.apiKey}`;
35
+ if (opts.body !== undefined)
36
+ headers["Content-Type"] = "application/json";
37
+ const init = {
38
+ method,
39
+ headers,
40
+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
41
+ };
42
+ let res = await this.send(url, init);
43
+ if (res.status === 429) {
44
+ // One retry, only when the server asks for a short wait.
45
+ const wait = Number(res.headers.get("retry-after"));
46
+ if (Number.isFinite(wait) && wait >= 0 && wait <= 10) {
47
+ await new Promise((r) => setTimeout(r, wait * 1000));
48
+ res = await this.send(url, init);
49
+ }
50
+ }
51
+ if (res.status === 204)
52
+ return undefined;
53
+ const text = await res.text();
54
+ let data;
55
+ try {
56
+ data = text ? JSON.parse(text) : undefined;
57
+ }
58
+ catch {
59
+ data = undefined;
60
+ }
61
+ if (!res.ok) {
62
+ const err = data?.error;
63
+ let message = err?.message ?? (text.slice(0, 200) || res.statusText);
64
+ if (res.status === 429)
65
+ message += ` (retry after ${res.headers.get("retry-after") ?? "?"}s)`;
66
+ throw new PallinoError(res.status, err?.code ?? `http_${res.status}`, message, err?.field);
67
+ }
68
+ return data;
69
+ }
70
+ async send(url, init) {
71
+ try {
72
+ return await this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
73
+ }
74
+ catch (e) {
75
+ const reason = e instanceof Error ? e.message : String(e);
76
+ throw new PallinoError(0, "network_error", `Cannot reach ${url.origin}: ${reason}`);
77
+ }
78
+ }
79
+ }
package/dist/config.js ADDED
@@ -0,0 +1,31 @@
1
+ import { DEFAULT_BASE_URL } from "./client.js";
2
+ export function loadConfig(argv = process.argv.slice(2), env = process.env) {
3
+ const flag = (name) => {
4
+ const i = argv.indexOf(`--${name}`);
5
+ if (i >= 0)
6
+ return argv[i + 1];
7
+ return argv.find((a) => a.startsWith(`--${name}=`))?.split("=").slice(1).join("=");
8
+ };
9
+ const transport = (flag("transport") ?? env.MCP_TRANSPORT ?? "stdio").toLowerCase();
10
+ if (transport !== "stdio" && transport !== "http")
11
+ throw new Error(`Unknown transport "${transport}" (use stdio or http)`);
12
+ const port = Number(flag("port") ?? env.PORT ?? 3000);
13
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
14
+ throw new Error(`Invalid port "${port}"`);
15
+ const timeZone = env.PALLINO_TIMEZONE || env.TZ || undefined;
16
+ if (timeZone)
17
+ new Intl.DateTimeFormat("en", { timeZone }); // throws RangeError on an unknown zone
18
+ const trust = env.TRUST_PROXY;
19
+ return {
20
+ transport,
21
+ baseUrl: env.PALLINO_BASE_URL || DEFAULT_BASE_URL,
22
+ apiKey: env.PALLINO_API_KEY || undefined,
23
+ timeZone,
24
+ host: flag("host") ?? env.HOST ?? "127.0.0.1",
25
+ port,
26
+ publicUrl: env.PUBLIC_URL || undefined,
27
+ oauthSecret: env.OAUTH_SECRET || undefined,
28
+ allowEnvKey: env.ALLOW_ENV_KEY === "true",
29
+ trustProxy: trust === undefined || trust === "" ? undefined : trust === "true" ? true : /^\d+$/.test(trust) ? Number(trust) : trust,
30
+ };
31
+ }
package/dist/http.js ADDED
@@ -0,0 +1,73 @@
1
+ import express from "express";
2
+ import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { mcpAuthRouter, getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/sdk/server/auth/router.js";
5
+ import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
6
+ import { PallinoOAuthProvider, verifyBearer } from "./oauth.js";
7
+ const APPROVE_PATH = "/oauth/approve";
8
+ export function createHttpApp(cfg, buildServer) {
9
+ const publicUrl = new URL(cfg.publicUrl ?? `http://${cfg.host === "0.0.0.0" ? "localhost" : cfg.host}:${cfg.port}`);
10
+ const mcpUrl = new URL("/mcp", publicUrl);
11
+ // Host-header check guards against DNS rebinding; behind a public URL allow it plus loopback (container healthcheck).
12
+ const app = createMcpExpressApp({ host: cfg.host, allowedHosts: cfg.publicUrl ? [publicUrl.hostname, "localhost", "127.0.0.1", "[::1]"] : undefined });
13
+ app.disable("x-powered-by");
14
+ if (cfg.trustProxy)
15
+ app.set("trust proxy", cfg.trustProxy);
16
+ app.use((_req, res, next) => {
17
+ res.setHeader("X-Content-Type-Options", "nosniff");
18
+ res.setHeader("X-Frame-Options", "DENY");
19
+ res.setHeader("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' https: http:; frame-ancestors 'none'");
20
+ res.setHeader("Referrer-Policy", "no-referrer");
21
+ next();
22
+ });
23
+ app.get("/healthz", (_req, res) => void res.json({ ok: true }));
24
+ let verifier = { verifyAccessToken: async (t) => verifyBearer(t) };
25
+ if (cfg.oauthSecret) {
26
+ const provider = new PallinoOAuthProvider({ secret: cfg.oauthSecret, pallinoBaseUrl: cfg.baseUrl, approvePath: APPROVE_PATH });
27
+ verifier = provider;
28
+ app.use(mcpAuthRouter({
29
+ provider,
30
+ issuerUrl: publicUrl,
31
+ resourceServerUrl: mcpUrl,
32
+ resourceName: "Pallino",
33
+ serviceDocumentationUrl: new URL("https://github.com/gorlix/pallino-mcp"),
34
+ clientRegistrationOptions: { clientIdGeneration: false },
35
+ }));
36
+ app.post(APPROVE_PATH, express.urlencoded({ extended: false, limit: "16kb" }), async (req, res) => {
37
+ const { pending, api_key } = (req.body ?? {});
38
+ if (typeof pending !== "string" || typeof api_key !== "string")
39
+ return void res.status(400).send("Bad request");
40
+ await provider.approve(pending, api_key, res);
41
+ });
42
+ }
43
+ const bearer = requireBearerAuth({
44
+ verifier,
45
+ resourceMetadataUrl: cfg.oauthSecret ? getOAuthProtectedResourceMetadataUrl(mcpUrl) : undefined,
46
+ });
47
+ const auth = cfg.allowEnvKey && cfg.apiKey
48
+ ? (req, res, next) => (req.headers.authorization ? bearer(req, res, next) : next())
49
+ : bearer;
50
+ // Stateless Streamable HTTP: a fresh server and transport per request, so any instance can serve any call.
51
+ const handle = async (req, res) => {
52
+ const server = buildServer();
53
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
54
+ res.on("close", () => {
55
+ void transport.close();
56
+ void server.close();
57
+ });
58
+ try {
59
+ await server.connect(transport);
60
+ await transport.handleRequest(req, res, req.body);
61
+ }
62
+ catch (e) {
63
+ console.error("MCP request failed:", e instanceof Error ? e.message : e);
64
+ if (!res.headersSent)
65
+ res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null });
66
+ }
67
+ };
68
+ app.post("/mcp", auth, handle);
69
+ const notAllowed = (_req, res) => void res.status(405).set("Allow", "POST").json({ jsonrpc: "2.0", error: { code: -32000, message: "Method not allowed (stateless server)" }, id: null });
70
+ app.get("/mcp", notAllowed);
71
+ app.delete("/mcp", notAllowed);
72
+ return app;
73
+ }
package/dist/index.js ADDED
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { createRequire } from "node:module";
5
+ import { PallinoClient } from "./client.js";
6
+ import { loadConfig } from "./config.js";
7
+ import { INSTRUCTIONS, registerTools } from "./tools.js";
8
+ import { createHttpApp } from "./http.js";
9
+ const { version } = createRequire(import.meta.url)("../package.json");
10
+ export function buildServer(cfg) {
11
+ const server = new McpServer({ name: "pallino-mcp", title: "Pallino", version }, { instructions: INSTRUCTIONS });
12
+ registerTools(server, (extra) => {
13
+ // HTTP: the caller's own key. stdio (or ALLOW_ENV_KEY without a header): the configured key.
14
+ const key = typeof extra?.apiKey === "string" ? extra.apiKey : cfg.transport === "stdio" || cfg.allowEnvKey ? cfg.apiKey : undefined;
15
+ return new PallinoClient(key, cfg.baseUrl);
16
+ }, { timeZone: cfg.timeZone });
17
+ return server;
18
+ }
19
+ async function main() {
20
+ const cfg = loadConfig();
21
+ if (cfg.transport === "stdio") {
22
+ if (!cfg.apiKey)
23
+ console.error("pallino-mcp: PALLINO_API_KEY is not set; every tool call will fail with unauthorized.");
24
+ await buildServer(cfg).connect(new StdioServerTransport());
25
+ return;
26
+ }
27
+ const app = createHttpApp(cfg, () => buildServer(cfg));
28
+ app.listen(cfg.port, cfg.host, () => {
29
+ console.error(`pallino-mcp ${version} listening on http://${cfg.host}:${cfg.port}/mcp (OAuth ${cfg.oauthSecret ? "on" : "off"})`);
30
+ });
31
+ }
32
+ main().catch((e) => {
33
+ console.error("pallino-mcp:", e instanceof Error ? e.message : e);
34
+ process.exit(1);
35
+ });
package/dist/oauth.js ADDED
@@ -0,0 +1,188 @@
1
+ import { createCipheriv, createDecipheriv, hkdfSync, randomBytes, createHash } from "node:crypto";
2
+ import { InvalidGrantError, InvalidTokenError, InvalidClientMetadataError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
3
+ import { PallinoClient } from "./client.js";
4
+ /**
5
+ * Stateless OAuth 2.1 facade: the user pastes a Pallino API key on our authorize page; every artifact
6
+ * (client_id, pending request, code, access and refresh token) is an AES-256-GCM sealed blob.
7
+ * No database. Rotating OAUTH_SECRET invalidates every client and token.
8
+ */
9
+ export const API_KEY_RE = /^pallino_[A-Za-z0-9_-]{20,100}$/;
10
+ const ACCESS_TTL = 3600;
11
+ const REFRESH_TTL = 90 * 24 * 3600;
12
+ const CODE_TTL = 120;
13
+ const PENDING_TTL = 15 * 60;
14
+ export class Sealer {
15
+ key;
16
+ constructor(secret) {
17
+ if (secret.length < 32)
18
+ throw new Error("OAUTH_SECRET must be at least 32 characters");
19
+ this.key = Buffer.from(hkdfSync("sha256", secret, "pallino-mcp", "oauth-seal-v1", 32));
20
+ }
21
+ seal(kind, payload, ttl) {
22
+ const iv = randomBytes(12);
23
+ const c = createCipheriv("aes-256-gcm", this.key, iv);
24
+ c.setAAD(Buffer.from(kind));
25
+ const pt = Buffer.from(JSON.stringify({ ...payload, exp: Math.floor(Date.now() / 1000) + ttl }));
26
+ const ct = Buffer.concat([c.update(pt), c.final()]);
27
+ return Buffer.concat([iv, c.getAuthTag(), ct]).toString("base64url");
28
+ }
29
+ /** Returns the payload, or undefined when forged, of another kind, or expired. */
30
+ open(kind, token) {
31
+ try {
32
+ const raw = Buffer.from(token, "base64url");
33
+ if (raw.length < 29)
34
+ return undefined;
35
+ const d = createDecipheriv("aes-256-gcm", this.key, raw.subarray(0, 12));
36
+ d.setAAD(Buffer.from(kind));
37
+ d.setAuthTag(raw.subarray(12, 28));
38
+ const p = JSON.parse(Buffer.concat([d.update(raw.subarray(28)), d.final()]).toString());
39
+ return p.exp >= Math.floor(Date.now() / 1000) ? p : undefined;
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ }
46
+ const clientHash = (clientId) => createHash("sha256").update(clientId).digest("base64url").slice(0, 22);
47
+ export class PallinoOAuthProvider {
48
+ opts;
49
+ sealer;
50
+ usedCodes = new Map();
51
+ constructor(opts) {
52
+ this.opts = opts;
53
+ this.sealer = new Sealer(opts.secret);
54
+ }
55
+ get clientsStore() {
56
+ return {
57
+ getClient: (clientId) => {
58
+ const blob = this.sealer.open("client", clientId);
59
+ return blob ? { ...blob, client_id: clientId } : undefined;
60
+ },
61
+ registerClient: (client) => {
62
+ if (client.redirect_uris.length > 10)
63
+ throw new InvalidClientMetadataError("Too many redirect_uris");
64
+ const blob = {
65
+ redirect_uris: client.redirect_uris,
66
+ token_endpoint_auth_method: client.token_endpoint_auth_method,
67
+ grant_types: client.grant_types,
68
+ response_types: client.response_types,
69
+ client_name: client.client_name?.slice(0, 100),
70
+ client_secret: client.client_secret,
71
+ client_secret_expires_at: client.client_secret_expires_at,
72
+ client_id_issued_at: Math.floor(Date.now() / 1000),
73
+ };
74
+ return { ...blob, client_id: this.sealer.seal("client", blob, 10 * 365 * 24 * 3600) };
75
+ },
76
+ };
77
+ }
78
+ async authorize(client, params, res) {
79
+ const pending = this.sealer.seal("pending", {
80
+ c: client.client_id,
81
+ r: params.redirectUri,
82
+ ch: params.codeChallenge,
83
+ s: params.state,
84
+ res: params.resource?.href,
85
+ sc: params.scopes,
86
+ }, PENDING_TTL);
87
+ res.status(200).type("html").send(authorizePage({ pending, approvePath: this.opts.approvePath, clientName: client.client_name, redirectUri: params.redirectUri }));
88
+ }
89
+ /** Handles the authorize page form: validates the key against Pallino, then redirects with a code. */
90
+ async approve(pendingToken, apiKey, res) {
91
+ const p = this.sealer.open("pending", pendingToken);
92
+ if (!p) {
93
+ res.status(400).type("html").send(errorPage("This authorization request expired. Start again from your AI client."));
94
+ return;
95
+ }
96
+ const key = apiKey.trim();
97
+ const retry = (msg) => res.status(400).type("html").send(authorizePage({ pending: pendingToken, approvePath: this.opts.approvePath, redirectUri: p.r, error: msg }));
98
+ if (!API_KEY_RE.test(key))
99
+ return void retry("That is not a Pallino API key (it starts with pallino_).");
100
+ try {
101
+ await new PallinoClient(key, this.opts.pallinoBaseUrl, this.opts.fetchImpl).request("GET", "v1/agent/spaces");
102
+ }
103
+ catch {
104
+ return void retry("Pallino did not accept this key: check it is correct, not expired and not revoked.");
105
+ }
106
+ const code = this.sealer.seal("code", { k: key, c: clientHash(p.c), r: p.r, ch: p.ch, res: p.res, sc: p.sc }, CODE_TTL);
107
+ const target = new URL(p.r);
108
+ target.searchParams.set("code", code);
109
+ if (p.s !== undefined)
110
+ target.searchParams.set("state", p.s);
111
+ res.redirect(302, target.href);
112
+ }
113
+ openGrant(kind, client, token) {
114
+ const g = this.sealer.open(kind, token);
115
+ if (!g || g.c !== clientHash(client.client_id))
116
+ throw new InvalidGrantError(`Invalid or expired ${kind === "code" ? "authorization code" : "refresh token"}`);
117
+ return g;
118
+ }
119
+ async challengeForAuthorizationCode(client, code) {
120
+ return this.openGrant("code", client, code).ch;
121
+ }
122
+ async exchangeAuthorizationCode(client, code, _verifier, redirectUri) {
123
+ const g = this.openGrant("code", client, code);
124
+ if (redirectUri !== undefined && redirectUri !== g.r)
125
+ throw new InvalidGrantError("redirect_uri does not match");
126
+ // shortcut: single-use is enforced per process only; codes also expire in 2 minutes and need PKCE.
127
+ const now = Date.now() / 1000;
128
+ for (const [c, exp] of this.usedCodes)
129
+ if (exp < now)
130
+ this.usedCodes.delete(c);
131
+ if (this.usedCodes.has(code))
132
+ throw new InvalidGrantError("Authorization code already used");
133
+ this.usedCodes.set(code, now + CODE_TTL);
134
+ return this.issue(g);
135
+ }
136
+ async exchangeRefreshToken(client, refreshToken) {
137
+ return this.issue(this.openGrant("refresh", client, refreshToken));
138
+ }
139
+ issue(g) {
140
+ const grant = { k: g.k, c: g.c, res: g.res, sc: g.sc };
141
+ return {
142
+ access_token: this.sealer.seal("access", grant, ACCESS_TTL),
143
+ token_type: "Bearer",
144
+ expires_in: ACCESS_TTL,
145
+ refresh_token: this.sealer.seal("refresh", grant, REFRESH_TTL),
146
+ scope: g.sc?.join(" "),
147
+ };
148
+ }
149
+ async verifyAccessToken(token) {
150
+ return verifyBearer(token, this.sealer);
151
+ }
152
+ }
153
+ /** Accepts a raw Pallino API key (passthrough) or, when a sealer is given, an access token from the facade. */
154
+ export function verifyBearer(token, sealer) {
155
+ if (API_KEY_RE.test(token)) {
156
+ // Pallino validates the key itself on every call; expiry here only satisfies the bearer middleware.
157
+ return { token, clientId: "api-key", scopes: [], expiresAt: Math.floor(Date.now() / 1000) + 3600, extra: { apiKey: token } };
158
+ }
159
+ const g = sealer?.open("access", token);
160
+ if (!g)
161
+ throw new InvalidTokenError("Invalid or expired token");
162
+ return { token, clientId: g.c, scopes: g.sc ?? [], expiresAt: g.exp, resource: g.res ? new URL(g.res) : undefined, extra: { apiKey: g.k } };
163
+ }
164
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
165
+ function shell(body) {
166
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
167
+ <title>Connect Pallino</title><style>
168
+ :root{color-scheme:light dark;font-family:system-ui,sans-serif}body{max-width:28rem;margin:10vh auto;padding:0 1rem;line-height:1.5}
169
+ input{width:100%;box-sizing:border-box;padding:.6rem;font:inherit;font-family:ui-monospace,monospace;margin:.5rem 0 1rem}
170
+ button{padding:.6rem 1.2rem;font:inherit;cursor:pointer}.err{color:#c0392b}.muted{opacity:.7;font-size:.9em}code{word-break:break-all}
171
+ </style></head><body>${body}</body></html>`;
172
+ }
173
+ function authorizePage(o) {
174
+ return shell(`<h1>Connect Pallino</h1>
175
+ <p>${o.clientName ? `<strong>${esc(o.clientName)}</strong>` : "An application"} wants to access your Pallino account.</p>
176
+ <p class="muted">It will be able to do only what the key allows. After you approve, you go back to <code>${esc(new URL(o.redirectUri).origin)}</code>.</p>
177
+ ${o.error ? `<p class="err" role="alert">${esc(o.error)}</p>` : ""}
178
+ <form method="post" action="${esc(o.approvePath)}">
179
+ <input type="hidden" name="pending" value="${esc(o.pending)}">
180
+ <label for="key">Pallino API key</label>
181
+ <input id="key" name="api_key" type="password" autocomplete="off" required placeholder="pallino_…" pattern="pallino_.+">
182
+ <button type="submit">Connect</button>
183
+ </form>
184
+ <p class="muted">Create a dedicated API key in Pallino, granting only the spaces and actions you want this application to use.</p>`);
185
+ }
186
+ function errorPage(msg) {
187
+ return shell(`<h1>Connect Pallino</h1><p class="err" role="alert">${esc(msg)}</p>`);
188
+ }
package/dist/tools.js ADDED
@@ -0,0 +1,212 @@
1
+ import { z } from "zod";
2
+ import { PallinoError } from "./client.js";
3
+ export const INSTRUCTIONS = `Pallino is a notes-and-tasks app. Data lives in spaces (personal or shared with other members).
4
+ Each space holds projects, notes (types: note, list, template, bookmark; Markdown body) and tasks.
5
+ - Start with pallino_list_spaces: it returns space ids, members (their membership id is what goes in a task's "who"), and the actions this API key is granted per type. A 403 means the key lacks that action.
6
+ - Notes and tasks can belong to a project; a task can link to a note and have a parent task (two levels at most).
7
+ - Tasks: due/deadline are dates (YYYY-MM-DD), time/deadline_time are HH:MM, prio 1 (urgent) to 4 (none). Completing a recurring task moves it to its next date instead of marking it done.
8
+ - Updates accept an optional "revision" from the last read: if someone changed the record since, the call fails with "conflict"; re-read and retry.
9
+ - Replaced note text is kept as a version server-side, so edits never lose data. Deleting is permanent.
10
+ - Lists are paginated (limit up to 200, offset); "more": true means another page exists.`;
11
+ const id = (what) => z.string().uuid().describe(`${what} id (UUID)`);
12
+ const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "YYYY-MM-DD");
13
+ const hhmm = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$|^$/, "HH:MM (24h) or empty");
14
+ const tags = z.array(z.string().min(1).max(50)).max(3).describe("Up to 3 tags, 1-50 chars each");
15
+ const limit = z.number().int().min(1).max(200).optional().describe("Max records (default 50, max 200)");
16
+ const offset = z.number().int().min(0).max(100000).optional().describe("Records to skip (default 0)");
17
+ const revision = z
18
+ .number()
19
+ .int()
20
+ .min(0)
21
+ .optional()
22
+ .describe("Revision from your last read; if the record changed since, the call fails with conflict. Omit or 0 to overwrite.");
23
+ const projectName = z.string().min(1).max(100).regex(/^[^\r\n]*$/, "no newlines").describe("1-100 chars, no newlines");
24
+ const noteFields = {
25
+ title: z.string().max(500).regex(/^[^\r\n]*$/, "no newlines").optional().describe("Up to 500 chars, no newlines"),
26
+ body: z.string().optional().describe("Markdown body (title + body up to 1 MiB)"),
27
+ pinned: z.boolean().optional().describe("Pinned (templates are never pinned)"),
28
+ archived: z.boolean().optional().describe("Archived (templates are never archived)"),
29
+ tags: tags.optional(),
30
+ project_id: id("Project").nullable().optional().describe("Project of the same space; null removes it"),
31
+ };
32
+ const recurrence = z
33
+ .object({
34
+ unit: z.enum(["day", "week", "month", "year", "weekday"]),
35
+ interval: z.number().int().min(1).max(999).describe("Every N units (1 for weekday)"),
36
+ from_completion: z.boolean().optional().describe("Count the next date from completion instead of the due date"),
37
+ })
38
+ .nullable()
39
+ .describe("Recurrence rule; null removes it");
40
+ const taskFields = {
41
+ title: z.string().max(500).regex(/^[^\r\n]*$/, "no newlines").optional().describe("Up to 500 chars, no newlines"),
42
+ desc: z.string().optional().describe("Description"),
43
+ due: date.nullable().optional().describe("Planned day YYYY-MM-DD; null clears"),
44
+ time: hhmm.nullable().optional().describe("Planned time HH:MM; empty/null none"),
45
+ deadline: date.nullable().optional().describe("Deadline day YYYY-MM-DD; null clears"),
46
+ deadline_time: hhmm.nullable().optional().describe("Deadline time HH:MM; empty/null none"),
47
+ prio: z.number().int().min(1).max(4).optional().describe("1 urgent ... 4 none"),
48
+ duration_minutes: z.number().int().min(1).max(1440).nullable().optional().describe("Estimated minutes"),
49
+ tags: tags.optional(),
50
+ who: z.string().max(100).optional().describe("Assignee: a member's membership id (see pallino_list_spaces), a free name, or empty"),
51
+ location: z.string().max(200).optional(),
52
+ recurrence: recurrence.optional(),
53
+ project_id: id("Project").nullable().optional().describe("Project of the same space; null removes it"),
54
+ note_id: id("Note").nullable().optional().describe("Linked note of the same space; null removes it"),
55
+ parent_id: id("Parent task").nullable().optional().describe("Parent task (must have no parent itself); null removes it"),
56
+ };
57
+ const RO = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
58
+ const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
59
+ const EDIT = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true };
60
+ const DELETE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true };
61
+ /** Today's date in the given IANA time zone (the Pallino server cannot know the caller's zone). */
62
+ export function todayIn(timeZone) {
63
+ return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date());
64
+ }
65
+ function ok(data) {
66
+ const structured = data && typeof data === "object" && !Array.isArray(data) ? data : { result: data ?? "ok" };
67
+ return { content: [{ type: "text", text: JSON.stringify(data ?? { ok: true }, null, 2) }], structuredContent: structured };
68
+ }
69
+ const HINTS = {
70
+ unauthorized: "The API key is missing, expired or revoked.",
71
+ forbidden: "This API key is not granted the action needed for this change in this space (see actions in pallino_list_spaces).",
72
+ not_found: "The record does not exist or this key cannot see it.",
73
+ conflict: "The record changed since the given revision: re-read it and retry with the new revision.",
74
+ rate_limited: "Too many requests: wait and retry.",
75
+ };
76
+ function fail(e) {
77
+ if (e instanceof PallinoError) {
78
+ const hint = HINTS[e.code] ?? (e.status === 403 ? HINTS.forbidden : e.status === 404 ? HINTS.not_found : "");
79
+ const field = e.field ? ` (field: ${e.field})` : "";
80
+ return { isError: true, content: [{ type: "text", text: `Pallino error ${e.status} ${e.code}${field}: ${e.message}${hint ? `\n${hint}` : ""}` }] };
81
+ }
82
+ return { isError: true, content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }] };
83
+ }
84
+ /** Drops undefined values so omitted fields stay unchanged server-side (null is kept: it clears). */
85
+ function compact(o) {
86
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
87
+ }
88
+ export function registerTools(server, resolve, opts = {}) {
89
+ const run = (fn) => async (args, extra) => {
90
+ try {
91
+ return ok(await fn(resolve(extra.authInfo?.extra), args));
92
+ }
93
+ catch (e) {
94
+ return fail(e);
95
+ }
96
+ };
97
+ const today = (given) => given ?? todayIn(opts.timeZone);
98
+ const seg = encodeURIComponent;
99
+ // Spaces
100
+ server.registerTool("pallino_list_spaces", {
101
+ title: "List spaces",
102
+ description: "List the spaces this API key reaches, with members (membership ids for task assignment) and the actions granted per type.",
103
+ inputSchema: {},
104
+ annotations: RO,
105
+ }, run((c) => c.request("GET", "v1/agent/spaces")));
106
+ // Projects
107
+ server.registerTool("pallino_list_projects", { title: "List projects", description: "List the projects of a space.", inputSchema: { space_id: id("Space") }, annotations: RO }, run((c, a) => c.request("GET", `v1/agent/spaces/${seg(a.space_id)}/projects`)));
108
+ server.registerTool("pallino_create_project", { title: "Create project", description: "Create a project in a space.", inputSchema: { space_id: id("Space"), name: projectName }, annotations: WRITE }, run((c, a) => c.request("POST", `v1/agent/spaces/${seg(a.space_id)}/projects`, { body: { name: a.name } })));
109
+ server.registerTool("pallino_rename_project", { title: "Rename project", description: "Rename a project.", inputSchema: { project_id: id("Project"), name: projectName, revision }, annotations: EDIT }, run((c, a) => c.request("PATCH", `v1/agent/projects/${seg(a.project_id)}`, { body: compact({ name: a.name, revision: a.revision }) })));
110
+ server.registerTool("pallino_delete_project", {
111
+ title: "Delete project",
112
+ description: "Permanently delete a project. Its notes and tasks stay in the space, without project.",
113
+ inputSchema: { project_id: id("Project") },
114
+ annotations: DELETE,
115
+ }, run(async (c, a) => {
116
+ await c.request("DELETE", `v1/agent/projects/${seg(a.project_id)}`);
117
+ return { deleted: a.project_id };
118
+ }));
119
+ // Notes
120
+ server.registerTool("pallino_list_notes", {
121
+ title: "List notes",
122
+ description: "List or search the notes of a space (without body; use pallino_get_note for it).",
123
+ inputSchema: {
124
+ space_id: id("Space"),
125
+ q: z.string().optional().describe("Case-insensitive search in title or body"),
126
+ type: z.enum(["note", "list", "template", "bookmark"]).optional(),
127
+ archived: z.boolean().optional().describe("true only archived, false only not archived; omit for both"),
128
+ project_id: id("Project").optional(),
129
+ limit,
130
+ offset,
131
+ },
132
+ annotations: RO,
133
+ }, run((c, { space_id, ...query }) => c.request("GET", `v1/agent/spaces/${seg(space_id)}/notes`, { query })));
134
+ server.registerTool("pallino_get_note", { title: "Get note", description: "Get one note with its body.", inputSchema: { note_id: id("Note") }, annotations: RO }, run((c, a) => c.request("GET", `v1/agent/notes/${seg(a.note_id)}`)));
135
+ server.registerTool("pallino_create_note", {
136
+ title: "Create note",
137
+ description: "Create a note in a space. All fields optional.",
138
+ inputSchema: {
139
+ space_id: id("Space"),
140
+ ...noteFields,
141
+ type: z.enum(["note", "list", "template", "bookmark"]).optional().describe("Chosen only at creation (default note)"),
142
+ },
143
+ annotations: WRITE,
144
+ }, run((c, { space_id, ...body }) => c.request("POST", `v1/agent/spaces/${seg(space_id)}/notes`, { body: compact(body) })));
145
+ server.registerTool("pallino_update_note", {
146
+ title: "Update note",
147
+ description: "Update a note. Omitted fields stay unchanged. body replaces the whole text (the old text is kept as a version). title/body need 'edit'; pinned/archived/tags/project_id need 'organize'.",
148
+ inputSchema: { note_id: id("Note"), ...noteFields, revision },
149
+ annotations: EDIT,
150
+ }, run((c, { note_id, ...body }) => c.request("PATCH", `v1/agent/notes/${seg(note_id)}`, { body: compact(body) })));
151
+ server.registerTool("pallino_delete_note", { title: "Delete note", description: "Permanently delete a note and its versions.", inputSchema: { note_id: id("Note") }, annotations: DELETE }, run(async (c, a) => {
152
+ await c.request("DELETE", `v1/agent/notes/${seg(a.note_id)}`);
153
+ return { deleted: a.note_id };
154
+ }));
155
+ // Tasks
156
+ server.registerTool("pallino_list_tasks", {
157
+ title: "List tasks",
158
+ description: "List or search the tasks of a space. Date filters are inclusive; tasks without a due day are outside any date range.",
159
+ inputSchema: {
160
+ space_id: id("Space"),
161
+ q: z.string().optional().describe("Case-insensitive search in title or description"),
162
+ done: z.boolean().optional().describe("true only done, false only to do; omit for both"),
163
+ due_from: date.optional().describe("From this due day, inclusive"),
164
+ due_to: date.optional().describe("To this due day, inclusive"),
165
+ project_id: id("Project").optional(),
166
+ note_id: id("Note").optional(),
167
+ parent_id: id("Parent task").optional().describe("Only subtasks of this task"),
168
+ limit,
169
+ offset,
170
+ },
171
+ annotations: RO,
172
+ }, run((c, { space_id, ...query }) => c.request("GET", `v1/agent/spaces/${seg(space_id)}/tasks`, { query })));
173
+ server.registerTool("pallino_get_task", { title: "Get task", description: "Get one task.", inputSchema: { task_id: id("Task") }, annotations: RO }, run((c, a) => c.request("GET", `v1/agent/tasks/${seg(a.task_id)}`)));
174
+ server.registerTool("pallino_create_task", {
175
+ title: "Create task",
176
+ description: "Create a task in a space.",
177
+ inputSchema: { space_id: id("Space"), ...taskFields, title: taskFields.title.unwrap().min(1).describe("Task title, up to 500 chars") },
178
+ annotations: WRITE,
179
+ }, run((c, { space_id, ...body }) => c.request("POST", `v1/agent/spaces/${seg(space_id)}/tasks`, { body: { ...compact(body), today: today() } })));
180
+ server.registerTool("pallino_update_task", {
181
+ title: "Update task",
182
+ description: "Update a task. Omitted fields stay unchanged; null clears. due/time/deadline/deadline_time need 'reschedule', done needs 'complete', the rest 'edit'.",
183
+ inputSchema: {
184
+ task_id: id("Task"),
185
+ ...taskFields,
186
+ done: z.boolean().optional().describe("true completes the occurrence (a recurring task moves to its next date); false reopens"),
187
+ started: z.boolean().optional().describe("Manually started"),
188
+ revision,
189
+ },
190
+ annotations: EDIT,
191
+ }, run((c, { task_id, ...body }) => c.request("PATCH", `v1/agent/tasks/${seg(task_id)}`, { body: { ...compact(body), today: today() } })));
192
+ server.registerTool("pallino_complete_task", {
193
+ title: "Complete task",
194
+ description: "Mark a task done (a recurring task moves to its next date and updates its habit streak). Set done=false to reopen.",
195
+ inputSchema: { task_id: id("Task"), done: z.boolean().optional().describe("Default true") },
196
+ annotations: EDIT,
197
+ }, run((c, a) => c.request("PATCH", `v1/agent/tasks/${seg(a.task_id)}`, { body: { done: a.done ?? true, today: today() } })));
198
+ server.registerTool("pallino_delete_task", {
199
+ title: "Delete task",
200
+ description: "Permanently delete a task. Its subtasks stay, without parent.",
201
+ inputSchema: { task_id: id("Task") },
202
+ annotations: DELETE,
203
+ }, run(async (c, a) => {
204
+ await c.request("DELETE", `v1/agent/tasks/${seg(a.task_id)}`);
205
+ return { deleted: a.task_id };
206
+ }));
207
+ // Server capabilities (public, no key needed).
208
+ server.registerResource("capabilities", "pallino://capabilities", { title: "Pallino server capabilities", description: "Limits and agent actions supported by the Pallino server", mimeType: "application/json" }, async (uri, extra) => {
209
+ const data = await resolve(extra.authInfo?.extra).request("GET", "v1/capabilities");
210
+ return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(data, null, 2) }] };
211
+ });
212
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@pallino.me/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "MCP server for Pallino Cloud: spaces, projects, notes and tasks via the agent API. stdio, Streamable HTTP and OAuth.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "gorlix",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/gorlix/pallino-mcp.git"
11
+ },
12
+ "homepage": "https://github.com/gorlix/pallino-mcp#readme",
13
+ "mcpName": "io.github.gorlix/pallino-mcp",
14
+ "keywords": [
15
+ "mcp",
16
+ "model-context-protocol",
17
+ "pallino",
18
+ "notes",
19
+ "tasks",
20
+ "claude"
21
+ ],
22
+ "bin": {
23
+ "pallino-mcp": "dist/index.js"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "engines": {
31
+ "node": ">=20"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.build.json",
35
+ "typecheck": "tsc --noEmit",
36
+ "test": "vitest run",
37
+ "dev": "tsx src/index.ts",
38
+ "start": "node dist/index.js",
39
+ "prepublishOnly": "npm run build"
40
+ },
41
+ "dependencies": {
42
+ "@modelcontextprotocol/sdk": "^1.32.2",
43
+ "express": "^5.3.0",
44
+ "zod": "^4.6.7"
45
+ },
46
+ "devDependencies": {
47
+ "@types/express": "^5.0.6",
48
+ "@types/node": "^26.6.10",
49
+ "tsx": "^4.23.15",
50
+ "typescript": "^7.0.2",
51
+ "vitest": "^5.1.2"
52
+ }
53
+ }