@tempo-ai/mcp 0.0.143-staging.1 → 0.0.144-staging.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/README.md CHANGED
@@ -97,6 +97,11 @@ They require Playwright's Chromium once per machine:
97
97
  npx playwright install chromium
98
98
  ```
99
99
 
100
+ Canvas capture uses the capture SDK runtime bundled inside `@tempo-ai/mcp`.
101
+ MCP does not install the visual-review CLI. The public `tempo-sdk` stays
102
+ minimal, and no separate runtime download or credentials are needed. `TEMPO_SDK_RUNTIME_PATH` can select an explicitly
103
+ provisioned compatible provider instead.
104
+
100
105
  Share links require the canvas's branch to be committed and pushed.
101
106
 
102
107
  ### Visual review setup
package/dist/bin.js CHANGED
@@ -1,19 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire as __tempoCreateRequire } from 'node:module'; const require = __tempoCreateRequire(import.meta.url);
3
- import {
4
- run
5
- } from "./chunk-NZ7THB2V.js";
6
- import "./chunk-4R6XIZCX.js";
7
- import "./chunk-JKT5N6IQ.js";
8
-
9
- // src/bin.ts
10
- run(process.argv).then(
11
- (code) => {
12
- if (typeof code === "number") process.exit(code);
13
- },
14
- (err) => {
15
- console.error(err instanceof Error ? err.stack || err.message : err);
16
- process.exit(1);
17
- }
18
- );
19
- //# sourceMappingURL=bin.js.map
2
+ import{createRequire as r}from"node:module";r(import.meta.url);import{run as e}from"./chunk-2AGTI4OY.js";import"./chunk-OB7GTENV.js";import"./chunk-NCFWHGWN.js";e(process.argv).then(r=>{"number"==typeof r&&process.exit(r)},r=>{console.error(r instanceof Error?r.stack||r.message:r),process.exit(1)});
@@ -0,0 +1 @@
1
+ import{createRequire as t}from"node:module";t(import.meta.url);import{ensureCliAuth as o,parseServeArgs as e}from"./chunk-OB7GTENV.js";import"./chunk-NCFWHGWN.js";import{Client as r}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as n}from"@modelcontextprotocol/sdk/inMemory.js";async function connectAggregate(t){const{createTempoAggregate:o}=await(import("./serve-N3733IZL.js")),e=await o(t,{stageDocuments:!1}),[s,a]=n.createLinkedPair(),c=new r({name:"tempo-mcp-cli",version:"0"});return await e.aggregate.connect(a),await c.connect(s),{client:c,dispose:async()=>{await c.close(),await e.dispose()}}}function extractFlag(t,o){const e=t.filter(t=>t!==o);return{present:e.length!==t.length,rest:e}}async function runTools(t){const{present:r,rest:n}=extractFlag(t,"--schemas"),s=e(n);if("error"in s)return console.error(s.error),1;await o();const{client:a,dispose:c}=await connectAggregate(s);try{const{tools:t}=await a.listTools(),o=t.map(t=>r?{name:t.name,description:t.description,inputSchema:t.inputSchema}:{name:t.name,description:t.description});return console.log(JSON.stringify({tools:o},null,2)),0}finally{await c()}}async function runCall(t){const[r,...n]=t;if(!r||r.startsWith("--"))return console.error('Usage: tempo-mcp call <tool> --json \'{"orgId": "...", ...}\'\nDiscover tools and their schemas with `tempo-mcp tools --schemas`.'),1;let s=null;const a=[];for(let t=0;t<n.length;t++)"--json"===n[t]?s=n[++t]??null:a.push(n[t]);let c={};if(null!=s){"-"===s&&(s=await readStdin());try{const t=JSON.parse(s);if(null===t||"object"!=typeof t||Array.isArray(t))return console.error("--json must be a JSON object of tool arguments"),1;c=t}catch(t){return console.error(`--json is not valid JSON: ${t instanceof Error?t.message:String(t)}`),1}}const i=e(a);if("error"in i)return console.error(i.error),1;await o();const{client:l,dispose:m}=await connectAggregate(i);try{const t=await l.callTool({name:r,arguments:c}),o=Array.isArray(t.content)?t.content:[];for(const t of o)"text"===t.type?console.log(t.text):console.log(JSON.stringify(t));return t.isError?1:0}finally{await m()}}function readStdin(){return new Promise((t,o)=>{const e=[];process.stdin.on("data",t=>e.push(Buffer.from(t))),process.stdin.on("end",()=>t(Buffer.concat(e).toString("utf8"))),process.stdin.on("error",o)})}export{runCall,runTools};
@@ -0,0 +1 @@
1
+ import{createRequire as e}from"node:module";e(import.meta.url);import{NotSignedInError as o,clearAuth as n,ensureCliAuth as t,envAccessToken as r,parseServeArgs as s,readAuth as a,runLogin as i}from"./chunk-OB7GTENV.js";var l='tempo-mcp <subcommand>\n\nTempo\'s MCP server — issues, docs, comments, agents, scripts, Slack,\nLinear, and (inside a Tempo repo) canvas tools, served as ONE stdio MCP\nserver.\n\nGet started (no account needed first):\n claude mcp add tempo -- npx -y @tempo-ai/mcp\n Then use any Tempo tool from Claude Code — the first one that needs\n Tempo opens the browser to sign in or create an account. Other hosts\n (Codex / Cursor) take the same command:\n { "tempo": { "command": "npx", "args": ["-y", "@tempo-ai/mcp"] } }\n\nScoping: the AI passes an explicit orgId (and projectId where\nproject-scoped) on every tool call, discovered via the built-in\ntempo_list_orgs / tempo_list_projects tools. Nothing org-related is\nconfigured on the connection.\n\nServer:\n (default) | serve Serve the aggregate MCP server over stdio\n --toolsets a,b Only these toolsets (issues,docs,comments,agents,\n scripts,slack,linear,canvas,design-context). Default: all.\n --readonly Register no write tools at all\n\nDirect tool access (for hosts without MCP support — Codex cloud, bots):\n tools [--schemas] List every tool (add --schemas for arg schemas)\n call <tool> --json \'{"orgId": "..."}\'\n Invoke any tool; same pipeline as the MCP server.\n --json - reads the argument object from stdin.\n Both accept --toolsets / --readonly.\n\nAuth (identity only — optional; the server prompts on first use):\n login Sign in via the browser ahead of time\n logout Clear stored credentials (~/.tempo/auth.json)\n whoami Show the signed-in user (exchanges TEMPO_AUTH_TOKEN\n if set — the smoke test for headless environments)\n token create [--name <label>]\n Mint a personal access token (printed once) for\n headless environments — cloud sandboxes with no\n browser. Set it there as TEMPO_AUTH_TOKEN.\n token list List your tokens\n token revoke <id-or-prefix>\n Revoke a token\n\nEnvironment:\n TEMPO_CONVEX_URL Override the Convex deployment (default: production)\n TEMPO_MCP_READONLY=1 Same as --readonly\n TEMPO_AUTH_TOKEN Personal access token — signs in without a browser\n TEMPO_MCP_NO_BROWSER=1 Never open a browser; sign-in links are only\n printed / returned to the host\n TEMPO_MCP_SIGN_IN_WAIT_MS\n How long a tool call waits for the browser sign-in\n before returning the link (default 120000)\n';async function runWhoami(){let e=await a();if(r())try{await t(),e=await a()}catch(e){return console.error("TEMPO_AUTH_TOKEN sign-in failed:",e instanceof Error?e.message:String(e)),1}if(!e)return console.log("Not signed in. Use a Tempo tool from your agent to get a sign-in link, or run `npx -y @tempo-ai/mcp login`."),1;const o=e.email?`${e.email} (${e.userId})`:e.userId;console.log(`Signed in as: ${o}`);const n=e.expiresAt-Date.now();return n<=0?console.log(`Token state: expired ${Math.round(-n/1e3)}s ago (refresh on next call)`):console.log(`Token state: fresh, expires in ${Math.round(n/1e3)}s`),0}async function runLogout(){return await n(),console.log("Signed out. The next Tempo tool call from your agent will prompt for sign-in (or run `npx -y @tempo-ai/mcp login`)."),0}async function run(e){const[,,n,...t]=e;if("--help"===n||"-h"===n||"help"===n)return process.stdout.write(l),0;try{if(!n||"serve"===n||n.startsWith("--")){const e=n&&"serve"!==n?[n,...t]:t,o=s(e);if("error"in o)return console.error(o.error),process.stderr.write(l),1;const{runServe:r}=await(import("./serve-N3733IZL.js"));return await r(o)}switch(n){case"login":return await i();case"logout":return await runLogout();case"whoami":return await runWhoami();case"token":{const{runToken:e}=await(import("./token-ARFG52GQ.js"));return await e(t)}case"tools":{const{runTools:e}=await(import("./call-Z4FCZLBP.js"));return await e(t)}case"call":{const{runCall:e}=await(import("./call-Z4FCZLBP.js"));return await e(t)}default:return console.error(`Unknown subcommand: ${n}`),process.stderr.write(l),1}}catch(e){return e instanceof o?(console.error(e.message),1):(console.error(e instanceof Error?e.stack||e.message:String(e)),1)}}export{run};
@@ -0,0 +1 @@
1
+ import{createRequire as e}from"node:module";const require=e(import.meta.url);var r=Object.create,t=Object.defineProperty,o=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,u=Object.getPrototypeOf,i=Object.prototype.hasOwnProperty,p=(e=>void 0!==require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,r)=>(void 0!==require?require:e)[r]}):e)(function(e){if(void 0!==require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),__esm=(e,r)=>function __init(){return e&&(r=(0,e[n(e)[0]])(e=0)),r},__commonJS=(e,r)=>function __require2(){return r||(0,e[n(e)[0]])((r={exports:{}}).exports,r),r.exports},__export=(e,r)=>{for(var o in r)t(e,o,{get:r[o],enumerable:!0})},__copyProps=(e,r,u,p)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let a of n(r))i.call(e,a)||a===u||t(e,a,{get:()=>r[a],enumerable:!(p=o(r,a))||p.enumerable});return e},__toESM=(e,o,n)=>(n=null!=e?r(u(e)):{},__copyProps(!o&&e&&e.__esModule?n:t(n,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(t({},"__esModule",{value:!0}),e);export{p as __require,__esm,__commonJS,__export,__toESM,__toCommonJS};
@@ -0,0 +1 @@
1
+ import{createRequire as e}from"node:module";e(import.meta.url);import t from"fs";import n from"fs/promises";import o from"path";import r from"os";import s from"path";function tempoHome(){return process.env.TEMPO_MCP_HOME??s.join(r.homedir(),".tempo")}function authFilePath(){return s.join(tempoHome(),"auth.json")}function logsDir(){return s.join(tempoHome(),"logs")}function logFilePath(e){const t=(new Date).toISOString().slice(0,10);return s.join(logsDir(),`mcp-${e}-${t}.log`)}async function readAuth(){try{const e=await n.readFile(authFilePath(),"utf8"),t=JSON.parse(e);return"string"==typeof t.token&&"string"==typeof t.sessionId&&"string"==typeof t.userId&&"number"==typeof t.expiresAt?t:null}catch(e){return e.code,null}}function readAuthSync(){try{const e=t.readFileSync(authFilePath(),"utf8"),n=JSON.parse(e);return"string"==typeof n.token&&"string"==typeof n.sessionId&&"string"==typeof n.userId&&"number"==typeof n.expiresAt?n:null}catch{return null}}async function writeAuth(e){const t=tempoHome();await n.mkdir(t,{recursive:!0,mode:448});const r=authFilePath(),s=o.join(t,`auth.json.tmp.${process.pid}.${Date.now()}`),i=JSON.stringify(e,null,2);await n.writeFile(s,i,{mode:384}),await n.rename(s,r);try{await n.chmod(r,384)}catch{}}async function clearAuth(){try{await n.unlink(authFilePath())}catch(e){if("ENOENT"!==e.code)throw e}}function createRefreshLoop(e){const t=e.refreshLeadMs??6e4,n=e.retryDelayMs??5e3,o=e.maxRetries??3;let r=null,s=!1;async function reauthOrGiveUp(){if(e.attemptReauth)try{if(await e.attemptReauth()){const e=await readAuth();if(e)return e.token}}catch{}return e.onReauthRequired(),null}async function refreshNow(){const t=await readAuth();if(!t)return reauthOrGiveUp();for(let r=0;r<=o;r++)try{const s=await fetch(`${e.convexSiteUrl}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t.sessionId})});if(401===s.status)return await clearAuth(),reauthOrGiveUp();if(!s.ok){if(r<o){await sleep(n*Math.pow(1.5,r));continue}return reauthOrGiveUp()}const i=await s.json();if(!i.token)return reauthOrGiveUp();const a={...t,token:i.token,expiresAt:decodeJwtExp(i.token)};return await writeAuth(a),i.token}catch(e){if(r<o){await sleep(n*Math.pow(1.5,r));continue}return reauthOrGiveUp()}return null}function schedule(e){if(r&&clearTimeout(r),s)return;const n=Math.max(0,e.expiresAt-Date.now()-t);r=setTimeout(()=>{refreshNow().then(e=>{e&&!s&&readAuth().then(e=>{e&&schedule(e)})})},n)}function start(){s=!1,readAuth().then(e=>{e&&schedule(e)})}function stop(){s=!0,r&&(clearTimeout(r),r=null)}return{start,stop,refreshNow}}function sleep(e){return new Promise(t=>setTimeout(t,e))}function decodeJwtExp(e){try{const[,t]=e.split("."),n=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if("number"==typeof n.exp)return 1e3*n.exp}catch{}return Date.now()+3e5}function createAuthProvider(e){return{async getToken(){const t=await readAuth();if(!t)throw new Error("Not signed in to Tempo. Retry the tool to get a sign-in link, or run `npx -y @tempo-ai/mcp login`.");if(t.expiresAt-Date.now()<3e4){const t=await e.refreshNow();if(t){const e=await readAuth();if(e)return{jwt:e.token,expiresAt:e.expiresAt}}throw new Error("Tempo session expired. Retry the tool to get a sign-in link, or run `npx -y @tempo-ai/mcp login`.")}return{jwt:t.token,expiresAt:t.expiresAt}}}}import i from"http";import{randomBytes as a,createHash as c}from"crypto";async function startBrowserAuthFlow(e={}){const t=e.authUrl??"https://auth.tempo.build",n=e.timeoutMs??6e5,o=e.bindAddress??"127.0.0.1",r=a(32).toString("base64url"),s=a(32).toString("base64url"),l=c("sha256").update(s).digest("base64url"),u=e.convexSiteUrl??process.env.TEMPO_LOGIN_SITE_URL??"https://greedy-jackal-526.convex.site";let p,d,h=!1;const f=new Promise((e,t)=>{p=e,d=t}),m=i.createServer(async(e,t)=>{if("POST"===e.method&&e.url&&"/tempo/auth"===e.url)try{const n=await readJson(e);if(!n||"string"!=typeof n.code||"string"!=typeof n.state)return t.writeHead(400,{"Content-Type":"application/json"}),void t.end(JSON.stringify({error:"missing fields"}));if(n.state!==r||h)return t.writeHead(403,{"Content-Type":"application/json"}),void t.end(JSON.stringify({error:"invalid sign-in"}));h=!0;const o=await fetch(`${u}/auth/desktop-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:n.code,verifier:s}),signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Sign-in expired or invalid");const i=await o.json();if("string"!=typeof i.token||"string"!=typeof i.sessionId||"string"!=typeof i.userId)throw new Error("Invalid sign-in response");await writeAuth({token:i.token,sessionId:i.sessionId,userId:i.userId,email:"string"==typeof i.email?i.email:void 0,firstName:"string"==typeof i.firstName?i.firstName:void 0,lastName:"string"==typeof i.lastName?i.lastName:void 0,expiresAt:decodeJwtExp(i.token),lastOrgId:"string"==typeof i.orgId?i.orgId:null}),t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}),t.end(JSON.stringify({ok:!0})),setImmediate(()=>{m.close(),p()})}catch(e){h=!1,t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:String(e)}))}else{if("OPTIONS"===e.method)return t.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type"}),void t.end();t.writeHead(404),t.end()}});await new Promise((t,n)=>{m.once("error",n),m.listen(e.port??0,o,()=>t())});const g=m.address();if(!g||"string"==typeof g)throw m.close(),new Error("Failed to bind callback listener");const w=g.port,y=`${t}/sign-in?callbackPort=${w}&flow=mcp&loginState=${r}&loginChallenge=${l}`;if(Number.isFinite(n)){const e=setTimeout(()=>{m.close(),d(new Error(`Sign-in timeout after ${n}ms`))},n);"function"==typeof e.unref&&e.unref(),f.finally(()=>clearTimeout(e)).catch(()=>{})}return{signInUrl:y,callbackPort:w,done:f,cancel:()=>{m.close(),d(new Error("Sign-in cancelled"))}}}function readJson(e){return new Promise((t,n)=>{let o="";e.setEncoding("utf8"),e.on("data",t=>{o+=t,o.length>1e6&&(e.destroy(),n(new Error("payload too large")))}),e.on("end",()=>{if(!o)return t(null);try{t(JSON.parse(o))}catch(e){n(e)}}),e.on("error",n)})}import{exec as l}from"child_process";import{promisify as u}from"util";var p=u(l);function browserLaunchSuppressed(){return"1"===process.env.TEMPO_MCP_NO_BROWSER}async function openInBrowser(e){if(browserLaunchSuppressed())return!1;const t="darwin"===process.platform?`open "${e}"`:"win32"===process.platform?`start "" "${e}"`:`xdg-open "${e}"`;try{return await p(t,{windowsHide:!0}),!0}catch{return!1}}function createSignInPrompt(e={}){const t=e.openBrowser??openInBrowser;let n=null;const currentOrFresh=()=>{if(!n||n.spent){const t={handle:startBrowserAuthFlow({authUrl:e.authUrl,timeoutMs:1/0}),browserOpened:null,spent:!1};t.handle.then(e=>e.done).catch(()=>{}).finally(()=>{t.spent=!0}),n=t}return n};return{async ensure(e){for(;;){if(await readAuth())return"signed_in";const n=currentOrFresh(),o=await n.handle;n.browserOpened||(n.browserOpened=t(o.signInUrl));const r=await n.browserOpened,s=await Promise.race([o.done.then(()=>!0,()=>!1),sleep2(e).then(()=>!1)]);if(!s)return{signInUrl:o.signInUrl,browserOpened:r};n.spent=!0}},dispose(){n&&!n.spent&&n.handle.then(e=>e.cancel()).catch(()=>{})}}}function sleep2(e){return new Promise(t=>{const n=setTimeout(t,e);"function"==typeof n.unref&&n.unref()})}import{createHash as d}from"crypto";var h="TEMPO_AUTH_TOKEN";function envAccessToken(){const e=process.env[h]?.trim();return e||null}function accessTokenFingerprint(e){return d("sha256").update(e).digest("hex").slice(0,16)}function storedAuthMatchesAccessToken(e,t){return e.accessTokenFingerprint===accessTokenFingerprint(t)}var f=class extends Error{constructor(e,t){super(e),this.kind=t,this.name="TokenExchangeError"}};async function exchangeAccessToken(e){const t=e.maxRetries??2,n=e.retryDelayMs??2e3;let o="exchange failed";for(let r=0;r<=t;r++){let s;try{s=await fetch(`${e.convexSiteUrl}/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.accessToken})})}catch(e){if(o=e instanceof Error?e.message:String(e),r<t){await sleep3(n*Math.pow(1.5,r));continue}break}if(401===s.status)throw new f(`${h} was rejected (revoked or invalid). Mint a new token with \`tempo-mcp token create\` on a signed-in machine.`,"invalid_token");if(!s.ok){if(o=`token exchange returned ${s.status}`,r<t){await sleep3(n*Math.pow(1.5,r));continue}break}const i=await s.json();if(!i.token||!i.sessionId||!i.userId)throw new f("token exchange returned an incomplete payload","transient");const a={token:i.token,sessionId:i.sessionId,userId:i.userId,email:decodeJwtEmail(i.token),expiresAt:decodeJwtExp(i.token),accessTokenFingerprint:accessTokenFingerprint(e.accessToken)};return await writeAuth(a),a}throw new f(`Tempo token exchange failed: ${o}`,"transient")}function decodeJwtEmail(e){try{const[,t]=e.split("."),n=JSON.parse(Buffer.from(t,"base64").toString("utf8"));return"string"==typeof n.email?n.email:void 0}catch{return}}function sleep3(e){return new Promise(t=>setTimeout(t,e))}import{randomUUID as m}from"crypto";import{Server as g}from"@modelcontextprotocol/sdk/server/index.js";import{Client as w}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as y}from"@modelcontextprotocol/sdk/inMemory.js";import{CallToolRequestSchema as v,ListResourcesRequestSchema as A,ListToolsRequestSchema as S,ReadResourceRequestSchema as T}from"@modelcontextprotocol/sdk/types.js";var x=5e4;function exceedsElementLimit(e,t){let n=0;const o=[e];for(;o.length>0;){const e=o.pop();if(null===e||"object"!=typeof e)continue;const r=Array.isArray(e)?e:Object.values(e);if(n+=r.length,n>t)return!0;for(const e of r)null!==e&&"object"==typeof e&&o.push(e)}return!1}var k=6e5;async function createAggregateServer(e){const{name:t,version:n,instructions:o,backends:r,filterTool:s,injectParams:i,onScopedCall:a,gateCall:c}=e,l=[];for(const e of r){const[o,r]=y.createLinkedPair(),s=new w({name:`${t}-aggregator`,version:n});await e.server.connect(r),await s.connect(o),l.push({...e,client:s})}const u=new Map,p=new Map,d=new Map;for(const t of l){if(!t.client.getServerCapabilities()?.tools){d.set(t.toolset,[]);continue}const n=await t.client.listTools(),o=[];for(const r of n.tools){const n=e.toolIcons?.[r.name],a=e.toolAnnotations?.[r.name],c={...r,...n?{icons:n}:{},...a?{annotations:{...r.annotations,...a}}:{}};if(s&&!s(t.toolset,c.name))continue;const l=u.get(c.name);if(l)throw new Error(`MCP aggregate tool name collision: "${c.name}" registered by both "${l.toolset}" and "${t.toolset}"`);u.set(c.name,t);const d=i?.(t.toolset,c.name)??[];if(0===d.length){o.push(c);continue}p.set(c.name,d);const h=c.inputSchema??{type:"object"};o.push({...c,inputSchema:{...h,type:"object",properties:{...h.properties??{},...Object.fromEntries(d.map(e=>[e.name,{type:"string",description:e.description}]))},required:[...new Set([...h.required??[],...d.map(e=>e.name)])]}})}d.set(t.toolset,o)}const h=new g({name:t,version:n,...e.icons?{icons:e.icons}:{}},{capabilities:{tools:{},resources:{}},instructions:o});h.setRequestHandler(S,async()=>({tools:l.flatMap(e=>d.get(e.toolset)??[])}));let f=Promise.resolve();h.setRequestHandler(v,async(t,n)=>{const o=t.params.name;if(exceedsElementLimit(t.params.arguments,x))return{isError:!0,content:[{type:"text",text:JSON.stringify({error:{code:"tool_input_too_large",message:`Arguments for "${o}" contain more than ${x} array elements and object members. Split the call into smaller ones.`}})}]};const r=u.get(o);if(!r)return{isError:!0,content:[{type:"text",text:JSON.stringify({error:{code:"unknown_tool",message:`No registered tool named "${o}"`}})}]};const s=performance.now();let i;try{return i=await(async()=>{if(c){const e=await c(r.toolset,o);if(e)return e}const e={...t.params.arguments??{}},s=p.get(o)??[],i={};for(const t of s){const n=e[t.name];if(delete e[t.name],"string"!=typeof n||0===n.length)return{isError:!0,content:[{type:"text",text:JSON.stringify({error:{code:"missing_scope_param",message:`"${o}" requires "${t.name}". ${t.description}`}})}]};i[t.name]=n}const l=f.then(async()=>{n.signal.throwIfAborted(),s.length>0&&a?.(i);const t=m();r.onRequestStart?.(t);try{return await r.client.callTool({name:o,arguments:e},void 0,{timeout:k,signal:r.forwardCancellation?n.signal:void 0})}finally{r.onRequestEnd?.(t)}});return f=l.then(()=>{},()=>{}),await l})(),i}finally{try{e.onToolCallFinished?.({name:o,toolset:r.toolset,args:t.params.arguments??{},result:i,durationMs:Math.round(performance.now()-s)})}catch{}}});const listResourcesForBackend=async e=>{const t=e.client.getServerCapabilities();if(!t?.resources)return[];const n=await e.client.listResources();return n.resources};return h.setRequestHandler(A,async()=>{const e=await Promise.all(l.map(listResourcesForBackend));return{resources:e.flat()}}),h.setRequestHandler(T,async e=>{const t=e.params.uri;for(const e of l){const n=await listResourcesForBackend(e);if(n.some(e=>e.uri===t))return e.client.readResource({uri:t})}throw new Error(`Unknown resource: ${t}`)}),{server:h,connect:e=>h.connect(e),dispose:async()=>{for(const e of l)await e.client.close().catch(()=>{}),e.dispose?.();await h.close().catch(()=>{})}}}import I from"fs";import E from"fs/promises";import b from"path";function installProcessSafety(e={}){const t=e.binaryName??b.basename(process.argv[1]??"tempo-mcp"),logError=(e,n)=>{const o=`[${(new Date).toISOString()}] ${e}: ${n instanceof Error?n.stack||n.message:String(n)}\n`;try{I.mkdirSync(logsDir(),{recursive:!0,mode:448}),I.appendFileSync(logFilePath(t),o,{mode:384})}catch{try{process.stderr.write(o)}catch{}}},onUncaught=e=>logError("uncaughtException",e),onUnhandled=e=>logError("unhandledRejection",e);process.on("uncaughtException",onUncaught),process.on("unhandledRejection",onUnhandled);const stdoutError=e=>{"EPIPE"!==e.code&&logError("stdout-error",e)};process.stdout.on("error",stdoutError);const onSignal=t=>{Promise.resolve(e.onShutdown?.()).catch(e=>logError(`shutdown:${t}`,e)).finally(()=>{setTimeout(()=>process.exit(0),50)})};return process.once("SIGTERM",()=>onSignal("SIGTERM")),process.once("SIGINT",()=>onSignal("SIGINT")),()=>{process.off("uncaughtException",onUncaught),process.off("unhandledRejection",onUnhandled),process.stdout.off("error",stdoutError)}}import{randomUUID as O}from"crypto";import P from"fs";import N from"path";var C="https://greedy-jackal-526.convex.cloud";function resolveConvexUrl(){return process.env.TEMPO_CONVEX_URL??C}function resolveConvexSiteUrl(e){const t=process.env.TEMPO_CONVEX_SITE_URL;return t||e.replace(/\.convex\.cloud$/,".convex.site")}var R=12e4;function resolveSignInWaitMs(){const e=Number(process.env.TEMPO_MCP_SIGN_IN_WAIT_MS);return Number.isFinite(e)&&e>=0?e:R}var U=["design-context","issues","docs","comments","agents","scripts","slack","linear","canvas"];function parseServeArgs(e){let t=[...U],n="1"===process.env.TEMPO_MCP_READONLY;for(let o=0;o<e.length;o++){const r=e[o];if("--readonly"===r)n=!0;else{if("--toolsets"!==r)return{error:`Unknown flag: ${r}`};{const n=e[++o];if(!n)return{error:"--toolsets requires a comma-separated list"};const r=n.split(",").map(e=>e.trim()).filter(Boolean),s=r.filter(e=>!U.includes(e));if(s.length)return{error:`Unknown toolset(s): ${s.join(", ")}. Valid: ${U.join(", ")}`};t=r}}}return{toolsets:t,readonly:n}}function discoverWorkspace(e=process.cwd()){let t=N.resolve(e);for(;;){const e=N.join(t,"tempo","tempo.config.json");if(P.existsSync(e)){let n="./designs";try{const t=JSON.parse(P.readFileSync(e,"utf8"));t.paths?.canvases&&(n=t.paths.canvases)}catch{}return{workspaceRoot:t,canvasesDir:N.resolve(t,"tempo",n)}}const n=N.dirname(t);if(n===t)return null;t=n}}async function signInInteractively(){const e=await startBrowserAuthFlow({authUrl:process.env.TEMPO_AUTH_URL}),t=await openInBrowser(e.signInUrl);t?(console.log("Opened your browser to sign in to Tempo."),console.log("If a browser didn't open, visit this URL:")):console.log("Sign in to Tempo by visiting:"),console.log(` ${e.signInUrl}`),console.log(""),console.log("Waiting for sign-in to complete...");try{await e.done;const t=await readAuth();return console.log(""),console.log(`Signed in as ${t?.email??t?.userId??"unknown user"}.`),console.log("Credentials stored in ~/.tempo/auth.json (0600)."),0}catch(e){return console.error("Sign-in failed:",e instanceof Error?e.message:e),1}}async function runLogin(){const e=await readAuth();return e&&e.expiresAt-Date.now()>6e4?(console.log(`Already signed in as ${e.email??e.userId}. Run \`tempo-mcp logout\` first to re-authenticate.`),0):signInInteractively()}import{ConvexHttpClient as M}from"convex/browser";var j=class extends Error{constructor(e){super(e.message),this.name="McpToolError",this.error=e}};function mapConvexError(e){const t=e instanceof Error?e.message:String(e);return t.includes("Not authenticated")||t.includes("Unauthenticated")?{code:"auth_required",message:"Authentication required. Please sign in."}:t.includes("not a member")||t.includes("Unauthorized")||t.includes("forbidden")?{code:"forbidden",message:"You are not a member of this organization."}:t.includes("not found")||t.includes("Could not find")?{code:"not_found",message:t}:t.includes("rate limit")||t.includes("Too many requests")?{code:"rate_limited",message:"Rate limited. Please retry after a moment."}:t.includes("Invalid argument")||t.includes("Validator error")?{code:"invalid_args",message:t}:{code:"internal",message:t}}var $=3,_=200,J=class{constructor(e){this.cachedToken=null,this.signal=e.signal;const t=e.fetch??((e,t)=>globalThis.fetch(e,t));this.client=new M(e.url,e.signal||e.fetch?{fetch:e.signal?(n,o)=>t(n,{...o,signal:e.signal}):e.fetch}:void 0),this.authProvider=e.authProvider,this.beforeCall=e.beforeCall}async query(e,t){return this.callWithAuth(()=>this.client.query(e,t))}async mutation(e,t){return this.callWithAuth(()=>this.client.mutation(e,t))}async action(e,t){return this.callWithAuth(()=>this.client.action(e,t))}async ensureAuth(e=!1){const t=Date.now();if(!e&&this.cachedToken&&this.cachedToken.expiresAt-t>3e4)return void this.client.setAuth(this.cachedToken.jwt);const n=await this.withSignal(()=>this.authProvider.getToken(e));this.cachedToken=n,this.client.setAuth(n.jwt)}async callWithAuth(e){this.beforeCall?.(),this.signal?.throwIfAborted(),await this.ensureAuth();for(let t=0;t<$;t++){this.beforeCall?.();try{return await this.withSignal(e)}catch(e){this.signal?.throwIfAborted();const n=mapConvexError(e);if("auth_required"===n.code&&0===t){this.cachedToken=null,await this.ensureAuth(!0);continue}if("internal"===n.code&&t<$-1){await this.withSignal(()=>sleep4(_*2**t));continue}throw new j(n)}}throw new j({code:"internal",message:"Max retries exceeded"})}withSignal(e){const t=this.signal;return t?(t.throwIfAborted(),new Promise((n,o)=>{const onAbort=()=>o(t.reason);t.addEventListener("abort",onAbort,{once:!0}),Promise.resolve().then(()=>(t.throwIfAborted(),e())).then(n,o).finally(()=>t.removeEventListener("abort",onAbort))})):e()}};function sleep4(e){return new Promise(t=>setTimeout(t,e))}var F=class extends Error{constructor(){super("Not signed in to Tempo. Run `npx -y @tempo-ai/mcp login` in a terminal, or set TEMPO_AUTH_TOKEN for headless environments."),this.name="NotSignedInError"}};async function ensureCliAuth(){const e=envAccessToken(),t=resolveConvexSiteUrl(resolveConvexUrl());if(!e){const e=await readAuth();if(e&&e.expiresAt-Date.now()<=6e4){const e=createRefreshLoop({convexSiteUrl:t,onReauthRequired:()=>{}});await e.refreshNow()}if(await readAuth())return;if(!process.stdout.isTTY)throw new F;if(0!==await signInInteractively())throw new F;return}const n=await readAuth();n&&storedAuthMatchesAccessToken(n,e)&&n.expiresAt-Date.now()>6e4||await exchangeAccessToken({convexSiteUrl:t,accessToken:e})}function envTokenReauth(e){return async()=>{const t=envAccessToken();return!!t&&(await exchangeAccessToken({convexSiteUrl:e,accessToken:t}),!0)}}function createCliConvex(){const e=resolveConvexUrl(),t=resolveConvexSiteUrl(e),n=createRefreshLoop({convexSiteUrl:t,attemptReauth:envTokenReauth(t),onReauthRequired:()=>{console.error("[tempo-mcp] Tempo session expired. Run `npx -y @tempo-ai/mcp login` to sign in again.")}});n.start();const o=createAuthProvider(n),r=new J({url:e,authProvider:o});return{convex:r,authProvider:o,dispose:()=>n.stop()}}export{j as McpToolError,J as AuthedConvexClient,readAuth,readAuthSync,clearAuth,createRefreshLoop,createAuthProvider,envAccessToken,storedAuthMatchesAccessToken,f as TokenExchangeError,exchangeAccessToken,createSignInPrompt,createAggregateServer,installProcessSafety,resolveConvexUrl,resolveConvexSiteUrl,resolveSignInWaitMs,parseServeArgs,discoverWorkspace,runLogin,F as NotSignedInError,ensureCliAuth,envTokenReauth,createCliConvex};
package/dist/index.d.ts CHANGED
@@ -1,19 +1,3 @@
1
- /**
2
- * Tempo MCP CLI entrypoint.
3
- *
4
- * The DEFAULT command (no subcommand) serves Tempo's full MCP tool surface
5
- * over stdio — that's what an MCP host config invokes:
6
- * { "tempo": { "command": "npx", "args": ["-y", "@tempo-ai/mcp"] } }
7
- * It needs no prior sign-in: the first tool call that needs Tempo prompts
8
- * for one (TEM-2313).
9
- *
10
- * Subcommand routing:
11
- * (none) | serve [--toolsets a,b] [--readonly]
12
- * → run the aggregate MCP server over stdio (long-running)
13
- * login | logout | whoami | token → auth utilities (short-lived)
14
- * tools | call → the same tool surface as a CLI
15
- * --help | -h → print usage
16
- */
17
1
  declare function run(argv: string[]): Promise<number>;
18
2
 
19
3
  export { run };
package/dist/index.js CHANGED
@@ -1,10 +1 @@
1
- import { createRequire as __tempoCreateRequire } from 'node:module'; const require = __tempoCreateRequire(import.meta.url);
2
- import {
3
- run
4
- } from "./chunk-NZ7THB2V.js";
5
- import "./chunk-4R6XIZCX.js";
6
- import "./chunk-JKT5N6IQ.js";
7
- export {
8
- run
9
- };
10
- //# sourceMappingURL=index.js.map
1
+ import{createRequire as r}from"node:module";r(import.meta.url);import{run as o}from"./chunk-2AGTI4OY.js";import"./chunk-OB7GTENV.js";import"./chunk-NCFWHGWN.js";export{o as run};