@carbonaitech/ottofiles-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,94 @@
1
- # Temporary Holding Version
1
+ # @carbonaitech/ottofiles-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
+ A [Model Context Protocol](https://modelcontextprotocol.io) server that exposes
4
+ OttoFiles read tools to an LLM, over the existing gateway, with real per-user
5
+ authorization. You **log in with your own account** (interactive OAuth) — no
6
+ secret to paste, no per-user provisioning. Every result is scoped to your own
7
+ security tier and ACLs: exactly what you'd see signed into OttoFiles.
8
+
9
+ ## Install
10
+
11
+ Requires Node.js 18 or later. No npm login or token is needed: the package is public.
12
+
13
+ **dev environment:**
14
+
15
+ ```bash
16
+ # Claude Code
17
+ claude mcp add ottofiles \
18
+ --env OTTOFILES_ISSUER=https://id.dev.carbonai.ca \
19
+ --env OTTOFILES_GATEWAY_URL=https://gateways.ottofiles.dev.carbonai.ca \
20
+ --env OTTOFILES_CLIENT_ID=ottofiles_mcp_cli \
21
+ -- npx -y @carbonaitech/ottofiles-mcp
22
+ ```
23
+
24
+ On the first tool call it opens your browser to sign in; the token (with a
25
+ refresh token) is cached under `~/.ottofiles-mcp/` and stays valid ~7 days. The
26
+ three URLs are per-environment and identical for every user.
27
+
28
+ ## Tools
29
+
30
+ All read-only, all scoped to the signed-in user's security tier and ACLs.
31
+
32
+ | Tool | Wraps | Purpose |
33
+ |------|-------|---------|
34
+ | `search_documents` | `POST /api/search/documents` | Find documents by text, number, type, status, policy, tier, or date — paged and sorted. |
35
+ | `group_documents` | `POST /api/search/documents/group` | Per-bucket counts + last-modified over the whole tier-visible corpus (the "group summary"). |
36
+ | `list_policies` | `GET /api/policies` | List accessible policies with code, name, state, and document count. |
37
+ | `get_policy_stats` | `GET /api/policies/{id}/stats` | Aggregate a policy: document count, storage, counts by type/status, top contributors. |
38
+ | `policy_access_roster` | `GET /api/policies/{id}/access-roster` | Who can access a policy and who is denied, with effective tier rank. |
39
+ | `get_document` | `GET /documents/{id}` | Full detail for one document: status, version, file metadata, anchors, lock state. |
40
+ | `get_document_versions` | `GET /documents/{id}/versions` | Every version — increment, label, file, upload status, who and when. |
41
+ | `document_access_roster` | `GET /api/documents/{id}/access-roster` | Who can access a document and who is denied, with effective tier rank. |
42
+ | `list_workspaces` | `GET /api/workspaces` | External share spaces — title, document and member counts, expiry state. |
43
+
44
+ ## Authentication
45
+
46
+ Two modes; the server picks one from its config.
47
+
48
+ **Interactive (default).** `authorization_code` + PKCE against IdentityServer,
49
+ with a loopback redirect (`http://127.0.0.1:8765-8767/callback`, RFC 8252). On
50
+ first use it opens the browser, you sign in as yourself, and it caches a
51
+ reference token + refresh token under `~/.ottofiles-mcp/` (7-day refresh; the MCP
52
+ sends `prompt=login`). The gateway introspects the same claims a web session
53
+ carries, so your tenant scoping and per-user tier/ACL checks apply unchanged. Set
54
+ only `OTTOFILES_CLIENT_ID` — the public PKCE client (`ottofiles_mcp_cli`),
55
+ registered in Identity by `ClientLoader`. No secret is stored.
56
+
57
+ **Headless (CI / no browser).** Set `OTTOFILES_CLIENT_SECRET` to a
58
+ `client_credentials` client (mint one with `provision/mint-mcp-credential.sh`)
59
+ and the server switches to that mode automatically. `OTTOFILES_AUTH_MODE` can
60
+ force either mode explicitly.
61
+
62
+ ## From source (local dev)
63
+
64
+ ```bash
65
+ npm install
66
+ npm run build
67
+ ```
68
+
69
+ The server is a plain **stdio Node process** the MCP client spawns — not a
70
+ container. Point it at a local `otto` stack; `docker ps` is the source of truth
71
+ for ports (`:8133` gateway, `:8101` identity — note `:8151` is the document-api
72
+ and `:8001` is another environment's identity, neither is what you want).
73
+ Register the local OAuth client once, then run it:
74
+
75
+ ```bash
76
+ # one-time: seed ottofiles_mcp_cli into the local identity DB
77
+ bash provision/register-oauth-client.sh
78
+
79
+ OTTOFILES_ISSUER=http://localhost:8101 \
80
+ OTTOFILES_GATEWAY_URL=http://localhost:8133 \
81
+ OTTOFILES_CLIENT_ID=ottofiles_mcp_cli \
82
+ npm run inspect # Inspector UI over the built server
83
+ # or: npm run dev # tsx src/index.ts over stdio
84
+ ```
85
+
86
+ Config is read from the environment, or from a `.env` in the package root (see
87
+ `.env.example`) — never from the current working directory. `provision/` holds
88
+ the credential scripts and their own README.
89
+
90
+ ## Roadmap
91
+
92
+ - Writes (upload, status transitions) — a separate track that needs a
93
+ confirmation story and tighter scoping.
94
+ - Blob / download streaming for document bytes.
package/dist/auth.js ADDED
@@ -0,0 +1,67 @@
1
+ // Refresh a little before actual expiry so an in-flight request never races the
2
+ // boundary.
3
+ const EXPIRY_SAFETY_MARGIN_MS = 60_000;
4
+ /**
5
+ * Mints and caches an OttoFiles reference token via the OAuth client_credentials
6
+ * grant. The client is a per-user "external client" (see
7
+ * IdentityCreateExternalClientConsumer in Services.Identity) whose user_id /
8
+ * company_id are baked into the client itself, so the token the gateway
9
+ * introspects carries the acting user's identity and the full per-user ACL /
10
+ * tier enforcement applies downstream unchanged.
11
+ */
12
+ export class TokenProvider {
13
+ config;
14
+ cached = null;
15
+ inFlight = null;
16
+ constructor(config) {
17
+ this.config = config;
18
+ }
19
+ /** Drop the cached token so the next getToken() re-mints. */
20
+ invalidate() {
21
+ this.cached = null;
22
+ }
23
+ async getToken() {
24
+ if (this.cached && Date.now() < this.cached.expiresAt) {
25
+ return this.cached.accessToken;
26
+ }
27
+ // Collapse concurrent refreshes into one token request.
28
+ if (this.inFlight)
29
+ return this.inFlight;
30
+ this.inFlight = this.fetchToken().finally(() => {
31
+ this.inFlight = null;
32
+ });
33
+ return this.inFlight;
34
+ }
35
+ async fetchToken() {
36
+ if (!this.config.clientSecret) {
37
+ throw new Error("client_credentials mode requires a client secret.");
38
+ }
39
+ const tokenEndpoint = `${this.config.issuer}/connect/token`;
40
+ const body = new URLSearchParams({
41
+ grant_type: "client_credentials",
42
+ client_id: this.config.clientId,
43
+ client_secret: this.config.clientSecret,
44
+ scope: this.config.scopes,
45
+ });
46
+ const res = await fetch(tokenEndpoint, {
47
+ method: "POST",
48
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
49
+ body,
50
+ });
51
+ if (!res.ok) {
52
+ const detail = await res.text().catch(() => "");
53
+ throw new Error(`Token request to ${tokenEndpoint} failed (${res.status} ${res.statusText}): ${detail}`);
54
+ }
55
+ const json = (await res.json());
56
+ if (!json.access_token) {
57
+ throw new Error("Token endpoint returned no access_token");
58
+ }
59
+ const expiresInMs = (json.expires_in ?? 3600) * 1000;
60
+ this.cached = {
61
+ accessToken: json.access_token,
62
+ expiresAt: Date.now() + Math.max(0, expiresInMs - EXPIRY_SAFETY_MARGIN_MS),
63
+ };
64
+ return json.access_token;
65
+ }
66
+ }
67
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAeA,gFAAgF;AAChF,YAAY;AACZ,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAEvC;;;;;;;GAOG;AACH,MAAM,OAAO,aAAa;IAIK;IAHrB,MAAM,GAAuB,IAAI,CAAC;IAClC,QAAQ,GAA2B,IAAI,CAAC;IAEhD,YAA6B,MAAuB;QAAvB,WAAM,GAAN,MAAM,CAAiB;IAAG,CAAC;IAExD,6DAA6D;IAC7D,UAAU;QACR,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,QAAQ;QACZ,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;YACtD,OAAO,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACjC,CAAC;QACD,wDAAwD;QACxD,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO,IAAI,CAAC,QAAQ,CAAC;QAExC,IAAI,CAAC,Q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CAAC,yCAAyC,CAAC,CAAC;QAC7D,CAAC;QAED,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC;QACrD,IAAI,CAAC,MAAM,GAAG;YACZ,WAAW,EAAE,IAAI,CAAC,YAAY;YAC9B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,GAAG,uBAAuB,CAAC;SAC3E,CAAC;QACF,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF"}
package/dist/config.js ADDED
@@ -0,0 +1,88 @@
1
+ import { readFileSync, existsSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // Minimal .env loader (no dependency). Values already present in the real
5
+ // environment win — so an MCP client that injects env via its JSON config
6
+ // stays authoritative, and .env only fills the gaps for local `npm run dev` /
7
+ // `inspect`. Looks in the cwd and in the package root (one level up from the
8
+ // compiled file).
9
+ function loadDotEnv() {
10
+ const here = dirname(fileURLToPath(import.meta.url));
11
+ // Load ONLY from the package root (dist/../.env), NEVER process.cwd(). The MCP
12
+ // host spawns this server with cwd = the user's current project dir, so a `.env`
13
+ // there could belong to an untrusted repo and silently override
14
+ // OTTOFILES_GATEWAY_URL/ISSUER/TOKEN_CACHE — redirecting an already-cached
15
+ // reference token to an attacker host. An explicit OTTOFILES_ENV_FILE overrides.
16
+ const explicit = process.env.OTTOFILES_ENV_FILE;
17
+ const candidates = explicit ? [explicit] : [join(here, "..", ".env")];
18
+ for (const path of candidates) {
19
+ if (!existsSync(path))
20
+ continue;
21
+ for (const raw of readFileSync(path, "utf8").split("\n")) {
22
+ const line = raw.trim();
23
+ if (!line || line.startsWith("#"))
24
+ continue;
25
+ const eq = line.indexOf("=");
26
+ if (eq === -1)
27
+ continue;
28
+ const key = line.slice(0, eq).trim();
29
+ if (key in process.env)
30
+ continue;
31
+ let value = line.slice(eq + 1).trim();
32
+ if ((value.startsWith('"') && value.endsWith('"')) ||
33
+ (value.startsWith("'") && value.endsWith("'"))) {
34
+ value = value.slice(1, -1);
35
+ }
36
+ process.env[key] = value;
37
+ }
38
+ break; // first file found wins
39
+ }
40
+ }
41
+ // OttoFiles per-user external clients are provisioned with these scopes
42
+ // (mirrors CreatePortalCredential in Services.Workspace). Search only strictly
43
+ // needs lukla_search_api, but the wider set keeps the same credential usable as
44
+ // more read tools are added.
45
+ const DEFAULT_SCOPES = "lukla_search_api lukla_document_api lukla_bin_api lukla_workspace_api lukla_permission_api lukla_storage_api";
46
+ function required(name) {
47
+ const value = process.env[name];
48
+ if (!value || value.trim() === "") {
49
+ throw new Error(`Missing required environment variable ${name}. See .env.example for the full list.`);
50
+ }
51
+ return value.trim();
52
+ }
53
+ export function loadConfig() {
54
+ loadDotEnv();
55
+ // A secret selects headless client_credentials; without one we do the
56
+ // interactive browser login (Path A). OTTOFILES_AUTH_MODE can force either.
57
+ const secret = process.env.OTTOFILES_CLIENT_SECRET?.trim() || null;
58
+ const forced = process.env.OTTOFILES_AUTH_MODE?.trim();
59
+ const mode = forced === "client_credentials" || (!forced && secret)
60
+ ? "client_credentials"
61
+ : "interactive";
62
+ if (mode === "client_credentials" && !secret) {
63
+ throw new Error("OTTOFILES_AUTH_MODE=client_credentials requires OTTOFILES_CLIENT_SECRET.");
64
+ }
65
+ return {
66
+ // The OttoFiles YARP gateway (container ottofiles-ottofiles-gateway),
67
+ // e.g. http://localhost:8133 locally.
68
+ gatewayUrl: required("OTTOFILES_GATEWAY_URL").replace(/\/+$/, ""),
69
+ // IdentityServer authority (container ottofiles-identity-api),
70
+ // e.g. http://localhost:8101 locally.
71
+ issuer: required("OTTOFILES_ISSUER").replace(/\/+$/, ""),
72
+ clientId: required("OTTOFILES_CLIENT_ID"),
73
+ clientSecret: secret,
74
+ scopes: (process.env.OTTOFILES_SCOPES ?? DEFAULT_SCOPES).trim(),
75
+ mode,
76
+ redirectPort: parseRedirectPort(process.env.OTTOFILES_REDIRECT_PORT),
77
+ };
78
+ }
79
+ function parseRedirectPort(raw) {
80
+ if (raw === undefined || raw.trim() === "")
81
+ return 8765;
82
+ const n = Number(raw);
83
+ if (!Number.isInteger(n) || n < 1 || n > 65533) {
84
+ throw new Error(`OTTOFILES_REDIRECT_PORT must be an integer 1-65533 (got "${raw}"). It must also match a registered redirect URI.`);
85
+ }
86
+ return n;
87
+ }
88
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAezC,0EAA0E;AAC1E,0EAA0E;AAC1E,8EAA8E;AAC9E,6EAA6E;AAC7E,kBAAkB;AAClB,SAAS,UAAU;IACjB,MAAM,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACrD,+EAA+E;IAC/E,iFAAiF;IACjF,gEAAgE;IAChE,2EAA2E;IAC3E,iFAAiF;IACjF,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC;IAChD,MAAM,UAAU,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;IACtE,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE,CAAC;QAC9B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YAAE,SAAS;QAChC,KAAK,MAAM,GAAG,IAAI,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;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EAAE;QAAE,OAAO,IAAI,CAAC;IACxD,MAAM,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IACtB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CACb,4DAA4D,GAAG,mDAAmD,CACnH,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC"}
@@ -0,0 +1,94 @@
1
+ export class GatewayError extends Error {
2
+ status;
3
+ body;
4
+ constructor(message, status, body) {
5
+ super(message);
6
+ this.status = status;
7
+ this.body = body;
8
+ this.name = "GatewayError";
9
+ }
10
+ }
11
+ /**
12
+ * Thin authed HTTP client for the OttoFiles gateway. Attaches the bearer token
13
+ * and retries exactly once on a 401 with a freshly-minted token (covers a token
14
+ * that expired or was revoked between cache and call).
15
+ */
16
+ export class GatewayClient {
17
+ config;
18
+ tokens;
19
+ // Cap concurrent in-flight requests so an LLM fanning out tool calls can't
20
+ // burst the gateway. Small pool; requests beyond it queue.
21
+ maxConcurrent = 4;
22
+ active = 0;
23
+ queue = [];
24
+ // Cap on 429 retries per request before giving up.
25
+ static MAX_429_RETRIES = 4;
26
+ constructor(config, tokens) {
27
+ this.config = config;
28
+ this.tokens = tokens;
29
+ }
30
+ async postJson(path, payload) {
31
+ return this.gate(() => this.request("POST", path, payload));
32
+ }
33
+ async getJson(path) {
34
+ return this.gate(() => this.request("GET", path));
35
+ }
36
+ /** Run `fn` under the concurrency limit. */
37
+ async gate(fn) {
38
+ if (this.active >= this.maxConcurrent) {
39
+ await new Promise((resolve) => this.queue.push(resolve));
40
+ }
41
+ this.active++;
42
+ try {
43
+ return await fn();
44
+ }
45
+ finally {
46
+ this.active--;
47
+ this.queue.shift()?.();
48
+ }
49
+ }
50
+ static sleep(ms) {
51
+ return new Promise((r) => setTimeout(r, ms));
52
+ }
53
+ async request(method, path, payload, isRetry = false, retry429 = 0) {
54
+ const token = await this.tokens.getToken();
55
+ const url = `${this.config.gatewayUrl}${path}`;
56
+ const res = await fetch(url, {
57
+ method,
58
+ headers: {
59
+ Authorization: `Bearer ${token}`,
60
+ Accept: "application/json",
61
+ ...(payload !== undefined
62
+ ? { "Content-Type": "application/json" }
63
+ : {}),
64
+ },
65
+ body: payload !== undefined ? JSON.stringify(payload) : undefined,
66
+ });
67
+ // Respect server-side rate limiting: honour Retry-After when present, else
68
+ // exponential backoff, up to a cap. Cooperates with any gateway throttle.
69
+ if (res.status === 429 && retry429 < GatewayClient.MAX_429_RETRIES) {
70
+ const retryAfter = Number(res.headers.get("retry-after"));
71
+ // Honour Retry-After, but cap it so a hostile/misconfigured header can't
72
+ // park a request (and its concurrency slot) for an hour.
73
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0
74
+ ? Math.min(retryAfter * 1000, 30_000)
75
+ : Math.min(1000 * 2 ** retry429, 8000);
76
+ await GatewayClient.sleep(waitMs);
77
+ return this.request(method, path, payload, isRetry, retry429 + 1);
78
+ }
79
+ if (res.status === 401 && !isRetry) {
80
+ // Drop the cached token so getToken() actually re-acquires (refresh, or
81
+ // re-mint) rather than replaying the same rejected token, then retry once.
82
+ this.tokens.invalidate();
83
+ return this.request(method, path, payload, true);
84
+ }
85
+ if (!res.ok) {
86
+ const body = await res.text().catch(() => "");
87
+ throw new GatewayError(`OttoFiles gateway ${method} ${path} failed: ${res.status} ${res.statusText}`, res.status, body);
88
+ }
89
+ // 204 or empty body
90
+ const text = await res.text();
91
+ return (text ? JSON.parse(text) : undefined);
92
+ }
93
+ }
94
+ //# sourceMappingURL=gateway.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway.js","sourceRoot":"","sources":["../src/gateway.ts"],"names":[],"mappings":"AAGA,MAAM,OAAO,YAAa,SAAQ,KAAK;IAG1B;IACA;IAHX,YACE,OAAe,EACN,MAAc,EACd,IAAY;QAErB,KAAK,CAAC,OAAO,CAAC,CAAC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LToPath } from "node:url";
4
+ import { dirname, join } from "node:path";
5
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
+ import { loadConfig } from "./config.js";
8
+ import { TokenProvider } from "./auth.js";
9
+ import { OAuthTokenProvider } from "./oauth.js";
10
+ import { GatewayClient, GatewayError } from "./gateway.js";
11
+ import { searchDocumentsInput, runSearchDocuments, } from "./tools/searchDocuments.js";
12
+ import { groupDocumentsInput, runGroupDocuments, } from "./tools/groupDocuments.js";
13
+ import { listPoliciesInput, runListPolicies } from "./tools/listPolicies.js";
14
+ import { getDocumentInput, runGetDocument } from "./tools/getDocument.js";
15
+ import { documentAccessRosterInput, runDocumentAccessRoster, } from "./tools/documentAccessRoster.js";
16
+ import { getDocumentVersionsInput, runGetDocumentVersions, } from "./tools/getDocumentVersions.js";
17
+ import { listWorkspacesInput, runListWorkspaces, } from "./tools/listWorkspaces.js";
18
+ import { policyAccessRosterInput, runPolicyAccessRoster, } from "./tools/policyAccessRoster.js";
19
+ import { getPolicyStatsInput, runGetPolicyStats } from "./tools/getPolicyStats.js";
20
+ // The publish workflow stamps package.json's version from the git tag; read it
21
+ // so the server reports the same version rather than a hardcoded one.
22
+ function readVersion() {
23
+ try {
24
+ const pkg = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
25
+ return JSON.parse(readFileSync(pkg, "utf8")).version ?? "0.0.0";
26
+ }
27
+ catch {
28
+ return "0.0.0";
29
+ }
30
+ }
31
+ function jsonContent(data) {
32
+ return {
33
+ content: [
34
+ { type: "text", text: JSON.stringify(data, null, 2) },
35
+ ],
36
+ };
37
+ }
38
+ function errorContent(err) {
39
+ let text;
40
+ if (err instanceof GatewayError) {
41
+ text =
42
+ `OttoFiles request failed (HTTP ${err.status}).\n${err.message}` +
43
+ (err.body ? `\nResponse: ${err.body.slice(0, 800)}` : "");
44
+ }
45
+ else if (err instanceof Error) {
46
+ text = err.message;
47
+ }
48
+ else {
49
+ text = String(err);
50
+ }
51
+ return { isError: true, content: [{ type: "text", text }] };
52
+ }
53
+ async function main() {
54
+ const config = loadConfig();
55
+ const tokens = config.mode === "interactive"
56
+ ? new OAuthTokenProvider(config)
57
+ : new TokenProvider(config);
58
+ console.error(`ottofiles-mcp: auth mode = ${config.mode}`);
59
+ const gateway = new GatewayClient(config, tokens);
60
+ const server = new McpServer({
61
+ name: "ottofiles-mcp",
62
+ version: readVersion(),
63
+ });
64
+ server.registerTool("search_documents", {
65
+ title: "Search OttoFiles documents",
66
+ description: "Search documents across the caller's accessible OttoFiles policies with rich filters, sorting and pagination. Results are scoped by the acting user's tier and ACLs. Use this to find documents by text, number, type, status, policy, or date.",
67
+ inputSchema: searchDocumentsInput,
68
+ }, async (args) => {
69
+ try {
70
+ return jsonContent(await runSearchDocuments(gateway, args));
71
+ }
72
+ catch (err) {
73
+ return errorContent(err);
74
+ }
75
+ });
76
+ server.registerTool("group_documents", {
77
+ title: "Group / summarize OttoFiles documents",
78
+ description: "Bucket the caller's accessible documents by a field (policyId, statusCodeId, tierId, documentType, or anchor:<Name>) and return per-bucket counts and last-modified dates. Use this for summaries like 'how many documents per status' over the whole corpus, not a page.",
79
+ inputSchema: groupDocumentsInput,
80
+ }, async (args) => {
81
+ try {
82
+ return jsonContent(await runGroupDocuments(gateway, args));
83
+ }
84
+ catch (err) {
85
+ return errorContent(err);
86
+ }
87
+ });
88
+ server.registerTool("list_policies", {
89
+ title: "List OttoFiles policies",
90
+ description: "List the caller's accessible OttoFiles policies (formerly 'bins') with code, name, description and document count. Filter by search/state, paged. Use this to discover policy ids for scoping document searches.",
91
+ inputSchema: listPoliciesInput,
92
+ }, async (args) => {
93
+ try {
94
+ return jsonContent(await runListPolicies(gateway, args));
95
+ }
96
+ catch (err) {
97
+ return errorContent(err);
98
+ }
99
+ });
100
+ server.registerTool("get_document", {
101
+ title: "Get an OttoFiles document",
102
+ description: "Fetch full detail for one document by its GUID: title, number, policy, status, version info, file metadata, lock state, and anchor (metadata) values. Subject to the caller's access.",
103
+ inputSchema: getDocumentInput,
104
+ }, async (args) => {
105
+ try {
106
+ return jsonContent(await runGetDocument(gateway, args));
107
+ }
108
+ catch (err) {
109
+ return errorContent(err);
110
+ }
111
+ });
112
+ server.registerTool("document_access_roster", {
113
+ title: "Document access roster",
114
+ description: "List which users can access a given document and who is denied, with effective tier rank and access/denied counts. Use this to answer 'who can see this document'.",
115
+ inputSchema: documentAccessRosterInput,
116
+ }, async (args) => {
117
+ try {
118
+ return jsonContent(await runDocumentAccessRoster(gateway, args));
119
+ }
120
+ catch (err) {
121
+ return errorContent(err);
122
+ }
123
+ });
124
+ server.registerTool("get_document_versions", {
125
+ title: "List a document's versions",
126
+ description: "List every version of a document (increment number, version label, file, upload status, who uploaded and when). Use this for version history.",
127
+ inputSchema: getDocumentVersionsInput,
128
+ }, async (args) => {
129
+ try {
130
+ return jsonContent(await runGetDocumentVersions(gateway, args));
131
+ }
132
+ catch (err) {
133
+ return errorContent(err);
134
+ }
135
+ });
136
+ server.registerTool("get_policy_stats", {
137
+ title: "Get policy statistics",
138
+ description: "Aggregate stats for one policy: document count, storage used, counts by type and status, top contributors, and recent activity. Requires admin, an open published policy, or a Policy.Read grant.",
139
+ inputSchema: getPolicyStatsInput,
140
+ }, async (args) => {
141
+ try {
142
+ return jsonContent(await runGetPolicyStats(gateway, args));
143
+ }
144
+ catch (err) {
145
+ return errorContent(err);
146
+ }
147
+ });
148
+ server.registerTool("list_workspaces", {
149
+ title: "List OttoFiles workspaces",
150
+ description: "List the caller's accessible workspaces (external document-share spaces) with title, document count, member count, and expiry/revocation state.",
151
+ inputSchema: listWorkspacesInput,
152
+ }, async (args) => {
153
+ try {
154
+ return jsonContent(await runListWorkspaces(gateway, args));
155
+ }
156
+ catch (err) {
157
+ return errorContent(err);
158
+ }
159
+ });
160
+ server.registerTool("policy_access_roster", {
161
+ title: "Policy access roster",
162
+ description: "List which users can access a given policy and who is denied, with effective tier rank and access/denied counts. Use this to answer 'who can see this policy'.",
163
+ inputSchema: policyAccessRosterInput,
164
+ }, async (args) => {
165
+ try {
166
+ return jsonContent(await runPolicyAccessRoster(gateway, args));
167
+ }
168
+ catch (err) {
169
+ return errorContent(err);
170
+ }
171
+ });
172
+ const transport = new StdioServerTransport();
173
+ await server.connect(transport);
174
+ // stderr is safe for logging under stdio transport; stdout is the protocol.
175
+ console.error("ottofiles-mcp: connected over stdio");
176
+ }
177
+ main().catch((err) => {
178
+ console.error("ottofiles-mcp: fatal", err);
179
+ process.exit(1);
180
+ });
181
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAoB,MAAM,YAAY,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EACL,yBAAyB,EACzB,uBAAuB,GACxB,MAAM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