@atoms-tech/atoms-mcp 0.4.0 → 0.4.2

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/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var e=require("fs/promises"),t=require("os"),n=require("path"),r=require("@supabase/supabase-js"),i=require("@modelcontextprotocol/ext-apps/server"),a=require("url"),s=require("@modelcontextprotocol/sdk/server/mcp.js"),o=require("zod"),d=require("crypto"),c=require("http"),l=require("@modelcontextprotocol/sdk/server/stdio.js"),m="undefined"!=typeof document?document.currentScript:null;function p(e){return e&&e.__esModule?e:{default:e}}var u,h,_,f,g,y=p(e),w=p(n),b=Object.defineProperty,v=Object.getOwnPropertyNames,j=(e,t)=>function(){return e&&(t=(0,e[v(e)[0]])(e=0)),t},x=(e,t)=>{for(var n in t)b(e,n,{get:t[n],enumerable:!0})},S=j({"src/middleware/audit.ts"(){}}),I=j({"src/middleware/rate-limiter.ts"(){u=60,h=6e4,_=new Map}}),k={};async function E(){try{const t=await e.readFile(g,"utf-8"),n=JSON.parse(t);return n.access_token&&n.refresh_token?n:null}catch{return null}}async function T(t){await e.mkdir(f,{recursive:!0,mode:448}),await e.writeFile(g,JSON.stringify(t,null,2),{mode:384})}async function H(){const e=await E();return!!e&&e.expires_at>Date.now()+6e4}function C(e){return e.expires_at>Date.now()+6e4}async function q(){try{await e.unlink(g)}catch{}}function O(){return g}x(k,{clearCredentials:()=>q,getCredentialsPath:()=>O,hasValidCredentials:()=>H,isTokenValid:()=>C,readCredentials:()=>E,writeCredentials:()=>T});var U,z,R,M=j({"src/auth/token-store.ts"(){f=n.join(t.homedir(),".atoms"),g=n.join(f,"credentials.json")}}),D=j({"src/config.ts"(){U="https://gmebjyhomsbvhrxffzre.supabase.co",z="sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",R=process.env.ATOMS_APP_URL??"https://x.atoms.tech"}}),P={};async function A(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=N(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await E();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' to connect your ATOMS account.");if(t.expires_at>Date.now()+6e4){const e=N(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}process.stderr.write("[atoms-mcp] Refreshing access token...\n");const n=r.createClient(U,z),{data:i,error:a}=await n.auth.refreshSession({refresh_token:t.refresh_token});if(a||!i.session)throw new Error(`Token refresh failed: ${a?.message??"No session returned"}. Re-run 'npx @atoms-tech/atoms-mcp login'.`);const s=i.session;return await T({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:Date.now()+1e3*(s.expires_in??3600),user_email:s.user?.email}),{access_token:s.access_token,refresh_token:s.refresh_token,user_id:s.user?.id??"",email:s.user?.email??""}}function N(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),r=JSON.parse(Buffer.from(n,"base64").toString("utf-8"));if(!r.sub)throw new Error("JWT missing 'sub' claim");return r}x(P,{getValidToken:()=>A});var $,F,W,L,V=j({"src/auth/refresh.ts"(){M(),D()}});async function J(){if($&&L>Date.now()+6e4)return $;$&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:n}=await A(),i=e.split(".");if(3===i.length)try{const e=JSON.parse(Buffer.from(i[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());L=1e3*(e.exp??0)}catch{L=Date.now()+36e5}const a=r.createClient(U,z,{global:{headers:{Authorization:`Bearer ${e}`}}});return F=t,W=n,$=a}function B(){if(!F)throw new Error("Not authenticated. Call getClient() first.");return F}async function G(e,t){const n=B(),{data:r,error:i}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(i||!r)throw new Error(`Project '${t}' not found`);const{data:a,error:s}=await e.from("org_members").select("role").eq("user_id",n).eq("org_id",r.org_id).maybeSingle();if(s||!a){const{data:t}=await e.rpc("is_platform_admin");if(!0===t)return"admin";throw new Error("Not a member of this project's organization")}if("viewer"===a.role)throw new Error("VIEWER_ROLE");return a.role}var Q,Y=j({"src/db/client.ts"(){V(),D(),$=null,F=null,W=null,L=0}});function K(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function X(e,t,n){return{total_count:e,limit:t,offset:n,has_more:n+t<e}}function Z(e,t){return{status:"error",message:e,next_steps:t}}function ee(e,t){return Z(`${e} '${t}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function te(e){return Z(`${e} role cannot modify project data`,["Contact your org admin to upgrade your role to editor","Use read-only tools (atoms_list_items, atoms_get_item, atoms_search) instead"])}function ne(e){return Z(`Validation error: ${e}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function re(){return Z("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' first.",["Run: npx @atoms-tech/atoms-mcp login","Or set ATOMS_ACCESS_TOKEN environment variable"])}function ie(e){return Z(`Database error: ${e}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function ae(e){const t=JSON.stringify(e,null,2);if(t.length>Q&&"success"===e.status&&Array.isArray(e.data)){const t=Math.max(1,Math.floor(e.data.length/2)),n={...e,data:e.data.slice(0,t),meta:{...e.meta,truncated:!0,truncation_message:`Response truncated from ${e.data.length} to ${t} items. Use 'offset' parameter or add filters to see more results.`}};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}}return{content:[{type:"text",text:t}],structuredContent:e}}function se(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}var oe,de=j({"src/tools/_base.ts"(){Q=25e3}});function ce(e,t){const n=`ui://${t.toolName}/${t.htmlFile}`,r=function(e,t){const n=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href),r=w.default.dirname(n);return w.default.resolve(r,"apps","src","apps",e,t)}(t.appName,t.htmlFile),s=[...oe.resourceDomains,...t.extraResourceDomains??[]];i.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:n}}},t.handler),i.registerAppResource(e,`${t.title} UI`,n,{mimeType:i.RESOURCE_MIME_TYPE},async()=>{const e=await y.default.readFile(r,"utf-8");return{contents:[{uri:n,mimeType:i.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:s}}}}]}})}var le=j({"src/apps/register.ts"(){oe={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});async function me(e,t,n){let r=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0}).range(n.offset,n.offset+n.limit-1);n.type&&(r=r.eq("type",n.type));const{data:i,error:a,count:s}=await r;if(a)throw new Error(a.message);let o=i??[];return n.domain&&(o=o.filter(e=>(e.data?.tags?.domains??[]).includes(n.domain))),n.level&&(o=o.filter(e=>e.data?.tags?.level===n.level)),{items:o,totalCount:n.domain||n.level?o.length:s??0}}async function pe(e,t,n){const{data:r,error:i}=await e.from("items").select("*").eq("id",n).eq("project_id",t).is("deleted_at",null).maybeSingle();if(i)throw new Error(i.message);return r}async function ue(e,t,n,r){const i=n.trim();if(!i)return{items:[],totalCount:0};let a=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.%${i}%,data->>body.ilike.%${i}%,data->>summary.ilike.%${i}%`).limit(r.limit);r.type&&(a=a.eq("type",r.type));const{data:s,error:o,count:d}=await a;if(o)throw new Error(o.message);return{items:s??[],totalCount:d??0}}async function he(e,t,n){const r="requirement"===n?"REQ":"test-case"===n?"TC":"note"===n?"NOTE":"TABLE",{data:i,error:a}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(a)throw new Error(`ID generation failed: ${a.message}`);return i}var _e=j({"src/db/queries.ts"(){}}),fe={};async function ge(){try{const e=await J(),t=await async function(e){const{data:t,error:n}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(n)throw new Error(n.message);return(t??[]).map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.organizations?.name??"Unknown",created_at:e.created_at}))}(e);return ae(K(t.map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.org_name,created_at:e.created_at}))))}catch(e){return se(ie(e instanceof Error?e.message:"Unknown error"))}}x(fe,{listProjectsHandler:()=>ge});var ye=j({"src/tools/list-projects.ts"(){Y(),_e(),de()}}),we={};async function be(e){try{const t=await J(),{items:n,totalCount:r}=await me(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});return ae(K(n.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),X(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(we,{listItemsHandler:()=>be});var ve=j({"src/tools/list-items.ts"(){Y(),_e(),de()}}),je={};async function xe(e){try{const t=await J(),n=await pe(t,e.project_id,e.item_id);if(!n)return se(ee("Item",e.item_id));const r=await async function(e,t,n){const{data:r,error:i}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${n},to_id.eq.${n}`);if(i)throw new Error(i.message);return r??[]}(t,e.project_id,e.item_id),i={parents:[],children:[],related:[],verified_by:[],verifies:[]};for(const t of r)if(t.from_id===e.item_id)t.type in i&&i[t.type].push(t.to_id);else{const e={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",related:"related"}[t.type]??t.type;e in i&&i[e].push(t.from_id)}let a=[];if("test-case"===n.type){const{data:n,error:r}=await t.from("test_results").select("result, run_by, run_at, note").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);!r&&n&&(a=n)}return ae(K({id:n.id,type:n.type,title:n.title,summary:n.data?.summary,body:n.data?.body,tags:n.data?.tags??{domains:[]},ownership:n.data?.ownership??{primary:null,additional:[]},relationships:i,links:n.data?.links??[],status:n.data?.status,..."test-case"===n.type?{latest_result:a[0]?.result??"not-run",test_results:a}:{},metadata:{created_at:n.created_at,created_by:n.created_by,updated_at:n.updated_at,updated_by:n.updated_by,source_id:n.data?.metadata?.source_id}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(je,{getItemHandler:()=>xe});var Se=j({"src/tools/get-item.ts"(){Y(),_e(),de()}}),Ie={};async function ke(e){try{const t=await J(),{items:n,totalCount:r}=await ue(t,e.project_id,e.query,{type:e.type,limit:e.limit});return ae(K(n.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),X(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(Ie,{searchHandler:()=>ke});var Ee=j({"src/tools/search.ts"(){Y(),_e(),de()}}),Te={};async function He(e){try{const t=await J(),{covered:n,uncovered:r,total:i}=await async function(e,t,n){const{data:r,error:i}=await e.from("items").select("*").eq("project_id",t).eq("type","requirement").is("deleted_at",null);if(i)throw new Error(i.message);const a=(r??[]).filter(e=>!(n.domain&&!(e.data?.tags?.domains??[]).includes(n.domain)||n.level&&e.data?.tags?.level!==n.level)),{data:s,error:o}=await e.from("item_relationships").select("from_id").eq("project_id",t).eq("type","verified_by");if(o)throw new Error(o.message);const d=new Set((s??[]).map(e=>e.from_id));return{covered:a.filter(e=>d.has(e.id)),uncovered:a.filter(e=>!d.has(e.id)),total:a.length}}(t,e.project_id,{domain:e.domain,level:e.level}),a=r.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level}));return ae(K({covered:n.length,uncovered:r.length,total:i,coverage_percent:i>0?Math.round(n.length/i*1e3)/10:100,uncovered_items:a}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(Te,{getCoverageHandler:()=>He});var Ce=j({"src/tools/get-coverage.ts"(){Y(),_e(),de()}}),qe={};async function Oe(e){try{const t=await J(),n=await async function(e,t,n,r){const{data:i,error:a}=await e.from("change_history").select("*").eq("item_id",n).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r);if(a)throw new Error(a.message);return i??[]}(t,e.project_id,e.item_id,e.limit),r=n.map(e=>{const t=[],n=e.old_data,r=e.new_data;if(n&&r){const e=new Set([...Object.keys(n),...Object.keys(r)]);for(const i of e)JSON.stringify(n[i])!==JSON.stringify(r[i])&&t.push(i)}else r?t.push("(created)"):n&&t.push("(deleted)");return{id:e.id,event_type:e.event_type,changed_by:e.changed_by??null,changed_at:e.changed_at,actor:e.actor??"user",session_id:e.session_id??null,fields_changed:t}});return ae(K(r,X(r.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(qe,{getHistoryHandler:()=>Oe});var Ue=j({"src/tools/get-history.ts"(){Y(),_e(),de()}}),ze={};async function Re(e){try{const t=await J(),{data:n,error:r}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(r)throw new Error(r.message);if(!n||0===n.length)return ae(K({mermaid:"graph TD\n empty[No items in project]"}));const{data:i,error:a}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(a)throw new Error(a.message);const s=new Map;for(const e of n)s.set(e.id,e);const o=["graph TD"],d=new Set,c=new Set,l=(new Set((i??[]).filter(e=>"child"===e.type).map(e=>e.to_id)),new Set((i??[]).filter(e=>"parent"===e.type).map(e=>e.from_id)));let m;m=e.root_item_id?[e.root_item_id]:n.filter(e=>!l.has(e.id)).filter(t=>!(!e.include_tests&&"test-case"===t.type)).map(e=>e.id);const p=m.map(e=>({id:e,depth:0}));for(;p.length>0;){const{id:t,depth:n}=p.shift();if(d.has(t)||n>e.depth)continue;d.add(t);const r=s.get(t);if(!r)continue;if(!e.include_tests&&"test-case"===r.type)continue;const a=Me(r.title),l="requirement"===r.type?`["${a}"]`:"test-case"===r.type?`(["${a}"])`:`("${a}")`;o.push(` ${t}${l}`);for(const r of i??[]){if(r.from_id!==t)continue;const i=s.get(r.to_id);if(!i)continue;if(!e.include_tests&&"test-case"===i.type)continue;const a=`${r.from_id}-${r.type}-${r.to_id}`;c.has(a)||(c.add(a),"child"===r.type?o.push(` ${t} --\x3e ${r.to_id}`):"verified_by"===r.type?o.push(` ${t} -.->|verified_by| ${r.to_id}`):"related"===r.type&&o.push(` ${t} -.- ${r.to_id}`),!d.has(r.to_id)&&n+1<=e.depth&&p.push({id:r.to_id,depth:n+1}))}}return ae(K({mermaid:o.join("\n"),node_count:d.size,edge_count:c.size}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}function Me(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,50)}x(ze,{exportMermaidHandler:()=>Re});var De=j({"src/tools/export-mermaid.ts"(){Y(),de()}}),Pe={};async function Ae(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return se(te("Viewer"));throw e}const r=await he(t,e.project_id,e.type),i={id:r,type:e.type,title:e.title,summary:e.summary,body:e.body,tags:{domains:e.domains??[],level:e.level},ownership:{primary:null,additional:[]},relationships:{parents:e.parent_ids??[],children:[],related:[]},links:[],metadata:{created_at:(new Date).toISOString(),created_by:n,updated_at:(new Date).toISOString(),updated_by:n}},{error:a}=await t.from("items").insert({id:r,project_id:e.project_id,type:e.type,title:e.title,data:i,created_by:n,updated_by:n}).select().single();if(a)throw new Error(a.message);if(e.parent_ids&&e.parent_ids.length>0){const n=e.parent_ids.map(t=>({from_id:r,to_id:t,type:"parent",project_id:e.project_id}));await t.from("item_relationships").insert(n).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: relationship sync failed: ${e.message}\n`)})}return await t.from("change_history").insert({item_id:r,project_id:e.project_id,changed_by:n,event_type:"created",old_data:null,new_data:i,actor:"mcp_claude",session_id:Ot()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),ae(K({id:r,type:e.type,title:e.title,project_id:e.project_id}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(Pe,{createItemHandler:()=>Ae});var Ne=j({"src/tools/create-item.ts"(){Y(),_e(),Rt(),de()}}),$e={};async function Fe(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return se(te("Viewer"));throw e}const r=await pe(t,e.project_id,e.item_id);if(!r)return se(ee("Item",e.item_id));const i={...r.data},a={...r.data};void 0!==e.title&&(a.title=e.title),void 0!==e.body&&(a.body=e.body),void 0!==e.summary&&(a.summary=e.summary),void 0!==e.domains&&(a.tags={...a.tags,domains:e.domains}),void 0!==e.level&&(a.tags={...a.tags,level:e.level}),void 0!==e.status&&(a.status=e.status),a.metadata={...a.metadata,updated_at:(new Date).toISOString(),updated_by:n};const{error:s}=await t.from("items").update({title:e.title??r.title,data:a,updated_by:n}).eq("id",e.item_id).eq("project_id",e.project_id);if(s)throw new Error(s.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:i,new_data:a,actor:"mcp_claude",session_id:Ot()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),ae(K({id:e.item_id,title:a.title,type:r.type,updated_fields:Object.keys(e).filter(t=>"project_id"!==t&&"item_id"!==t&&void 0!==e[t])}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x($e,{updateItemHandler:()=>Fe});var We=j({"src/tools/update-item.ts"(){Y(),_e(),Rt(),de()}}),Le={};async function Ve(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return se(te("Viewer"));throw e}const r=await pe(t,e.project_id,e.item_id);if(!r)return se(ee("Item",e.item_id));const{error:i}=await t.from("items").update({deleted_at:(new Date).toISOString()}).eq("id",e.item_id).eq("project_id",e.project_id);if(i)throw new Error(i.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:n,event_type:"deleted",old_data:r.data,new_data:null,actor:"mcp_claude",session_id:Ot()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),ae(K({id:e.item_id,title:r.title,type:r.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(Le,{deleteItemHandler:()=>Ve});var Je=j({"src/tools/delete-item.ts"(){Y(),_e(),Rt(),de()}}),Be={};async function Ge(e){try{const t=await J(),n=B();if(e.from_id===e.to_id)return se(ne("Cannot create a relationship between an item and itself"));try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return se(te("Viewer"));throw e}const r=await pe(t,e.project_id,e.from_id);if(!r)return se(ee("Item",e.from_id));if(!await pe(t,e.project_id,e.to_id))return se(ee("Item",e.to_id));if("add"===e.action){const{data:i}=await t.from("item_relationships").select("from_id").eq("from_id",e.from_id).eq("to_id",e.to_id).eq("type",e.type).eq("project_id",e.project_id).maybeSingle();if(!i){const{error:n}=await t.from("item_relationships").insert({from_id:e.from_id,to_id:e.to_id,type:e.type,project_id:e.project_id});if(n)throw new Error(n.message)}const a={...r.data},s="verified_by"===e.type||"verifies"===e.type?e.type:e.type+"s"=="parents"||"parent"===e.type?"parents":"child"===e.type?"children":"related";if(a.relationships){const t=a.relationships[s]??[];t.includes(e.to_id)||(a.relationships[s]=[...t,e.to_id])}await t.from("items").update({data:a,updated_by:n}).eq("id",e.from_id).eq("project_id",e.project_id)}else{const{error:i}=await t.from("item_relationships").delete().eq("from_id",e.from_id).eq("to_id",e.to_id).eq("type",e.type).eq("project_id",e.project_id);if(i)throw new Error(i.message);const a={...r.data},s="parent"===e.type?"parents":"child"===e.type?"children":e.type;if(a.relationships){const t=a.relationships[s]??[];a.relationships[s]=t.filter(t=>t!==e.to_id)}await t.from("items").update({data:a,updated_by:n}).eq("id",e.from_id).eq("project_id",e.project_id)}return await t.from("change_history").insert({item_id:e.from_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:null,new_data:{relationship_change:{action:e.action,type:e.type,from:e.from_id,to:e.to_id}},actor:"mcp_claude",session_id:Ot()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),ae(K({action:e.action,type:e.type,from_id:e.from_id,to_id:e.to_id,message:`Relationship ${"add"===e.action?"added":"removed"}: ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(Be,{linkItemsHandler:()=>Ge});var Qe=j({"src/tools/link-items.ts"(){Y(),_e(),Rt(),de()}}),Ye={};async function Ke(e){try{if(!e.items||0===e.items.length)return se(ne("items array must contain at least 1 item"));if(e.items.length>100)return se(ne(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return se(te("Viewer"));throw e}const r=(new Date).toISOString(),i=Ot(),a=[],s=[],o=[];for(let n=0;n<e.items.length;n++){const r=e.items[n];try{const i=await he(t,e.project_id,r.type);o.push({itemId:i,input:r,index:n})}catch(e){s.push({index:n,title:r.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===o.length)return ae(K({created:0,items:[],errors:s}));const d=[],c=new Map;for(const{itemId:t,input:i}of o){const a={id:t,type:i.type,title:i.title,summary:i.summary,body:i.body,tags:{domains:i.domains??[],level:i.level},ownership:{primary:null,additional:[]},relationships:{parents:i.parent_id?[i.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:r,created_by:n,updated_at:r,updated_by:n}};c.set(t,a),d.push({id:t,project_id:e.project_id,type:i.type,title:i.title,data:a,created_by:n,updated_by:n})}const{error:l}=await t.from("items").insert(d);if(l)for(const{itemId:e,input:n,index:r}of o){const i=d.find(t=>t.id===e);if(!i)continue;const{error:o}=await t.from("items").insert(i);o?s.push({index:r,title:n.title,error:o.message}):a.push({id:e,title:n.title,type:n.type})}else for(const{itemId:e,input:t}of o)a.push({id:e,title:t.title,type:t.type});const m=o.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>a.some(t=>t.id===e)).map(({itemId:t,input:n})=>({from_id:t,to_id:n.parent_id,type:"parent",project_id:e.project_id}));m.length>0&&await t.from("item_relationships").insert(m).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk relationship sync failed: ${e.message}\n`)});const p=a.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:n,event_type:"created",old_data:null,new_data:c.get(t.id)??null,actor:"mcp_claude",session_id:i}));return p.length>0&&await t.from("change_history").insert(p).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)}),ae(K({created:a.length,items:a,errors:s.length>0?s:[],project_id:e.project_id}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(Ye,{bulkImportHandler:()=>Ke});var Xe=j({"src/tools/bulk-import.ts"(){Y(),_e(),Rt(),de()}}),Ze={};async function et(e){try{const t=await J(),n=B(),r=W??"";try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return se(te("Viewer"));throw e}const i=await pe(t,e.project_id,e.item_id);if(!i)return se(ee("Item",e.item_id));if("test-case"!==i.type)return se(ne(`Item '${e.item_id}' is a ${i.type}, not a test-case`));const a=(new Date).toISOString(),{error:s}=await t.from("test_results").insert({item_id:e.item_id,project_id:e.project_id,result:e.result,run_by:r||n,run_at:a,note:e.note??null});if(s)throw new Error(s.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:n,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:a,note:e.note},actor:"mcp_claude",session_id:Ot()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),ae(K({item_id:e.item_id,result:e.result,run_at:a,run_by:r||n,note:e.note??null,message:`Test result '${e.result}' recorded for ${e.item_id}`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(Ze,{recordTestResultHandler:()=>et});var tt,nt,rt,it,at=j({"src/tools/record-test-result.ts"(){Y(),_e(),Rt(),de()}}),st={};async function ot(e){try{const t=Math.min(Math.max(e.depth??5,1),10),n=await J();if(!await pe(n,e.project_id,e.item_id))return se(ee("Item",e.item_id));const{data:r,error:i}=await n.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(i)throw new Error(i.message);const{data:a,error:s}=await n.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(s)throw new Error(s.message);const o=new Map;for(const e of a??[])o.set(e.id,{title:e.title,type:e.type});const d=new Map,c=(e,t,n)=>{d.has(e)||d.set(e,[]),d.get(e).push({neighbor:t,relType:n})},l=e.relationship_types?new Set(e.relationship_types):null;for(const t of r??[]){const n=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(nt.includes(n)&&(l&&!l.has(n)||c(t.from_id,t.to_id,n)),rt.includes(n))){const e=it[n]??n;l&&!l.has(e)||c(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(rt.includes(n)&&(l&&!l.has(n)||c(t.from_id,t.to_id,n)),nt.includes(n))){const e=it[n]??n;l&&!l.has(e)||c(t.to_id,t.from_id,e)}"related"===n&&(l&&!l.has("related")||(c(t.from_id,t.to_id,"related"),c(t.to_id,t.from_id,"related")))}const m=new Set;m.add(e.item_id);const p=[],u=[],h=d.get(e.item_id)??[];for(const e of h)u.push({id:e.neighbor,depth:1,relType:e.relType});for(;u.length>0&&p.length<tt;){const{id:e,depth:n,relType:r}=u.shift();if(m.has(e)||n>t)continue;m.add(e);const i=o.get(e);if(i&&(p.push({id:e,title:i.title,type:i.type,relationship:r,depth:n}),n<t)){const t=d.get(e)??[];for(const e of t)m.has(e.neighbor)||u.push({id:e.neighbor,depth:n+1,relType:e.relType})}}return ae(K({root:e.item_id,direction:e.direction,depth_limit:t,items:p,total_count:p.length,...p.length>=tt?{truncated:!0,truncation_message:`Results capped at ${tt} items. Use a smaller depth or filter by relationship_types.`}:{}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(st,{traceHandler:()=>ot});var dt=j({"src/tools/trace.ts"(){Y(),_e(),de(),tt=200,nt=["parent","verifies"],rt=["child","verified_by"],it={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related"}}}),ct={};async function lt(e){try{const t=await J(),{data:n,error:r}=await t.from("project_variables").select("*").eq("project_id",e.project_id).order("name");if(r)throw new Error(r.message);return ae(K({variables:n||[],total:(n||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}async function mt(e){try{const t=await J(),{data:n,error:r}=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(r)throw new Error(r.message);if(!n)return se(ee("Variable",e.variable_name));const{data:i}=await t.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null),a=`{${e.variable_name}}`,s=(i||[]).filter(e=>(e.data?.body||"").includes(a));return ae(K({variable:n,referenced_by:s.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:s.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}async function pt(e){try{const t=await J(),n={value:e.value,updated_at:(new Date).toISOString()};void 0!==e.unit&&(n.unit=e.unit||null);const{data:r,error:i}=await t.from("project_variables").update(n).eq("project_id",e.project_id).eq("name",e.variable_name).select().single();if(i)throw new Error(i.message);return r?ae(K({variable:r,message:`Variable "${e.variable_name}" updated to ${e.value}${e.unit?` ${e.unit}`:""}`})):se(ee("Variable",e.variable_name))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(ct,{getVariableHandler:()=>mt,listVariablesHandler:()=>lt,updateVariableHandler:()=>pt});var ut=j({"src/tools/variables.ts"(){Y(),de()}}),ht={};async function _t(e){try{const t=await J(),{data:n,error:r}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle();if(r)throw new Error(r.message);if(!n)return se(ee("Project",e.project_id));const{data:i,error:a}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);const s=i??[],o={requirements:0,test_cases:0,notes:0},d=[],c=[];for(const e of s)if("requirement"===e.type){o.requirements++;const t=e.data?.tags?.domains??[];c.push({id:e.id,domains:t})}else"test-case"===e.type?(o.test_cases++,d.push(e.id)):"note"===e.type&&o.notes++;const l={passed:0,failed:0,blocked:0,not_run:0};if(d.length>0){const{data:n,error:r}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(r)throw new Error(r.message);const i=new Map;for(const e of n??[])i.has(e.item_id)||i.set(e.item_id,e.result);for(const e of d){const t=i.get(e);t&&"not-run"!==t?"passed"===t?l.passed++:"failed"===t?l.failed++:"blocked"===t?l.blocked++:l.not_run++:l.not_run++}}const{data:m,error:p}=await t.from("item_relationships").select("from_id").eq("project_id",e.project_id).eq("type","verified_by");if(p)throw new Error(p.message);const u=new Set((m??[]).map(e=>e.from_id)),h=c.filter(e=>u.has(e.id)).length,_=c.length,f={covered:h,uncovered:_-h,total:_,percent:_>0?Math.round(h/_*1e3)/10:100},g=new Map;for(const e of c){const t=e.domains.length>0?e.domains:["(untagged)"],n=u.has(e.id);for(const e of t){g.has(e)||g.set(e,{covered:0,total:0});const t=g.get(e);t.total++,n&&t.covered++}}const y=Array.from(g.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:t.total>0?Math.round(t.covered/t.total*1e3)/10:100})),w=new Date;w.setDate(w.getDate()-7);const{count:b,error:v}=await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",w.toISOString());if(v)throw new Error(v.message);return ae(K({project_id:e.project_id,project_name:n.name,counts:o,test_status:l,coverage:f,coverage_by_domain:y,recent_changes:b??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(ht,{projectSummaryHandler:()=>_t});var ft,gt=j({"src/tools/project-summary.ts"(){Y(),de()}}),yt={};async function wt(e){try{const t=await J();let n,r;if(e.query&&e.query.trim().length>0){const i=await ue(t,e.project_id,e.query,{type:e.type,limit:e.limit});n=i.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=i.totalCount}else{const i=await me(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});n=i.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=i.totalCount}const i=await async function(e,t){const{data:n,error:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(r)throw new Error(r.message);const i=new Set,a=new Set;for(const e of n??[]){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)i.add(t);const n=t.level;n&&a.add(n)}}return{domains:[...i].sort(),levels:[...a].sort()}}(t,e.project_id);return ae(K({items:n,filters:{domains:i.domains,levels:i.levels,types:ft},project_id:e.project_id},X(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(yt,{browseHandler:()=>wt});var bt,vt,jt,xt,St=j({"src/tools/browse.ts"(){Y(),_e(),de(),ft=["requirement","test-case","note","table"]}}),It={};async function kt(e){try{const t=e.direction??"downstream",n=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await J(),i=await pe(r,e.project_id,e.item_id);if(!i)return se(ee("Item",e.item_id));const{data:a,error:s}=await r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(s)throw new Error(s.message);const{data:o,error:d}=await r.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(d)throw new Error(d.message);const c=new Map;for(const e of o??[])c.set(e.id,{title:e.title,type:e.type});const l=new Map,m=(e,t,n)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:n})};for(const e of a??[]){const n=e.type;"upstream"!==t&&"both"!==t||(vt.includes(n)&&m(e.from_id,e.to_id,n),jt.includes(n)&&m(e.to_id,e.from_id,xt[n]??n)),"downstream"!==t&&"both"!==t||(jt.includes(n)&&m(e.from_id,e.to_id,n),vt.includes(n)&&m(e.to_id,e.from_id,xt[n]??n)),"related"===n&&(m(e.from_id,e.to_id,"related"),m(e.to_id,e.from_id,"related"))}const p=new Set;p.add(e.item_id);const u=[];let h=0;const _=[];for(const t of l.get(e.item_id)??[])_.push({id:t.neighbor,depth:1,path:[{from_id:e.item_id,to_id:t.neighbor,relationship_type:t.relType}]});for(;_.length>0&&u.length<bt;){const{id:e,depth:t,path:r}=_.shift();if(p.has(e))continue;if(null!==n&&t>n)continue;p.add(e);const i=c.get(e);if(i&&(u.push({item_id:e,title:i.title,type:i.type,depth:t,relationship_path:r}),t>h&&(h=t),null===n||t<n))for(const n of l.get(e)??[])p.has(n.neighbor)||_.push({id:n.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:n.neighbor,relationship_type:n.relType}]})}const f={};for(const e of u)f[e.type]=(f[e.type]??0)+1;const g=c.get(e.item_id);return ae(K({root:{item_id:e.item_id,title:g?.title??i.title,type:g?.type??i.type},impacted_items:u,summary:{total_impacted:u.length,by_type:f,max_depth_reached:h,...u.length>=bt?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?se(re()):se(ie(e instanceof Error?e.message:String(e)))}}x(It,{impactAnalysisHandler:()=>kt});var Et,Tt,Ht,Ct=j({"src/tools/impact-analysis.ts"(){Y(),_e(),de(),bt=200,vt=["parent","verifies"],jt=["child","verified_by"],xt={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related"}}});function qt(e,t){return async n=>{let r;try{await J(),r=B()}catch{return t(n)}const i=function(e){const t=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||u,n=Date.now(),r=n-h;let i=_.get(e);if(i||(i={timestamps:[]},_.set(e,i)),i.timestamps=i.timestamps.filter(e=>e>r),i.timestamps.length>=t){const e=i.timestamps[0]+h-n;return{allowed:!1,retryAfterSeconds:Math.ceil(e/1e3)}}return i.timestamps.push(n),{allowed:!0}}(r);if(!i.allowed)return se(Z("Rate limit exceeded",[`Wait ${i.retryAfterSeconds} seconds before making more requests`,"Reduce the frequency of tool calls"]));const a=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let s,o="success";try{const e=await t(n),r=e;if(!0===r?.isError){o="error";const e=r?.content;if(e?.[0]?.text)try{s=JSON.parse(e[0].text).message}catch{}}return e}catch(e){throw o="error",s=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:n,status:o,duration_ms:a(),error_msg:s,project_id:n.project_id,session_id:Tt,client_name:Ht};try{!function(e,t,n){const r={...n.params};delete r.access_token,delete r.refresh_token,delete r.password,e.from("mcp_audit_log").insert({user_id:t,tool_name:n.tool_name,params:r,status:n.status,duration_ms:n.duration_ms,error_msg:n.error_msg??null,project_id:n.project_id??null,session_id:n.session_id??null,client_name:n.client_name??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await J(),r,t)}catch{}}}}function Ot(){return Tt}var Ut,zt,Rt=j({"src/server.ts"(){S(),I(),Y(),de(),le(),Et=new s.McpServer({name:"atoms-mcp-server",version:"0.4.0"}),Tt=d.randomUUID(),Ht=process.env.ATOMS_CLIENT_NAME??"unknown",Et.registerTool("atoms_status",{title:"ATOMS MCP Health Check",description:'Check the health and authentication status of the ATOMS MCP server.\n\nCall this FIRST if other atoms tools fail or return auth errors.\nThis tool works WITHOUT authentication — it checks whether credentials\nexist and are valid, and tells the user exactly what to do if not.\n\nArgs: None\n\nReturns:\n { status: "authenticated"|"not_authenticated"|"expired", email, message, next_steps }\n\nExamples:\n - "Is ATOMS MCP working?" → atoms_status()\n - "Why are atoms tools failing?" → atoms_status()',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{try{const{readCredentials:e,isTokenValid:t}=await Promise.resolve().then(()=>(M(),k)),n=await e();if(!n)return{content:[{type:"text",text:JSON.stringify({status:"not_authenticated",message:"No ATOMS credentials found. You need to login first.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp login","3. Complete the login in your browser","4. Restart Claude Desktop (quit and reopen)","5. Try your query again"]},null,2)}]};if(!t(n))try{const{getValidToken:e}=await Promise.resolve().then(()=>(V(),P)),{email:t}=await e();return{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:t,message:"Token was expired but has been refreshed. You're good to go!"},null,2)}]}}catch{return{content:[{type:"text",text:JSON.stringify({status:"expired",email:n.user_email??"unknown",message:"Your session has expired and could not be refreshed.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp logout","3. Run: npx @atoms-tech/atoms-mcp login","4. Complete the login in your browser","5. Restart Claude Desktop (quit and reopen)"]},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:n.user_email??"unknown",message:"ATOMS MCP is connected and authenticated. All tools are ready."},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({status:"error",message:`Health check failed: ${e instanceof Error?e.message:String(e)}`,next_steps:["1. Open a terminal","2. Run: npx @atoms-tech/atoms-mcp login","3. Restart Claude Desktop"]},null,2)}]}}}),Et.registerTool("atoms_list_projects",{title:"List ATOMS Projects",description:'List all projects the authenticated user has access to.\n\nThis is the ENTRY POINT tool. Call this first to discover project IDs,\nthen use those IDs with all other tools.\n\nArgs: None\n\nReturns:\n { status: "success", data: [{ id, name, description, org_id, created_at }] }\n\nExamples:\n - "What projects do I have?" → atoms_list_projects()\n - "Show my projects" → atoms_list_projects()\n\nWorkflow:\n atoms_list_projects → atoms_list_items(project_id) → atoms_get_item(project_id, item_id)',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(ye(),fe));return e()})),Et.registerTool("atoms_list_items",{title:"List ATOMS Items",description:'List items in an ATOMS project with optional type/domain/level filters.\n\nThis is the primary ENTRY POINT for discovering items. Use it to browse\nproject contents before drilling into specific items with atoms_get_item.\n\nArgs:\n - project_id (string, UUID): The project to list items from\n - type (string, optional): Filter: requirement|test-case|note|table\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - limit (number, optional): Max results, 1-200 (default 50)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { status: "success", data: [{ id, title, type, status, domains, level }], meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me all requirements" → atoms_list_items(project_id, type="requirement")\n - "What test cases exist?" → atoms_list_items(project_id, type="test-case")\n\nErrors:\n - "Project not found" → verify project_id\n - "Access denied" → check org membership',inputSchema:{project_id:o.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:o.z.string().optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:o.z.string().optional().describe("Filter by level (System, Subsystem, Component)"),limit:o.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(ve(),we));return t(e)})),Et.registerTool("atoms_get_item",{title:"Get ATOMS Item Details",description:'Get full details of a single item including relationships, test history, and ownership.\n\nUse after atoms_list_items or atoms_search to drill into a specific item.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID (e.g., "REQ-001", "TC-050")\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\nExamples:\n - "Show me requirement REQ-001" → atoms_get_item(project_id, "REQ-001")\n - "Get test case details" → atoms_get_item(project_id, "TC-050")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(Se(),je));return t(e)})),Et.registerTool("atoms_search",{title:"Search ATOMS Items",description:'Full-text search across items in a project. Searches title, body, and summary.\n\nAlternative entry point to atoms_list_items when you know what you\'re looking for.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Search text (max 1000 chars)\n - type (string, optional): Filter by type\n - limit (number, optional): Max results, 1-100 (default 25)\n\nReturns:\n Matching items with @basic fields, ranked by relevance.\n\nExamples:\n - "Find braking requirements" → atoms_search(project_id, "braking system")\n - "Search for safety tests" → atoms_search(project_id, "safety", type="test-case")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),query:o.z.string().min(1).max(1e3).describe("Search text"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(Ee(),Ie));return t(e)})),ce(Et,{appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:'Find requirements without linked test cases (coverage gaps).\n\nEssential for compliance reporting in safety-critical industries.\n\nIn MCP App hosts (Claude, ChatGPT), renders a visual coverage heatmap.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to analyze\n - domain (string, optional): Filter by domain\n - level (string, optional): Filter by level\n\nReturns:\n { covered, uncovered, total, coverage_percent, uncovered_items: [...] }\n\nExamples:\n - "What\'s our test coverage?" → atoms_get_coverage(project_id)\n - "Safety coverage gaps?" → atoms_get_coverage(project_id, domain="Safety")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),domain:o.z.string().optional().describe("Filter by domain tag"),level:o.z.string().optional().describe("Filter by level")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:qt("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(Ce(),Te));return t(e)})}),Et.registerTool("atoms_get_history",{title:"Get Item Change History",description:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_claude) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID"),limit:o.z.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(Ue(),qe));return t(e)})),ce(Et,{appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Shows parent-child relationships\nand requirement-to-test-case verification links.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive pan/zoom diagram.\nFalls back to Mermaid text for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to visualize\n - root_item_id (string, optional): Start node (default: all roots)\n - depth (number, optional): Max depth (default 3, max 10)\n - include_tests (boolean, optional): Show test case links (default true)\n\nReturns:\n Mermaid graph string.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),root_item_id:o.z.string().optional().describe("Root item ID to start from"),depth:o.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:o.z.boolean().default(!0).describe("Include test case links")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},extraResourceDomains:["cdn.jsdelivr.net","mermaid.ink"],handler:qt("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>(De(),ze));return t(e)})}),Et.registerTool("atoms_create_item",{title:"Create ATOMS Item",description:"Create a new requirement, test case, or note in a project.\n\nRequires editor or admin role. Changes are logged with AI actor attribution.\n\nArgs:\n - project_id (string, UUID): Target project\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_ids (string[], optional): Parent item IDs to link\n\nReturns:\n Created item with generated ID (e.g., \"REQ-058\")\n\nSide effects:\n - Logs to change_history with actor='mcp_claude'\n - Creates relationships if parent_ids provided",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the target project"),type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),body:o.z.string().optional().describe("Rich text body"),summary:o.z.string().optional().describe("Brief summary"),domains:o.z.array(o.z.string()).optional().describe("Domain tags"),level:o.z.string().optional().describe("System|Subsystem|Component"),parent_ids:o.z.array(o.z.string()).optional().describe("Parent item IDs to link")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},qt("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Ne(),Pe));return t(e)})),Et.registerTool("atoms_update_item",{title:"Update ATOMS Item",description:"Update an existing item's fields. Only provided fields are changed.\n\nRequires editor or admin role. Logs old/new data diff to change history.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to update\n - title, body, summary, domains, level, status: Fields to update (all optional)\n\nReturns:\n Updated item.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to update"),title:o.z.string().min(1).max(500).optional().describe("New title"),body:o.z.string().optional().describe("New body"),summary:o.z.string().optional().describe("New summary"),domains:o.z.array(o.z.string()).optional().describe("New domain tags"),level:o.z.string().optional().describe("New level"),status:o.z.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(We(),$e));return t(e)})),Et.registerTool("atoms_delete_item",{title:"Delete ATOMS Item",description:"Soft-delete an item (sets deleted_at, preserves for audit trail).\n\nRequires editor or admin role. The item is never truly removed.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to delete\n\nReturns:\n Confirmation with deleted item summary.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to soft-delete")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},qt("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Je(),Le));return t(e)})),Et.registerTool("atoms_link_items",{title:"Link ATOMS Items",description:"Add or remove relationships between items.\n\nSupports: parent, child, related, verifies, verified_by.\nUpdates both items' JSONB data and the shadow table.\n\nArgs:\n - project_id (string, UUID): Project containing both items\n - from_id (string): Source item\n - to_id (string): Target item\n - type (string): parent|child|related|verifies|verified_by\n - action (string): add|remove\n\nReturns:\n Updated relationship state for both items.",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),from_id:o.z.string().min(1).max(20).describe("Source item ID"),to_id:o.z.string().min(1).max(20).describe("Target item ID"),type:o.z.enum(["parent","child","related","verifies","verified_by"]).describe("Relationship type"),action:o.z.enum(["add","remove"]).describe("Add or remove the relationship")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(Qe(),Be));return t(e)})),ce(Et,{appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:"Bulk create multiple items in a single tool call. Essential for AI agents\nthat generate 20+ requirements at once.\n\nChecks write access once, generates sequential IDs, batch inserts all items,\nand reports per-item errors without aborting the entire batch.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive results table.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Target project\n - items (array): Up to 100 items to create, each with:\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_id (string, optional): Parent item ID to link\n\nReturns:\n { created: number, items: [{ id, title, type }], errors: [] }\n\nLimits:\n - Maximum 100 items per call\n - If any item fails, others still succeed — errors reported separately\n\nSide effects:\n - Logs to change_history with actor='mcp_claude' for each created item\n - Creates parent relationships for items with parent_id",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the target project"),items:o.z.array(o.z.object({type:o.z.enum(["requirement","test-case","note"]).describe("Item type"),title:o.z.string().min(1).max(500).describe("Item title"),body:o.z.string().optional().describe("Rich text body"),summary:o.z.string().optional().describe("Brief summary"),domains:o.z.array(o.z.string()).optional().describe("Domain tags"),level:o.z.string().optional().describe("System|Subsystem|Component"),parent_id:o.z.string().optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:qt("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(Xe(),Ye));return t(e)})}),Et.registerTool("atoms_record_test_result",{title:"Record Test Result",description:"Record a pass/fail/blocked result for a test case.\n\nAppends to the test results history. Use atoms_get_item to see all results.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., \"TC-001\")\n - result (string): passed|failed|blocked|not-run\n - note (string, optional): Reason or comment for this result\n\nReturns:\n Recorded result with timestamp.\n\nSide effects:\n - Appends to test_results table\n - Logs to change_history with actor='mcp_claude'",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:o.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:o.z.string().max(1e3).optional().describe("Reason or comment for this result")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},qt("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(at(),Ze));return t(e)})),ce(Et,{appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:'Walk the traceability graph from a starting item.\n\nAnswers questions like "which requirements does TC-003 verify?" or\n"if I change REQ-001, what\'s affected downstream?"\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive graph visualization.\nFalls back to flat list for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Starting item ID\n - direction (string): upstream|downstream|both\n - upstream: follow parent/verifies links (dependencies)\n - downstream: follow child/verified_by links (dependents)\n - both: trace in both directions\n - depth (number, optional): Max traversal depth (default 5, max 10)\n - relationship_types (string[], optional): Filter to specific types (parent, child, related, verifies, verified_by)\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], total_count }\n\nExamples:\n - "What does TC-003 verify?" → atoms_trace(project_id, "TC-003", "upstream")\n - "What\'s affected by REQ-001?" → atoms_trace(project_id, "REQ-001", "downstream")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Starting item ID"),direction:o.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:o.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:o.z.array(o.z.enum(["parent","child","related","verifies","verified_by"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:qt("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(dt(),st));return t(e)})}),Et.registerTool("atoms_list_variables",{title:"List Project Variables",description:"List all parameterized variables defined in a project.\n\nVariables are shared values (e.g., backup_camera_latency = 2s) that can be\nreferenced in requirement bodies as {variable_name}.\n\nArgs:\n - project_id (string, UUID): Project to list variables for\n\nReturns:\n { variables: [{ id, name, value, unit, description }], total }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(ut(),ct));return t(e)})),Et.registerTool("atoms_get_variable",{title:"Get Project Variable",description:'Get a specific variable by name, including which items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name (e.g., "backup_camera_latency")\n\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).describe("Variable name")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(ut(),ct));return t(e)})),Et.registerTool("atoms_update_variable",{title:"Update Project Variable",description:"Update a variable's value or unit. All items referencing this variable\nwill display the new value at render time.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name\n - value (string): New value\n - unit (string, optional): New unit abbreviation\n\nReturns:\n { variable, message }",inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),variable_name:o.z.string().min(1).describe("Variable name"),value:o.z.string().min(1).describe("New value"),unit:o.z.string().optional().describe("Unit abbreviation (e.g., 's', 'kg')")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(ut(),ct));return t(e)})),ce(Et,{appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:'One-call project health and compliance dashboard.\n\nReturns item counts by type, test execution status, requirement coverage\n(overall and by domain), and recent change activity.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive dashboard with charts.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project to summarize\n\nReturns:\n { project_name, counts, test_status, coverage, coverage_by_domain, recent_changes, last_updated }\n\nExamples:\n - "Give me a compliance snapshot" → atoms_project_summary(project_id)\n - "How\'s our test coverage?" → atoms_project_summary(project_id)',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:qt("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(gt(),ht));return t(e)})}),ce(Et,{appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:'View and filter items in an ATOMS project with a visual browser.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive filterable list\nwith expandable item details. Falls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to browse\n - type (string, optional): Filter by type (requirement, test-case, note, table)\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - query (string, optional): Full-text search query\n - limit (number, optional): Max results (default 25, max 100)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { items: [...], filters: { domains, levels, types }, meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me the requirements" → atoms_browse(project_id, type="requirement")\n - "Browse safety items" → atoms_browse(project_id, domain="Safety")\n - "Find braking requirements" → atoms_browse(project_id, query="braking")',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),type:o.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:o.z.string().optional().describe("Filter by domain tag"),level:o.z.string().optional().describe("Filter by level (System, Subsystem, Component)"),query:o.z.string().max(1e3).optional().describe("Full-text search query"),limit:o.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:o.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:qt("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(St(),yt));return t(e)})}),Et.registerTool("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:'Analyze the blast radius of changing a specific item.\n\nTraverses the relationship graph from the given item and returns every item that\nwould be affected by a change — with their types, depths, and full relationship paths.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to analyze (e.g., "REQ-001")\n - direction (string, optional): "downstream" (default) | "upstream" | "both"\n - downstream: what this item affects (children, verified_by)\n - upstream: what affects this item (parents, verifies)\n - both: full bidirectional traversal\n - depth (integer, optional): Max traversal depth. Omit for full depth (all reachable nodes).\n - include_variable_refs (boolean, optional): Reserved for future variable-aware impact. Default true.\n\nReturns:\n { root: { item_id, title, type }, impacted_items: [{ item_id, title, type, depth, relationship_path }], summary: { total_impacted, by_type, max_depth_reached } }\n\nExamples:\n - "What breaks if I change REQ-001?" → atoms_impact_analysis(project_id, "REQ-001")\n - "What\'s upstream of TC-005?" → atoms_impact_analysis(project_id, "TC-005", direction="upstream")\n - "Show direct dependencies only" → atoms_impact_analysis(project_id, "REQ-001", depth=1)\n\nErrors:\n - "Item not found" → verify item_id exists in the project',inputSchema:{project_id:o.z.string().uuid().describe("UUID of the project"),item_id:o.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:o.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:o.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:o.z.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},qt("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(Ct(),It));return t(e)}))}}),Mt={};async function Dt(){const e=d.randomBytes(32).toString("base64url"),t=d.createHash("sha256").update(e).digest("base64url"),n=`http://localhost:${Ut}${zt}`,r=new a.URL(`${R}/auth/mcp-consent`);return r.searchParams.set("redirect_uri",n),r.searchParams.set("code_challenge",t),r.searchParams.set("code_challenge_method","S256"),new Promise((t,n)=>{let i;function s(){clearTimeout(i)}const o=c.createServer(async(r,i)=>{const d=new a.URL(r.url??"/",`http://localhost:${Ut}`);if(d.pathname!==zt)return i.writeHead(404),void i.end("Not found");try{if("access_denied"===d.searchParams.get("error"))return i.writeHead(200,{"Content-Type":"text/html"}),i.end(At("Authorization was cancelled.")),s(),o.close(),void n(new Error("Authorization cancelled by user."));const r=d.searchParams.get("code");if(r){const a=await fetch(`${U}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:z},body:JSON.stringify({auth_code:r,code_verifier:e})}),d=await a.json();if(!a.ok||!d.access_token){const e=d.error_description??d.msg??"Unknown error";return i.writeHead(200,{"Content-Type":"text/html"}),i.end(At(`Code exchange failed: ${e}`)),s(),o.close(),void n(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(d.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(U,z,{global:{headers:{Authorization:`Bearer ${d.access_token}`}}}),{data:p,error:u}=await m.from("org_members").select("org_id").limit(1);return u||!p||0===p.length?(i.writeHead(200,{"Content-Type":"text/html"}),i.end(At('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://x.atoms.tech">x.atoms.tech</a> first, then run this login command again.')),s(),o.close(),void n(new Error("No ATOMS account found. Sign up at x.atoms.tech first."))):(await T({access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Date.now()+1e3*(d.expires_in??3600),user_email:c}),i.writeHead(200,{"Content-Type":"text/html"}),i.end(Pt(c)),s(),o.close(),void t({email:c}))}const a=d.searchParams.get("access_token"),c=d.searchParams.get("refresh_token"),l=parseInt(d.searchParams.get("expires_in")??"3600",10);a&&c?(await T({access_token:a,refresh_token:c,expires_at:Date.now()+1e3*l}),i.writeHead(200,{"Content-Type":"text/html"}),i.end(Pt("authenticated")),s(),o.close(),t({email:"authenticated"})):(i.writeHead(200,{"Content-Type":"text/html"}),i.end("<!DOCTYPE html>\n<html>\n<head><title>ATOMS MCP Login</title></head>\n<body>\n <h1>Completing login...</h1>\n <script>\n const hash = window.location.hash.substring(1);\n const params = new URLSearchParams(hash);\n const data = {\n access_token: params.get('access_token'),\n refresh_token: params.get('refresh_token'),\n expires_in: params.get('expires_in'),\n user_email: ''\n };\n if (data.access_token) {\n // Decode JWT to get email\n try {\n const payload = JSON.parse(atob(data.access_token.split('.')[1]));\n data.user_email = payload.email || '';\n } catch(e) {}\n fetch('/token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data)\n }).then(() => {\n document.body.innerHTML = '<h1>Login successful! You can close this tab.</h1>';\n }).catch(() => {\n document.body.innerHTML = '<h1>Login failed. Please try again.</h1>';\n });\n } else {\n document.body.innerHTML = '<h1>Login failed — no tokens received.</h1>';\n }\n <\/script>\n</body>\n</html>"))}catch(e){i.writeHead(500),i.end("Authentication failed"),s(),o.close(),n(e)}});o.on("request",async(e,r)=>{if("POST"===e.method&&"/token"===e.url){let i="";e.on("data",e=>{i+=e.toString()}),e.on("end",async()=>{try{const e=JSON.parse(i);await T({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0})),s(),o.close(),t({email:e.user_email??"authenticated"})}catch(e){r.writeHead(500),r.end("Failed to store credentials"),s(),o.close(),n(e)}})}}),o.listen(Ut,"127.0.0.1",async()=>{process.stderr.write("\nOpening browser for ATOMS login...\n"),process.stderr.write(`If the browser doesn't open, visit:\n${r.toString()}\n\n`);try{const{default:e}=await import("open");await e(r.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),i=setTimeout(()=>{o.close(),n(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function Pt(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Authorized</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #052e16;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 {\n font-size: 22px;\n font-weight: 600;\n margin-bottom: 8px;\n color: #22c55e;\n }\n .email {\n font-size: 14px;\n color: #a3a3a3;\n margin-bottom: 32px;\n }\n .permissions {\n text-align: left;\n background: #0a0a0a;\n border: 1px solid #262626;\n border-radius: 12px;\n padding: 20px;\n margin-bottom: 24px;\n }\n .permissions h3 {\n font-size: 12px;\n font-weight: 600;\n color: #737373;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n margin-bottom: 12px;\n }\n .perm-item {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 6px 0;\n font-size: 14px;\n color: #d4d4d4;\n }\n .perm-item .dot {\n width: 6px;\n height: 6px;\n background: #22c55e;\n border-radius: 50%;\n flex-shrink: 0;\n }\n .closing {\n font-size: 13px;\n color: #525252;\n }\n .closing span { color: #a3a3a3; font-variant-numeric: tabular-nums; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#22c55e" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1>Authorization Granted</h1>\n <p class="email">${e}</p>\n\n <div class="permissions">\n <h3>ATOMS MCP can now</h3>\n <div class="perm-item"><span class="dot"></span> Read your projects and requirements</div>\n <div class="perm-item"><span class="dot"></span> Create and edit requirements and test cases</div>\n <div class="perm-item"><span class="dot"></span> Record test results (pass/fail)</div>\n <div class="perm-item"><span class="dot"></span> Manage traceability relationships</div>\n <div class="perm-item"><span class="dot"></span> Export coverage reports and diagrams</div>\n </div>\n\n <p class="closing">This tab will close in <span id="countdown">5</span>s</p>\n </div>\n\n <script>\n let seconds = 5;\n const el = document.getElementById('countdown');\n const timer = setInterval(() => {\n seconds--;\n el.textContent = seconds;\n if (seconds <= 0) {\n clearInterval(timer);\n window.close();\n // If window.close() is blocked (not opened by script), update message\n setTimeout(() => {\n document.querySelector('.closing').textContent = 'You can close this tab now.';\n }, 500);\n }\n }, 1000);\n <\/script>\n</body>\n</html>`}function At(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Failed</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #450a0a;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 { font-size: 22px; font-weight: 600; margin-bottom: 16px; color: #ef4444; }\n .reason { font-size: 14px; color: #a3a3a3; line-height: 1.6; }\n .reason a { color: #7c3aed; text-decoration: underline; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#ef4444" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1>Authorization Failed</h1>\n <p class="reason">${e}</p>\n </div>\n</body>\n</html>`}x(Mt,{login:()=>Dt});var Nt=j({"src/auth/login.ts"(){M(),D(),Ut=19275,zt="/callback"}});Rt();var $t=process.argv.slice(2)[0];(async function(){switch($t){case"login":{const{login:e}=await Promise.resolve().then(()=>(Nt(),Mt));try{const{email:t}=await e();process.stderr.write(`\n ✓ Authenticated as ${t}\n`),process.stderr.write(" ✓ Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" Next steps:\n"),process.stderr.write(" $ claude mcp add atoms -- npx -y @atoms-tech/atoms-mcp\n"),process.stderr.write("\n Or add to Claude Desktop (Settings → MCP → Edit Config):\n"),process.stderr.write(' {\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp"]\n }\n }\n }\n\n')}catch(e){process.stderr.write(`\n ✗ ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>(V(),P));try{const{email:t,user_id:n}=await e();process.stderr.write(`\n ✓ Logged in as ${t}\n User ID: ${n}\n\n`)}catch(e){process.stderr.write("\n ✗ Not authenticated.\n Run: npx @atoms-tech/atoms-mcp login\n\n"),process.exit(1)}break}case"logout":{const{clearCredentials:e}=await Promise.resolve().then(()=>(M(),k));await e(),process.stderr.write("Logged out. Credentials removed.\n"),process.stderr.write("Run 'npx @atoms-tech/atoms-mcp login' to authenticate again.\n");break}case"--version":case"-v":process.stderr.write("@atoms-tech/atoms-mcp v0.4.0\n");break;case"--help":case"-h":process.stderr.write("ATOMS MCP Server — AI agent integration for requirements management\n\nUsage:\n npx @atoms-tech/atoms-mcp Start MCP server (stdio)\n npx @atoms-tech/atoms-mcp login Authenticate with ATOMS.tech\n npx @atoms-tech/atoms-mcp logout Switch account / clear credentials\n npx @atoms-tech/atoms-mcp whoami Show current user\n npx @atoms-tech/atoms-mcp --version Show version\n");break;default:{process.stderr.write("[atoms-mcp] Starting MCP server via stdio...\n");try{const{getValidToken:e}=await Promise.resolve().then(()=>(V(),P)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch{process.stderr.write("[atoms-mcp] No credentials found. Starting login flow...\n");try{const{login:e}=await Promise.resolve().then(()=>(Nt(),Mt)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch(e){process.stderr.write(`[atoms-mcp] Login failed: ${e instanceof Error?e.message:String(e)}\n[atoms-mcp] Starting server without auth. Tools will fail until you run: npx @atoms-tech/atoms-mcp login\n`)}}const e=new l.StdioServerTransport;await Et.connect(e),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}})().catch(e=>{process.stderr.write(`[atoms-mcp] Fatal: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)});
2
+ "use strict";var e=require("fs/promises"),t=require("os"),n=require("path"),r=require("@supabase/supabase-js"),i=require("@modelcontextprotocol/ext-apps/server"),a=require("url"),o=require("@modelcontextprotocol/sdk/server/mcp.js"),s=require("zod"),d=require("crypto"),c=require("http"),l=require("@modelcontextprotocol/sdk/server/stdio.js"),m="undefined"!=typeof document?document.currentScript:null;function p(e){return e&&e.__esModule?e:{default:e}}var u,h,_,f,g,y=p(e),b=p(n),w=Object.defineProperty,v=Object.getOwnPropertyNames,j=(e,t)=>function(){return e&&(t=(0,e[v(e)[0]])(e=0)),t},S=(e,t)=>{for(var n in t)w(e,n,{get:t[n],enumerable:!0})},x=j({"src/middleware/audit.ts"(){}}),I=j({"src/middleware/rate-limiter.ts"(){u=60,h=6e4,_=new Map}}),E={};async function k(){try{const t=await e.readFile(g,"utf-8"),n=JSON.parse(t);return n.access_token&&n.refresh_token?n:null}catch{return null}}async function H(t){await e.mkdir(f,{recursive:!0,mode:448}),await e.writeFile(g,JSON.stringify(t,null,2),{mode:384})}async function z(){const e=await k();return!!e&&e.expires_at>Date.now()+6e4}function T(e){return e.expires_at>Date.now()+6e4}async function U(){try{await e.unlink(g)}catch{}}function D(){return g}S(E,{clearCredentials:()=>U,getCredentialsPath:()=>D,hasValidCredentials:()=>z,isTokenValid:()=>T,readCredentials:()=>k,writeCredentials:()=>H});var q,O,C,R=j({"src/auth/token-store.ts"(){f=n.join(t.homedir(),".atoms"),g=n.join(f,"credentials.json")}}),P=j({"src/config.ts"(){q="https://gmebjyhomsbvhrxffzre.supabase.co",O="sb_publishable_b49MUAB8XCrQiF7x5b9lUA_w1aplSBH",C=process.env.ATOMS_APP_URL??"https://x.atoms.tech"}}),A={};async function $(){const e=process.env.ATOMS_ACCESS_TOKEN;if(e){const t=M(e);return{access_token:e,refresh_token:"",user_id:t.sub,email:t.email??""}}const t=await k();if(!t)throw new Error("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' to connect your ATOMS account.");if(t.expires_at>Date.now()+6e4){const e=M(t.access_token);return{access_token:t.access_token,refresh_token:t.refresh_token,user_id:e.sub,email:e.email??t.user_email??""}}process.stderr.write("[atoms-mcp] Refreshing access token...\n");const n=r.createClient(q,O),{data:i,error:a}=await n.auth.refreshSession({refresh_token:t.refresh_token});if(a||!i.session)throw new Error(`Token refresh failed: ${a?.message??"No session returned"}. Re-run 'npx @atoms-tech/atoms-mcp login'.`);const o=i.session;return await H({access_token:o.access_token,refresh_token:o.refresh_token,expires_at:Date.now()+1e3*(o.expires_in??3600),user_email:o.user?.email}),{access_token:o.access_token,refresh_token:o.refresh_token,user_id:o.user?.id??"",email:o.user?.email??""}}function M(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/").padEnd(t[1].length+(4-t[1].length%4)%4,"="),r=JSON.parse(Buffer.from(n,"base64").toString("utf-8"));if(!r.sub)throw new Error("JWT missing 'sub' claim");return r}S(A,{getValidToken:()=>$});var N,V,W,L,F=j({"src/auth/refresh.ts"(){R(),P()}});async function J(){if(N&&L>Date.now()+6e4)return N;N&&process.stderr.write("[atoms-mcp] Token expiring, refreshing client...\n");const{access_token:e,user_id:t,email:n}=await $(),i=e.split(".");if(3===i.length)try{const e=JSON.parse(Buffer.from(i[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());L=1e3*(e.exp??0)}catch{L=Date.now()+36e5}const a=r.createClient(q,O,{global:{headers:{Authorization:`Bearer ${e}`}}});return V=t,W=n,N=a}function B(){if(!V)throw new Error("Not authenticated. Call getClient() first.");return V}async function G(e,t){const n=B(),{data:r,error:i}=await e.from("projects").select("org_id").eq("id",t).maybeSingle();if(i||!r)throw new Error(`Project '${t}' not found`);const{data:a,error:o}=await e.from("org_members").select("role").eq("user_id",n).eq("org_id",r.org_id).maybeSingle();if(o||!a){const{data:t}=await e.rpc("is_platform_admin");if(!0===t)return"admin";throw new Error("Not a member of this project's organization")}if("viewer"===a.role)throw new Error("VIEWER_ROLE");return a.role}var Q,Y=j({"src/db/client.ts"(){F(),P(),N=null,V=null,W=null,L=0}});function K(e,t){return{status:"success",data:e,...t?{meta:t}:{}}}function Z(e,t,n){return{total_count:e,limit:t,offset:n,has_more:n+t<e}}function X(e,t){return{status:"error",message:e,next_steps:t}}function ee(e,t){return X(`${e} '${t}' not found`,[`Verify the ${e.toLowerCase()} ID is correct`,"Use atoms_list_items or atoms_search to find valid IDs"])}function te(e){return X(`${e} role cannot modify project data`,["Contact your org admin to upgrade your role to editor","Use read-only tools (atoms_list_items, atoms_get_item, atoms_search) instead"])}function ne(e){return X(`Validation error: ${e}`,["Check the parameter types and constraints in the tool description","Ensure all required parameters are provided"])}function re(){return X("Not authenticated. Run 'npx @atoms-tech/atoms-mcp login' first.",["Run: npx @atoms-tech/atoms-mcp login","Or set ATOMS_ACCESS_TOKEN environment variable"])}function ie(e){return X("Rate limited: too many requests to ATOMS API.",[e?`Wait ${e} seconds before retrying.`:"Wait a few seconds before retrying.","Reduce the frequency of back-to-back tool calls"])}function ae(e){const t=e instanceof Error?e.message:String(e);return/not authenticated/i.test(t)?re():/rate.?limit|too many requests|429/i.test(t)?ie():/invalid input syntax|invalid json|unexpected token|malformed|json parse/i.test(t)?X(`Parse error: ${t}`,["Check that body/title/summary fields contain valid text (no unexpected control characters)","If the content was generated programmatically, validate the string before passing it","Simplify the content and retry — if it succeeds, the original content has a malformed character"]):oe(t)}function oe(e){return/row.level security|permission denied for/i.test(e)?X("Permission denied: your account does not have write access to this project.",["Verify you have editor or admin role in this project","Contact your org admin to upgrade your permissions","Use atoms_list_projects to confirm the project_id is one you have access to"]):X(`Database error: ${e}`,["This may be a temporary issue — try again","If the error persists, check that the project_id is valid"])}function se(e){const t=JSON.stringify(e,null,2);if(t.length>Q&&"success"===e.status&&Array.isArray(e.data)){const t=Math.max(1,Math.floor(e.data.length/2)),n={...e,data:e.data.slice(0,t),meta:{...e.meta,truncated:!0,truncation_message:`Response truncated from ${e.data.length} to ${t} items. Use 'offset' parameter or add filters to see more results.`}};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}}return{content:[{type:"text",text:t}],structuredContent:e}}function de(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e,isError:!0}}var ce,le=j({"src/tools/_base.ts"(){Q=25e3}});function me(e,t){const n=`ui://${t.toolName}/${t.htmlFile}`,r=function(e,t){const n=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:m&&"SCRIPT"===m.tagName.toUpperCase()&&m.src||new URL("index.cjs",document.baseURI).href),r=b.default.dirname(n);return b.default.resolve(r,"apps","src","apps",e,t)}(t.appName,t.htmlFile),o=[...ce.resourceDomains,...t.extraResourceDomains??[]];i.registerAppTool(e,t.toolName,{title:t.title,description:t.description,inputSchema:t.inputSchema,annotations:t.annotations,_meta:{ui:{resourceUri:n}}},t.handler),i.registerAppResource(e,`${t.title} UI`,n,{mimeType:i.RESOURCE_MIME_TYPE},async()=>{const e=await y.default.readFile(r,"utf-8");return{contents:[{uri:n,mimeType:i.RESOURCE_MIME_TYPE,text:e,_meta:{ui:{csp:{resourceDomains:o}}}}]}})}var pe=j({"src/apps/register.ts"(){ce={resourceDomains:["fonts.googleapis.com","fonts.gstatic.com"]}}});async function ue(e,t,n){let r=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).order("created_at",{ascending:!0});n.type&&(r=r.eq("type",n.type)),n.domain&&(r=r.filter("data->tags->domains","cs",JSON.stringify([n.domain]))),n.level&&(r=r.filter("data->tags->>level","eq",n.level)),r=r.range(n.offset,n.offset+n.limit-1);const{data:i,error:a,count:o}=await r;if(a)throw new Error(a.message);return{items:i??[],totalCount:o??0}}async function he(e,t,n){const{data:r,error:i}=await e.from("items").select("*").eq("id",n).eq("project_id",t).is("deleted_at",null).maybeSingle();if(i)throw new Error(i.message);return r}async function _e(e,t,n,r){const i=n.trim();if(!i)return{items:[],totalCount:0};let a=e.from("items").select("*",{count:"exact"}).eq("project_id",t).is("deleted_at",null).or(`title.ilike.%${i}%,data->>body.ilike.%${i}%,data->>summary.ilike.%${i}%`).limit(r.limit);r.type&&(a=a.eq("type",r.type));const{data:o,error:s,count:d}=await a;if(s)throw new Error(s.message);return{items:o??[],totalCount:d??0}}async function fe(e,t,n){const r="requirement"===n?"REQ":"test-case"===n?"TC":"note"===n?"NOTE":"TABLE",{data:i,error:a}=await e.rpc("next_item_id",{p_project_id:t,p_prefix:r});if(a)throw new Error(`ID generation failed: ${a.message}`);return i}var ge=j({"src/db/queries.ts"(){}}),ye={};async function be(){try{const e=await J(),t=await async function(e){const{data:t,error:n}=await e.from("projects").select("id, name, description, org_id, created_at, organizations(name)").is("deleted_at",null).order("created_at",{ascending:!1});if(n)throw new Error(n.message);return(t??[]).map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.organizations?.name??"Unknown",created_at:e.created_at}))}(e);return se(K(t.map(e=>({id:e.id,name:e.name,description:e.description,org_id:e.org_id,org_name:e.org_name,created_at:e.created_at}))))}catch(e){return de(oe(e instanceof Error?e.message:"Unknown error"))}}S(ye,{listProjectsHandler:()=>be});var we=j({"src/tools/list-projects.ts"(){Y(),ge(),le()}}),ve={};async function je(e){try{const t=await J(),{items:n,totalCount:r}=await ue(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});return se(K(n.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Z(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(ve,{listItemsHandler:()=>je});var Se=j({"src/tools/list-items.ts"(){Y(),ge(),le()}}),xe={};async function Ie(e){try{const t=await J(),n=await he(t,e.project_id,e.item_id);if(!n)return de(ee("Item",e.item_id));const r=await async function(e,t,n){const{data:r,error:i}=await e.from("item_relationships").select("from_id, to_id, type").eq("project_id",t).or(`from_id.eq.${n},to_id.eq.${n}`);if(i)throw new Error(i.message);return r??[]}(t,e.project_id,e.item_id),i={parents:[],children:[],related:[],verified_by:[],verifies:[]};for(const t of r)if(t.from_id===e.item_id)t.type in i&&i[t.type].push(t.to_id);else{const e={parent:"children",child:"parents",verified_by:"verifies",verifies:"verified_by",related:"related"}[t.type]??t.type;e in i&&i[e].push(t.from_id)}let a=[];if("test-case"===n.type){const{data:n,error:r}=await t.from("test_results").select("result, run_by, run_at, note").eq("item_id",e.item_id).eq("project_id",e.project_id).order("run_at",{ascending:!1}).limit(20);!r&&n&&(a=n)}return se(K({id:n.id,type:n.type,title:n.title,summary:n.data?.summary,body:n.data?.body,tags:n.data?.tags??{domains:[]},ownership:n.data?.ownership??{primary:null,additional:[]},relationships:i,links:n.data?.links??[],status:n.data?.status,..."test-case"===n.type?{latest_result:a[0]?.result??"not-run",test_results:a}:{},metadata:{created_at:n.created_at,created_by:n.created_by,updated_at:n.updated_at,updated_by:n.updated_by,source_id:n.data?.metadata?.source_id}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(xe,{getItemHandler:()=>Ie});var Ee=j({"src/tools/get-item.ts"(){Y(),ge(),le()}}),ke={};async function He(e){try{const t=await J(),{items:n,totalCount:r}=await _e(t,e.project_id,e.query,{type:e.type,limit:e.limit});return se(K(n.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),Z(r,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(ke,{searchHandler:()=>He});var ze=j({"src/tools/search.ts"(){Y(),ge(),le()}}),Te={};async function Ue(e){try{const t=await J(),{covered:n,uncovered:r,total:i}=await async function(e,t,n){const{data:r,error:i}=await e.from("items").select("*").eq("project_id",t).eq("type","requirement").is("deleted_at",null);if(i)throw new Error(i.message);const a=(r??[]).filter(e=>!(n.domain&&!(e.data?.tags?.domains??[]).includes(n.domain)||n.level&&e.data?.tags?.level!==n.level)),{data:o,error:s}=await e.from("item_relationships").select("from_id").eq("project_id",t).eq("type","verified_by");if(s)throw new Error(s.message);const d=new Set((o??[]).map(e=>e.from_id));return{covered:a.filter(e=>d.has(e.id)),uncovered:a.filter(e=>!d.has(e.id)),total:a.length}}(t,e.project_id,{domain:e.domain,level:e.level}),a=r.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level}));return se(K({covered:n.length,uncovered:r.length,total:i,coverage_percent:i>0?Math.round(n.length/i*1e3)/10:100,uncovered_items:a}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(Te,{getCoverageHandler:()=>Ue});var De=j({"src/tools/get-coverage.ts"(){Y(),ge(),le()}}),qe={};async function Oe(e){try{const t=await J(),n=await async function(e,t,n,r){const{data:i,error:a}=await e.from("change_history").select("*").eq("item_id",n).eq("project_id",t).order("changed_at",{ascending:!1}).limit(r);if(a)throw new Error(a.message);return i??[]}(t,e.project_id,e.item_id,e.limit),r=n.map(e=>{const t=[],n=e.old_data,r=e.new_data;if(n&&r){const e=new Set([...Object.keys(n),...Object.keys(r)]);for(const i of e)JSON.stringify(n[i])!==JSON.stringify(r[i])&&t.push(i)}else r?t.push("(created)"):n&&t.push("(deleted)");return{id:e.id,event_type:e.event_type,changed_by:e.changed_by??null,changed_at:e.changed_at,actor:e.actor??"user",session_id:e.session_id??null,fields_changed:t}});return se(K(r,Z(r.length,e.limit,0)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(qe,{getHistoryHandler:()=>Oe});var Ce=j({"src/tools/get-history.ts"(){Y(),ge(),le()}}),Re={};async function Pe(e){try{const t=await J(),{data:n,error:r}=await t.from("items").select("id, title, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(r)throw new Error(r.message);if(!n||0===n.length)return se(K({mermaid:"graph TD\n empty[No items in project]"}));const{data:i,error:a}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(a)throw new Error(a.message);const o=new Map;for(const e of n)o.set(e.id,e);const s=["graph TD"],d=new Set,c=new Set,l=(new Set((i??[]).filter(e=>"child"===e.type).map(e=>e.to_id)),new Set((i??[]).filter(e=>"parent"===e.type).map(e=>e.from_id)));let m;m=e.root_item_id?[e.root_item_id]:n.filter(e=>!l.has(e.id)).filter(t=>!(!e.include_tests&&"test-case"===t.type)).map(e=>e.id);const p=m.map(e=>({id:e,depth:0}));for(;p.length>0;){const{id:t,depth:n}=p.shift();if(d.has(t)||n>e.depth)continue;d.add(t);const r=o.get(t);if(!r)continue;if(!e.include_tests&&"test-case"===r.type)continue;const a=Ae(r.title),l="requirement"===r.type?`["${a}"]`:"test-case"===r.type?`(["${a}"])`:`("${a}")`;s.push(` ${t}${l}`);for(const r of i??[]){if(r.from_id!==t)continue;const i=o.get(r.to_id);if(!i)continue;if(!e.include_tests&&"test-case"===i.type)continue;const a=`${r.from_id}-${r.type}-${r.to_id}`;c.has(a)||(c.add(a),"child"===r.type?s.push(` ${t} --\x3e ${r.to_id}`):"verified_by"===r.type?s.push(` ${t} -.->|verified_by| ${r.to_id}`):"related"===r.type&&s.push(` ${t} -.- ${r.to_id}`),!d.has(r.to_id)&&n+1<=e.depth&&p.push({id:r.to_id,depth:n+1}))}}return se(K({mermaid:s.join("\n"),node_count:d.size,edge_count:c.size}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}function Ae(e){return e.replace(/"/g,"'").replace(/[[\]{}()]/g,"").substring(0,50)}S(Re,{exportMermaidHandler:()=>Pe});var $e=j({"src/tools/export-mermaid.ts"(){Y(),le()}}),Me={};async function Ne(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}if(e.domains&&e.domains.length>0){const{data:n}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),r=n?.domains??[];if(r.length>0){const t=e.domains.filter(e=>!r.includes(e));if(t.length>0)return de(ne(`Unknown domain${t.length>1?"s":""}: ${t.join(", ")}. Registered: ${r.join(", ")}. Add new domains via Taxonomy Management in the ATOMS web app first.`))}}const r=await fe(t,e.project_id,e.type),i=(new Date).toISOString(),a={id:r,type:e.type,title:e.title,summary:e.summary,body:e.body,tags:{domains:e.domains??[],level:e.level},ownership:{primary:null,additional:[]},relationships:{parents:e.parent_ids??[],children:[],related:[]},links:[],metadata:{created_at:i,created_by:n,updated_at:i,updated_by:n}},{error:o}=await t.from("items").insert({id:r,project_id:e.project_id,type:e.type,title:e.title,data:a,created_by:n,updated_by:n}).select().single();if(o)throw new Error(o.message);if(e.parent_ids&&e.parent_ids.length>0){const n=e.parent_ids.map(t=>({from_id:r,to_id:t,type:"parent",project_id:e.project_id}));await t.from("item_relationships").insert(n).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: relationship sync failed: ${e.message}\n`)})}return await t.from("change_history").insert({item_id:r,project_id:e.project_id,changed_by:n,event_type:"created",old_data:null,new_data:a,actor:"mcp_claude",session_id:Jt()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),!1===e.echo?se(K({id:r,type:e.type})):se(K({id:r,type:e.type,title:e.title,summary:e.summary??"",body:e.body??"",domains:e.domains??[],level:e.level??"",project_id:e.project_id}))}catch(e){return de(ae(e))}}S(Me,{createItemHandler:()=>Ne});var Ve=j({"src/tools/create-item.ts"(){Y(),ge(),Qt(),le()}}),We={};async function Le(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const r=async(r,i,a,o)=>{const s=await he(t,e.project_id,r);if(!s)return{updated_fields:[],error:`Item "${r}" not found`};if(void 0!==i.domains&&i.domains.length>0){const{data:n}=await t.from("metadata").select("domains").eq("project_id",e.project_id).maybeSingle(),r=n?.domains??[];if(r.length>0){const e=i.domains.filter(e=>!r.includes(e));if(e.length>0)return{updated_fields:[],error:`Unknown domains: ${e.join(", ")}`}}}const d={...s.data},c={...s.data},l=[];void 0!==i.title&&(c.title=i.title,l.push("title")),void 0!==i.body&&(c.body=i.body,l.push("body")),void 0!==i.summary&&(c.summary=i.summary,l.push("summary")),void 0!==i.domains&&(c.tags={...c.tags,domains:i.domains},l.push("domains")),void 0!==i.level&&(c.tags={...c.tags,level:i.level},l.push("level")),void 0!==i.status&&(c.status=i.status,l.push("status")),c.metadata={...c.metadata,updated_at:(new Date).toISOString(),updated_by:n};const{error:m}=await t.from("items").update({title:i.title??s.title,data:c,updated_by:n}).eq("id",r).eq("project_id",e.project_id);if(m)return{updated_fields:[],error:m.message};const p={item_id:r,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:d,new_data:c,actor:"mcp_claude",session_id:Jt()};return a&&(p.batch_id=a),o&&(p.reason=o),await t.from("change_history").insert(p).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),{updated_fields:l,updatedData:c,itemType:s.type}};if(e.updates&&Array.isArray(e.updates)){const t=crypto.randomUUID(),n=!0===e.continue_on_error,i=[],a=[];for(const o of e.updates){const{updated_fields:s,error:d}=await r(o.item_id,o,t,e.reason);if(d){if(!n)return de(ne(`Batch stopped at "${o.item_id}": ${d}. ${i.length} item(s) already updated.`));a.push({item_id:o.item_id,error:d})}else i.push({id:o.item_id,updated_fields:s})}return se(K({batch_id:t,updated:i.length,results:!1===e.echo?void 0:i,errors:a}))}if(!e.item_id)return de(ne("Provide either item_id (single) or updates[] (array form)."));const{updated_fields:i,updatedData:a,itemType:o,error:s}=await r(e.item_id,{title:e.title,body:e.body,summary:e.summary,domains:e.domains,level:e.level,status:e.status},void 0,e.reason);if(s)return s.includes("not found")?de(ee("Item",e.item_id)):s.includes("Unknown domain")?de(ne(s)):de(oe(s));if(!1===e.echo)return se(K({id:e.item_id,updated_fields:i}));const d=a??{};return se(K({id:e.item_id,type:o,title:d.title??"",summary:d.summary??"",body:d.body??"",domains:d.tags?.domains??[],level:d.tags?.level??"",updated_fields:i}))}catch(e){return de(ae(e))}}S(We,{updateItemHandler:()=>Le});var Fe=j({"src/tools/update-item.ts"(){Y(),ge(),Qt(),le()}}),Je={};async function Be(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const r=await he(t,e.project_id,e.item_id);if(!r)return de(ee("Item",e.item_id));const{error:i}=await t.from("items").update({deleted_at:(new Date).toISOString()}).eq("id",e.item_id).eq("project_id",e.project_id);if(i)throw new Error(i.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:n,event_type:"deleted",old_data:r.data,new_data:null,actor:"mcp_claude",session_id:Jt()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),se(K({id:e.item_id,title:r.title,type:r.type,deleted:!0,message:`Item ${e.item_id} soft-deleted. It can still be found in audit logs.`}))}catch(e){return de(ae(e))}}S(Je,{deleteItemHandler:()=>Be});var Ge,Qe,Ye=j({"src/tools/delete-item.ts"(){Y(),ge(),Qt(),le()}}),Ke={};async function Ze(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const r=async(r,i,a)=>{const o=await he(t,e.project_id,r.from_id);if(!o)throw new Error(`Item "${r.from_id}" not found`);const s=await he(t,e.project_id,r.to_id);if(!s)throw new Error(`Item "${r.to_id}" not found`);const d=Ge(r.type);if("add"===r.action){const{data:i}=await t.from("item_relationships").select("from_id").eq("from_id",r.from_id).eq("to_id",r.to_id).eq("type",r.type).eq("project_id",e.project_id).maybeSingle();if(!i){const{error:n}=await t.from("item_relationships").insert({from_id:r.from_id,to_id:r.to_id,type:r.type,project_id:e.project_id});if(n)throw new Error(n.message)}const a=JSON.parse(JSON.stringify(o.data));a.relationships=a.relationships??{};const c=a.relationships[Qe(r.type)]??[];c.includes(r.to_id)||(a.relationships[Qe(r.type)]=[...c,r.to_id]),await t.from("items").update({data:a,updated_by:n}).eq("id",r.from_id).eq("project_id",e.project_id);const l=JSON.parse(JSON.stringify(s.data));l.relationships=l.relationships??{};const m=l.relationships[Qe(d)]??[];m.includes(r.from_id)||(l.relationships[Qe(d)]=[...m,r.from_id]),await t.from("items").update({data:l,updated_by:n}).eq("id",r.to_id).eq("project_id",e.project_id)}else{await Promise.all([t.from("item_relationships").delete().eq("from_id",r.from_id).eq("to_id",r.to_id).eq("type",r.type).eq("project_id",e.project_id),t.from("item_relationships").delete().eq("from_id",r.to_id).eq("to_id",r.from_id).eq("type",d).eq("project_id",e.project_id)]);const i=JSON.parse(JSON.stringify(o.data));i.relationships?.[Qe(r.type)]&&(i.relationships[Qe(r.type)]=i.relationships[Qe(r.type)].filter(e=>e!==r.to_id)),await t.from("items").update({data:i,updated_by:n}).eq("id",r.from_id).eq("project_id",e.project_id);const a=JSON.parse(JSON.stringify(s.data));a.relationships?.[Qe(d)]&&(a.relationships[Qe(d)]=a.relationships[Qe(d)].filter(e=>e!==r.from_id)),await t.from("items").update({data:a,updated_by:n}).eq("id",r.to_id).eq("project_id",e.project_id)}const c={item_id:r.from_id,project_id:e.project_id,changed_by:n,event_type:"updated",old_data:null,new_data:{relationship_change:{action:r.action,type:r.type,from:r.from_id,to:r.to_id}},actor:"mcp_claude",session_id:Jt()};i&&(c.batch_id=i),a&&(c.reason=a),await t.from("change_history").insert(c).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)})};if(e.operations&&Array.isArray(e.operations)){for(const t of e.operations)if(t.from_id===t.to_id)return de(ne(`Self-reference in batch: "${t.from_id}"`));const n=[...new Set(e.operations.flatMap(e=>[e.from_id,e.to_id]))],{data:i}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).in("id",n),a=new Set((i??[]).map(e=>e.id)),o=n.filter(e=>!a.has(e));if(o.length>0)return de(ee("Items",o.join(", ")));const{data:s}=await t.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id),d=new Map;for(const e of s??[])"parent"===e.type&&(d.has(e.from_id)||d.set(e.from_id,new Set),d.get(e.from_id).add(e.to_id));for(const t of e.operations){if("parent"!==t.type&&"child"!==t.type)continue;const[e,n]="parent"===t.type?[t.from_id,t.to_id]:[t.to_id,t.from_id];"remove"===t.action?d.get(e)?.delete(n):(d.has(e)||d.set(e,new Set),d.get(e).add(n))}const c=e=>{const t=new Set,n=[e];for(;n.length;){const e=n.pop();if(t.has(e))return e;t.add(e);for(const t of d.get(e)??[])n.push(t)}return null};for(const e of d.keys()){const t=c(e);if(t)return de(ne(`Batch would create a cycle at item "${t}". No changes applied.`))}const l=crypto.randomUUID(),m=e.operations.filter(e=>"remove"===e.action),p=e.operations.filter(e=>"add"===e.action);for(const t of[...m,...p])await r(t,l,e.reason);return se(K({batch_id:l,processed:e.operations.length,operations:!1===e.echo?void 0:e.operations}))}return e.from_id&&e.to_id&&e.type&&e.action?e.from_id===e.to_id?de(ne("Cannot create a relationship between an item and itself")):(await r({action:e.action,from_id:e.from_id,to_id:e.to_id,type:e.type},void 0,e.reason),!1===e.echo?se(K({action:e.action,from_id:e.from_id,to_id:e.to_id})):se(K({action:e.action,type:e.type,from_id:e.from_id,to_id:e.to_id,message:`Relationship ${"add"===e.action?"added":"removed"}: ${e.from_id} --[${e.type}]--\x3e ${e.to_id}`}))):de(ne("Provide (from_id, to_id, type, action) for single-op or operations[] for batch."))}catch(e){return de(ae(e))}}S(Ke,{linkItemsHandler:()=>Ze});var Xe=j({"src/tools/link-items.ts"(){Y(),ge(),Qt(),le(),Ge=e=>"parent"===e?"child":"child"===e?"parent":"verifies"===e?"verified_by":"verified_by"===e?"verifies":"related",Qe=e=>"parent"===e?"parents":"child"===e?"children":e}}),et={};async function tt(e){try{if(!e.items||0===e.items.length)return de(ne("items array must contain at least 1 item"));if(e.items.length>100)return de(ne(`Maximum 100 items per call (received ${e.items.length}). Split into multiple calls.`));const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const r=(new Date).toISOString(),i=Jt(),a=[],o=[],s=[];for(let n=0;n<e.items.length;n++){const r=e.items[n];try{const i=await fe(t,e.project_id,r.type);s.push({itemId:i,input:r,index:n})}catch(e){o.push({index:n,title:r.title,error:`ID generation failed: ${e instanceof Error?e.message:String(e)}`})}}if(0===s.length)return se(K({created:0,items:[],errors:o}));const d=[],c=new Map;for(const{itemId:t,input:i}of s){const a={id:t,type:i.type,title:i.title,summary:i.summary,body:i.body,tags:{domains:i.domains??[],level:i.level},ownership:{primary:null,additional:[]},relationships:{parents:i.parent_id?[i.parent_id]:[],children:[],related:[]},links:[],metadata:{created_at:r,created_by:n,updated_at:r,updated_by:n}};c.set(t,a),d.push({id:t,project_id:e.project_id,type:i.type,title:i.title,data:a,created_by:n,updated_by:n})}const{error:l}=await t.from("items").insert(d);if(l)for(const{itemId:e,input:n,index:r}of s){const i=d.find(t=>t.id===e);if(!i)continue;const{error:s}=await t.from("items").insert(i);s?o.push({index:r,title:n.title,error:s.message}):a.push({id:e,title:n.title,type:n.type})}else for(const{itemId:e,input:t}of s)a.push({id:e,title:t.title,type:t.type});const m=s.filter(({input:e})=>e.parent_id).filter(({itemId:e})=>a.some(t=>t.id===e)).map(({itemId:t,input:n})=>({from_id:t,to_id:n.parent_id,type:"parent",project_id:e.project_id}));m.length>0&&await t.from("item_relationships").insert(m).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk relationship sync failed: ${e.message}\n`)});const p=a.map(t=>({item_id:t.id,project_id:e.project_id,changed_by:n,event_type:"created",old_data:null,new_data:c.get(t.id)??null,actor:"mcp_claude",session_id:i}));return p.length>0&&await t.from("change_history").insert(p).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: bulk change_history log failed: ${e.message}\n`)}),se(K({created:a.length,items:a,errors:o.length>0?o:[],project_id:e.project_id}))}catch(e){return de(ae(e))}}S(et,{bulkImportHandler:()=>tt});var nt=j({"src/tools/bulk-import.ts"(){Y(),ge(),Qt(),le()}}),rt={};async function it(e){try{const t=await J(),n=B(),r=W??"";try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const i=await he(t,e.project_id,e.item_id);if(!i)return de(ee("Item",e.item_id));if("test-case"!==i.type)return de(ne(`Item '${e.item_id}' is a ${i.type}, not a test-case`));const a=(new Date).toISOString(),{error:o}=await t.from("test_results").insert({item_id:e.item_id,project_id:e.project_id,result:e.result,run_by:r||n,run_at:a,note:e.note??null});if(o)throw new Error(o.message);return await t.from("change_history").insert({item_id:e.item_id,project_id:e.project_id,changed_by:n,event_type:"test_result_recorded",old_data:null,new_data:{result:e.result,run_at:a,note:e.note},actor:"mcp_claude",session_id:Jt()}).then(({error:e})=>{e&&process.stderr.write(`[atoms-mcp] Warning: change_history log failed: ${e.message}\n`)}),se(K({item_id:e.item_id,result:e.result,run_at:a,run_by:r||n,note:e.note??null,message:`Test result '${e.result}' recorded for ${e.item_id}`}))}catch(e){return de(ae(e))}}S(rt,{recordTestResultHandler:()=>it});var at,ot,st,dt,ct=j({"src/tools/record-test-result.ts"(){Y(),ge(),Qt(),le()}}),lt={};async function mt(e){try{const t=Math.min(Math.max(e.depth??5,1),10),n=await J(),r=await he(n,e.project_id,e.item_id);if(!r)return de(ee("Item",e.item_id));const{data:i,error:a}=await n.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(a)throw new Error(a.message);const{data:o,error:s}=await n.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(s)throw new Error(s.message);const d=new Map;for(const e of o??[])d.set(e.id,{title:e.title,type:e.type});const c=new Map,l=(e,t,n)=>{c.has(e)||c.set(e,[]),c.get(e).push({neighbor:t,relType:n})},m=e.relationship_types?new Set(e.relationship_types):null;for(const t of i??[]){const n=t.type;if(("upstream"===e.direction||"both"===e.direction)&&(ot.includes(n)&&(m&&!m.has(n)||l(t.from_id,t.to_id,n)),st.includes(n))){const e=dt[n]??n;m&&!m.has(e)||l(t.to_id,t.from_id,e)}if(("downstream"===e.direction||"both"===e.direction)&&(st.includes(n)&&(m&&!m.has(n)||l(t.from_id,t.to_id,n)),ot.includes(n))){const e=dt[n]??n;m&&!m.has(e)||l(t.to_id,t.from_id,e)}"related"===n&&(m&&!m.has("related")||(l(t.from_id,t.to_id,"related"),l(t.to_id,t.from_id,"related")))}const p=new Set;p.add(e.item_id);const u=[],h=[],_=[],f=c.get(e.item_id)??[];for(const t of f)_.push({id:t.neighbor,depth:1,relType:t.relType,from:e.item_id});for(;_.length>0&&u.length<at;){const{id:e,depth:n,relType:r,from:i}=_.shift();if(p.has(e)||n>t)continue;p.add(e);const a=d.get(e);if(a&&(u.push({id:e,title:a.title,type:a.type,relationship:r,depth:n,from:i}),h.push({from:i,to:e,type:r}),n<t)){const t=c.get(e)??[];for(const r of t)p.has(r.neighbor)||_.push({id:r.neighbor,depth:n+1,relType:r.relType,from:e})}}const g=d.get(e.item_id),y=g?{id:e.item_id,title:g.title,type:g.type,relationship:"root",depth:0,from:e.item_id}:{id:e.item_id,title:r.title??e.item_id,type:r.type??"unknown",relationship:"root",depth:0,from:e.item_id};return se(K({root:e.item_id,direction:e.direction,depth_limit:t,items:[y,...u],edges:h,total_count:u.length+1,...u.length>=at?{truncated:!0,truncation_message:`Results capped at ${at} items. Use a smaller depth or filter by relationship_types.`}:{}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(lt,{traceHandler:()=>mt});var pt=j({"src/tools/trace.ts"(){Y(),ge(),le(),at=200,ot=["parent","verifies"],st=["child","verified_by"],dt={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related"}}}),ut={};async function ht(e){try{const t=await J(),{data:n,error:r}=await t.from("project_variables").select("*").eq("project_id",e.project_id).order("name");if(r)throw new Error(r.message);return se(K({variables:n||[],total:(n||[]).length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}async function _t(e){try{const t=await J(),{data:n,error:r}=await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle();if(r)throw new Error(r.message);if(!n)return de(ee("Variable",e.variable_name));const{data:i}=await t.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null),a=`{${e.variable_name}}`,o=(i||[]).filter(e=>(e.data?.body||"").includes(a));return se(K({variable:n,referenced_by:o.map(e=>({id:e.id,title:e.title,type:e.type})),reference_count:o.length}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}async function ft(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}if(!(await t.from("project_variables").select("*").eq("project_id",e.project_id).eq("name",e.variable_name).maybeSingle()).data)return de(ee("Variable",e.variable_name));const r={updated_by:n,updated_at:(new Date).toISOString()};void 0!==e.value&&(r.value=e.value),void 0!==e.unit&&(r.unit=e.unit||null),void 0!==e.description&&(r.description=e.description||null);const{data:i,error:a}=await t.from("project_variables").update(r).eq("project_id",e.project_id).eq("name",e.variable_name).select().single();if(a)throw new Error(a.message);return se(K({variable:i}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}async function gt(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const r=/^[a-zA-Z_][a-zA-Z0-9_]*$/;if(e.variables&&Array.isArray(e.variables)){const i=e.variables.filter(e=>!r.test(e.name));if(i.length>0)return de(ne(`Invalid variable name(s): ${i.map(e=>e.name).join(", ")}. Use letters, digits, underscores; must start with letter or underscore.`));const a=e.variables.map(e=>e.name),o=a.filter((e,t)=>a.indexOf(e)!==t);if(o.length>0)return de(ne(`Duplicate names in batch: ${[...new Set(o)].join(", ")}`));const{data:s}=await t.from("project_variables").select("name").eq("project_id",e.project_id).in("name",a),d=(s??[]).map(e=>e.name);if(d.length>0)return de(ne(`Variable(s) already exist: ${d.join(", ")}. Remove them from the batch or use atoms_update_variable to change values.`));const c=e.variables.map(t=>({project_id:e.project_id,name:t.name,value:t.value,unit:t.unit??null,description:t.description??null,created_by:n,updated_by:n})),{data:l,error:m}=await t.from("project_variables").insert(c).select();if(m)throw new Error(m.message);return se(K({batch_id:crypto.randomUUID(),created:(l??[]).length,variables:!1===e.echo?(l??[]).map(e=>({name:e.name})):l??[],message:`${(l??[]).length} variable(s) created. Reference them as {name} in requirement bodies.`}))}if(!e.name||!e.value)return de(ne("Provide either (name, value) for single variable or variables[] for batch."));if(!r.test(e.name))return de(ne(`Variable name "${e.name}" is invalid. Use letters, digits, and underscores only; must start with a letter or underscore.`));const{data:i,error:a}=await t.from("project_variables").insert({project_id:e.project_id,name:e.name,value:e.value,unit:e.unit??null,description:e.description??null,created_by:n,updated_by:n}).select().single();if(a){if(a.message.includes("unique")||a.message.includes("duplicate"))return de(ne(`Variable "${e.name}" already exists in this project.`));throw new Error(a.message)}return!1===e.echo?se(K({name:e.name})):se(K({variable:i,message:`Variable "${e.name}" created. Reference it in requirement bodies as {${e.name}}.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}async function yt(e){try{const t=await J();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const{data:n}=await t.from("project_variables").select("id").eq("project_id",e.project_id).eq("name",e.name).maybeSingle();if(!n)return de(ee("Variable",e.name));const{data:r}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->>body","ilike",`%{${e.name}}%`),i=(r??[]).length;if(i>0&&!e.force)return de(ne(`Variable "${e.name}" is referenced in ${i} item${i>1?"s":""}. Use force=true to delete anyway, or remove all {${e.name}} references first.`));const{error:a}=await t.from("project_variables").delete().eq("project_id",e.project_id).eq("name",e.name);if(a)throw new Error(a.message);return se(K({deleted:!0,name:e.name,referenced_by_items:i,warning:i>0?`${i} item${i>1?"s":""} still contain {${e.name}} — those references are now unresolved.`:void 0}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(ut,{createVariableHandler:()=>gt,deleteVariableHandler:()=>yt,getVariableHandler:()=>_t,listVariablesHandler:()=>ht,updateVariableHandler:()=>ft});var bt=j({"src/tools/variables.ts"(){Y(),le()}}),wt={};async function vt(e,t){const{data:n}=await e.from("metadata").select("domains, levels").eq("project_id",t).maybeSingle();return{domains:n?.domains??[],levels:n?.levels??[]}}async function jt(e,t,n,r){const{error:i}=await e.from("metadata").upsert({project_id:t,domains:n,levels:r},{onConflict:"project_id"});if(i)throw new Error(i.message)}async function St(e){try{const t=await J(),{domains:n}=await vt(t,e.project_id),{counts:r,orphans:i}=await async function(e,t,n){const{data:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null),i={};for(const e of n)i[e]=0;const a={};for(const e of r??[]){const t=e.data?.tags?.domains??[];for(const e of t)a[e]=(a[e]??0)+1,e in i&&i[e]++}const o=new Set(n),s={};for(const[e,t]of Object.entries(a))o.has(e)||(s[e]=t);return{counts:i,orphans:s}}(t,e.project_id,n),a=n.map(e=>({name:e,registered:!0,item_count:r[e]??0})),o=Object.entries(i).map(([e,t])=>({name:e,registered:!1,item_count:t})).sort((e,t)=>e.name.localeCompare(t.name)),s=[...a,...o];return se(K({domains:s,total:s.length,registered_count:a.length,unregistered_count:o.length,note:o.length>0?`${o.length} unregistered tag(s) found on items. Use atoms_create_domain to register them, or atoms_update_item to remove them.`:void 0}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}async function xt(e){try{const t=await J();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const{domains:n,levels:r}=await vt(t,e.project_id),i=e.name.trim().toLowerCase();return i?n.includes(i)?de(ne(`Domain "${i}" already exists in this project.`)):(await jt(t,e.project_id,[...n,i],r),se(K({domain:{name:i},message:`Domain "${i}" registered. You can now tag items with domains=["${i}"].`}))):de(ne("Domain name cannot be empty."))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}async function It(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const{domains:r,levels:i}=await vt(t,e.project_id),a=e.name.trim().toLowerCase(),o=e.new_name.trim().toLowerCase();if(!o)return de(ne("new_name cannot be empty."));const s=r.includes(a);if(!s){const{data:n}=await t.from("items").select("id").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a])).limit(1);if(!n||0===n.length)return de(ee("Domain",a))}if(o!==a&&r.includes(o))return de(ne(`Domain "${o}" already exists. Choose a different name.`));const{data:d,error:c}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(c)throw new Error(c.message);const l=(d??[]).length;if(e.dry_run)return se(K({dry_run:!0,rename:{from:a,to:o},items_affected:l,message:`Dry run: renaming "${a}" → "${o}" would update ${l} item${1!==l?"s":""}. Call again with dry_run=false to apply.`}));let m;return m=s?r.map(e=>e===a?o:e):r.includes(o)?r:[...r,o],await jt(t,e.project_id,m,i),(new Date).toISOString(),await Promise.all((d??[]).map(r=>{const i=(r.data?.tags?.domains??[]).map(e=>e===a?o:e),s={...r.data,tags:{...r.data?.tags??{},domains:i}};return t.from("items").update({data:s,updated_by:n}).eq("id",r.id).eq("project_id",e.project_id)})),se(K({domain:{name:o},renamed_from:a,items_updated:l,message:`Domain renamed "${a}" → "${o}". ${l} item${1!==l?"s":""} updated.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}async function Et(e){try{const t=await J(),n=B();try{await G(t,e.project_id)}catch(e){if(e instanceof Error&&"VIEWER_ROLE"===e.message)return de(te("Viewer"));throw e}const{domains:r,levels:i}=await vt(t,e.project_id),a=e.name.trim().toLowerCase(),o=r.includes(a),{data:s,error:d}=await t.from("items").select("id, data").eq("project_id",e.project_id).is("deleted_at",null).filter("data->tags->domains","cs",JSON.stringify([a]));if(d)throw new Error(d.message);const c=(s??[]).length;if(!o&&0===c)return de(ee("Domain",a));if(c>0&&!e.force)return de(ne(`Domain "${a}" is used by ${c} item${c>1?"s":""}. Use force=true to delete and strip the domain from all items, or re-tag them first.`));const l=o?r.filter(e=>e!==a):r;return await jt(t,e.project_id,l,i),(new Date).toISOString(),c>0&&await Promise.all((s??[]).map(r=>{const i={...r.data,tags:{...r.data?.tags??{},domains:(r.data?.tags?.domains??[]).filter(e=>e!==a)}};return t.from("items").update({data:i,updated_by:n}).eq("id",r.id).eq("project_id",e.project_id)})),se(K({deleted:!0,name:a,items_updated:c,message:c>0?`Domain "${a}" deleted and stripped from ${c} item${c>1?"s":""}.`:`Domain "${a}" deleted.`}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(wt,{createDomainHandler:()=>xt,deleteDomainHandler:()=>Et,listDomainsHandler:()=>St,updateDomainHandler:()=>It});var kt=j({"src/tools/domains.ts"(){Y(),le()}}),Ht={};async function zt(e){try{const t=await J(),{data:n,error:r}=await t.from("projects").select("id, name").eq("id",e.project_id).is("deleted_at",null).maybeSingle();if(r)throw new Error(r.message);if(!n)return de(ee("Project",e.project_id));const{data:i,error:a}=await t.from("items").select("id, type, data").eq("project_id",e.project_id).is("deleted_at",null);if(a)throw new Error(a.message);const o=i??[],s={requirements:0,test_cases:0,notes:0},d=[],c=[];for(const e of o)if("requirement"===e.type){s.requirements++;const t=e.data?.tags?.domains??[];c.push({id:e.id,domains:t})}else"test-case"===e.type?(s.test_cases++,d.push(e.id)):"note"===e.type&&s.notes++;const l={passed:0,failed:0,blocked:0,not_run:0};if(d.length>0){const{data:n,error:r}=await t.from("test_results").select("item_id, result, run_at").eq("project_id",e.project_id).order("run_at",{ascending:!1});if(r)throw new Error(r.message);const i=new Map;for(const e of n??[])i.has(e.item_id)||i.set(e.item_id,e.result);for(const e of d){const t=i.get(e);t&&"not-run"!==t?"passed"===t?l.passed++:"failed"===t?l.failed++:"blocked"===t?l.blocked++:l.not_run++:l.not_run++}}const{data:m,error:p}=await t.from("item_relationships").select("from_id").eq("project_id",e.project_id).eq("type","verified_by");if(p)throw new Error(p.message);const u=new Set((m??[]).map(e=>e.from_id)),h=c.filter(e=>u.has(e.id)).length,_=c.length,f={covered:h,uncovered:_-h,total:_,percent:_>0?Math.round(h/_*1e3)/10:100},g=new Map;for(const e of c){const t=e.domains.length>0?e.domains:["(untagged)"],n=u.has(e.id);for(const e of t){g.has(e)||g.set(e,{covered:0,total:0});const t=g.get(e);t.total++,n&&t.covered++}}const y=Array.from(g.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({domain:e,covered:t.covered,total:t.total,percent:t.total>0?Math.round(t.covered/t.total*1e3)/10:100})),b=new Date;b.setDate(b.getDate()-7);const{count:w,error:v}=await t.from("change_history").select("id",{count:"exact",head:!0}).eq("project_id",e.project_id).gte("changed_at",b.toISOString());if(v)throw new Error(v.message);return se(K({project_id:e.project_id,project_name:n.name,counts:s,test_status:l,coverage:f,coverage_by_domain:y,recent_changes:w??0,last_updated:(new Date).toISOString()}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(Ht,{projectSummaryHandler:()=>zt});var Tt,Ut=j({"src/tools/project-summary.ts"(){Y(),le()}}),Dt={};async function qt(e){try{const t=await J();let n,r;if(e.query&&e.query.trim().length>0){const i=await _e(t,e.project_id,e.query,{type:e.type,limit:e.limit});n=i.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=i.totalCount}else{const i=await ue(t,e.project_id,{type:e.type,domain:e.domain,level:e.level,limit:e.limit,offset:e.offset});n=i.items.map(e=>({id:e.id,title:e.title,type:e.type,status:e.data?.status,domains:e.data?.tags?.domains??[],level:e.data?.tags?.level})),r=i.totalCount}const i=await async function(e,t){const{data:n,error:r}=await e.from("items").select("data").eq("project_id",t).is("deleted_at",null);if(r)throw new Error(r.message);const i=new Set,a=new Set;for(const e of n??[]){const t=e.data?.tags;if(t){const e=t.domains;if(e)for(const t of e)i.add(t);const n=t.level;n&&a.add(n)}}return{domains:[...i].sort(),levels:[...a].sort()}}(t,e.project_id);return se(K({items:n,filters:{domains:i.domains,levels:i.levels,types:Tt},project_id:e.project_id},Z(r,e.limit,e.offset)))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S(Dt,{browseHandler:()=>qt});var Ot,Ct,Rt,Pt,At=j({"src/tools/browse.ts"(){Y(),ge(),le(),Tt=["requirement","test-case","note","table"]}}),$t={};async function Mt(e){try{const t=e.direction??"downstream",n=null!=e.depth?Math.min(Math.max(e.depth,1),20):null,r=await J(),i=await he(r,e.project_id,e.item_id);if(!i)return de(ee("Item",e.item_id));const{data:a,error:o}=await r.from("item_relationships").select("from_id, to_id, type").eq("project_id",e.project_id);if(o)throw new Error(o.message);const{data:s,error:d}=await r.from("items").select("id, title, type").eq("project_id",e.project_id).is("deleted_at",null);if(d)throw new Error(d.message);const c=new Map;for(const e of s??[])c.set(e.id,{title:e.title,type:e.type});const l=new Map,m=(e,t,n)=>{l.has(e)||l.set(e,[]),l.get(e).push({neighbor:t,relType:n})};for(const e of a??[]){const n=e.type;"upstream"!==t&&"both"!==t||(Ct.includes(n)&&m(e.from_id,e.to_id,n),Rt.includes(n)&&m(e.to_id,e.from_id,Pt[n]??n)),"downstream"!==t&&"both"!==t||(Rt.includes(n)&&m(e.from_id,e.to_id,n),Ct.includes(n)&&m(e.to_id,e.from_id,Pt[n]??n)),"related"===n&&(m(e.from_id,e.to_id,"related"),m(e.to_id,e.from_id,"related"))}const p=new Set;p.add(e.item_id);const u=[];let h=0;const _=[];for(const t of l.get(e.item_id)??[])_.push({id:t.neighbor,depth:1,path:[{from_id:e.item_id,to_id:t.neighbor,relationship_type:t.relType}]});for(;_.length>0&&u.length<Ot;){const{id:e,depth:t,path:r}=_.shift();if(p.has(e))continue;if(null!==n&&t>n)continue;p.add(e);const i=c.get(e);if(i&&(u.push({item_id:e,title:i.title,type:i.type,depth:t,relationship_path:r}),t>h&&(h=t),null===n||t<n))for(const n of l.get(e)??[])p.has(n.neighbor)||_.push({id:n.neighbor,depth:t+1,path:[...r,{from_id:e,to_id:n.neighbor,relationship_type:n.relType}]})}const f={};for(const e of u)f[e.type]=(f[e.type]??0)+1;const g=c.get(e.item_id);return se(K({root:{item_id:e.item_id,title:g?.title??i.title,type:g?.type??i.type},impacted_items:u,summary:{total_impacted:u.length,by_type:f,max_depth_reached:h,...u.length>=Ot?{truncated:!0}:{}}}))}catch(e){return e instanceof Error&&e.message.includes("Not authenticated")?de(re()):de(oe(e instanceof Error?e.message:String(e)))}}S($t,{impactAnalysisHandler:()=>Mt});var Nt,Vt,Wt,Lt=j({"src/tools/impact-analysis.ts"(){Y(),ge(),le(),Ot=200,Ct=["parent","verifies"],Rt=["child","verified_by"],Pt={parent:"child",child:"parent",verifies:"verified_by",verified_by:"verifies",related:"related"}}});function Ft(e,t){return async n=>{let r;try{await J(),r=B()}catch{return t(n)}const i=function(e){const t=parseInt(process.env.ATOMS_RATE_LIMIT_RPM??"",10)||u,n=Date.now(),r=n-h;let i=_.get(e);if(i||(i={timestamps:[]},_.set(e,i)),i.timestamps=i.timestamps.filter(e=>e>r),i.timestamps.length>=t){const e=i.timestamps[0]+h-n;return{allowed:!1,retryAfterSeconds:Math.ceil(e/1e3)}}return i.timestamps.push(n),{allowed:!0}}(r);if(!i.allowed)return de(ie(i.retryAfterSeconds));const a=function(){const e=performance.now();return()=>Math.round(performance.now()-e)}();let o,s="success";try{const e=await t(n),r=e;if(!0===r?.isError){s="error";const e=r?.content;if(e?.[0]?.text)try{o=JSON.parse(e[0].text).message}catch{}}return e}catch(e){throw s="error",o=e instanceof Error?e.message:String(e),e}finally{const t={tool_name:e,params:n,status:s,duration_ms:a(),error_msg:o,project_id:n.project_id,session_id:Vt,client_name:Wt};try{!function(e,t,n){const r={...n.params};delete r.access_token,delete r.refresh_token,delete r.password,e.from("mcp_audit_log").insert({user_id:t,tool_name:n.tool_name,params:r,status:n.status,duration_ms:n.duration_ms,error_msg:n.error_msg??null,project_id:n.project_id??null,session_id:n.session_id??null,client_name:n.client_name??null}).then(({error:e})=>{e&&process.stderr.write(`[audit] Failed to log: ${e.message}\n`)})}(await J(),r,t)}catch{}}}}function Jt(){return Vt}var Bt,Gt,Qt=j({"src/server.ts"(){x(),I(),Y(),le(),pe(),Nt=new o.McpServer({name:"atoms-mcp-server",version:"0.4.0"}),Vt=d.randomUUID(),Wt=process.env.ATOMS_CLIENT_NAME??"unknown",Nt.registerTool("atoms_status",{title:"ATOMS MCP Health Check",description:'Check the health and authentication status of the ATOMS MCP server.\n\nCall this FIRST if other atoms tools fail or return auth errors.\nThis tool works WITHOUT authentication — it checks whether credentials\nexist and are valid, and tells the user exactly what to do if not.\n\nArgs: None\n\nReturns:\n { status: "authenticated"|"not_authenticated"|"expired", email, message, next_steps }\n\nExamples:\n - "Is ATOMS MCP working?" → atoms_status()\n - "Why are atoms tools failing?" → atoms_status()',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{try{const{readCredentials:e,isTokenValid:t}=await Promise.resolve().then(()=>(R(),E)),n=await e();if(!n)return{content:[{type:"text",text:JSON.stringify({status:"not_authenticated",message:"No ATOMS credentials found. You need to login first.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp login","3. Complete the login in your browser","4. Restart Claude Desktop (quit and reopen)","5. Try your query again"]},null,2)}]};if(!t(n))try{const{getValidToken:e}=await Promise.resolve().then(()=>(F(),A)),{email:t}=await e();return{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:t,message:"Token was expired but has been refreshed. You're good to go!"},null,2)}]}}catch{return{content:[{type:"text",text:JSON.stringify({status:"expired",email:n.user_email??"unknown",message:"Your session has expired and could not be refreshed.",next_steps:["1. Open a terminal on your machine","2. Run: npx @atoms-tech/atoms-mcp logout","3. Run: npx @atoms-tech/atoms-mcp login","4. Complete the login in your browser","5. Restart Claude Desktop (quit and reopen)"]},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({status:"authenticated",email:n.user_email??"unknown",message:"ATOMS MCP is connected and authenticated. All tools are ready."},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({status:"error",message:`Health check failed: ${e instanceof Error?e.message:String(e)}`,next_steps:["1. Open a terminal","2. Run: npx @atoms-tech/atoms-mcp login","3. Restart Claude Desktop"]},null,2)}]}}}),Nt.registerTool("atoms_list_projects",{title:"List ATOMS Projects",description:'List all projects the authenticated user has access to.\n\nThis is the ENTRY POINT tool. Call this first to discover project IDs,\nthen use those IDs with all other tools.\n\nArgs: None\n\nReturns:\n { status: "success", data: [{ id, name, description, org_id, created_at }] }\n\nExamples:\n - "What projects do I have?" → atoms_list_projects()\n - "Show my projects" → atoms_list_projects()\n\nWorkflow:\n atoms_list_projects → atoms_list_items(project_id) → atoms_get_item(project_id, item_id)',inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_list_projects",async()=>{const{listProjectsHandler:e}=await Promise.resolve().then(()=>(we(),ye));return e()})),Nt.registerTool("atoms_list_items",{title:"List ATOMS Items",description:'List items in an ATOMS project with optional type/domain/level filters.\n\nThis is the primary ENTRY POINT for discovering items. Use it to browse\nproject contents before drilling into specific items with atoms_get_item.\n\nArgs:\n - project_id (string, UUID): The project to list items from\n - type (string, optional): Filter: requirement|test-case|note|table\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - limit (number, optional): Max results, 1-200 (default 50)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { status: "success", data: [{ id, title, type, status, domains, level }], meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me all requirements" → atoms_list_items(project_id, type="requirement")\n - "What test cases exist?" → atoms_list_items(project_id, type="test-case")\n\nErrors:\n - "Project not found" → verify project_id\n - "Access denied" → check org membership',inputSchema:{project_id:s.z.string().uuid("Must be a valid project UUID").describe("UUID of the project"),type:s.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:s.z.string().optional().describe("Filter by domain tag (e.g., 'Safety', 'Performance')"),level:s.z.string().optional().describe("Filter by level (System, Subsystem, Component)"),limit:s.z.number().int().min(1).max(200).default(50).describe("Max results (default 50, max 200)"),offset:s.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_list_items",async e=>{const{listItemsHandler:t}=await Promise.resolve().then(()=>(Se(),ve));return t(e)})),Nt.registerTool("atoms_get_item",{title:"Get ATOMS Item Details",description:'Get full details of a single item including relationships, test history, and ownership.\n\nUse after atoms_list_items or atoms_search to drill into a specific item.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID (e.g., "REQ-001", "TC-050")\n\nReturns:\n Full WorkItem with relationships, test runs, ownership, metadata.\n\nExamples:\n - "Show me requirement REQ-001" → atoms_get_item(project_id, "REQ-001")\n - "Get test case details" → atoms_get_item(project_id, "TC-050")',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),item_id:s.z.string().min(1).max(20).describe("Item ID (e.g., REQ-001)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_get_item",async e=>{const{getItemHandler:t}=await Promise.resolve().then(()=>(Ee(),xe));return t(e)})),Nt.registerTool("atoms_search",{title:"Search ATOMS Items",description:'Full-text search across items in a project. Searches title, body, and summary.\n\nAlternative entry point to atoms_list_items when you know what you\'re looking for.\n\nArgs:\n - project_id (string, UUID): The project to search in\n - query (string): Search text (max 1000 chars)\n - type (string, optional): Filter by type\n - limit (number, optional): Max results, 1-100 (default 25)\n\nReturns:\n Matching items with @basic fields, ranked by relevance.\n\nExamples:\n - "Find braking requirements" → atoms_search(project_id, "braking system")\n - "Search for safety tests" → atoms_search(project_id, "safety", type="test-case")',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),query:s.z.string().min(1).max(1e3).describe("Search text"),type:s.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),limit:s.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_search",async e=>{const{searchHandler:t}=await Promise.resolve().then(()=>(ze(),ke));return t(e)})),me(Nt,{appName:"coverage",htmlFile:"coverage-app.html",toolName:"atoms_get_coverage",title:"Get Test Coverage Report",description:'Find requirements without linked test cases (coverage gaps).\n\nEssential for compliance reporting in safety-critical industries.\n\nIn MCP App hosts (Claude, ChatGPT), renders a visual coverage heatmap.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to analyze\n - domain (string, optional): Filter by domain\n - level (string, optional): Filter by level\n\nReturns:\n { covered, uncovered, total, coverage_percent, uncovered_items: [...] }\n\nExamples:\n - "What\'s our test coverage?" → atoms_get_coverage(project_id)\n - "Safety coverage gaps?" → atoms_get_coverage(project_id, domain="Safety")',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),domain:s.z.string().optional().describe("Filter by domain tag"),level:s.z.string().optional().describe("Filter by level")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Ft("atoms_get_coverage",async e=>{const{getCoverageHandler:t}=await Promise.resolve().then(()=>(De(),Te));return t(e)})}),Nt.registerTool("atoms_get_history",{title:"Get Item Change History",description:"Audit trail for an item — who changed what, when, and whether it was human or AI.\n\nShows actor attribution (user vs mcp_claude) and session grouping.\n\nArgs:\n - project_id (string, UUID): The project containing the item\n - item_id (string): Item ID\n - limit (number, optional): Max entries (default 20, max 100)\n\nReturns:\n Change entries with actor, session_id, event_type, changed_at, fields_changed.",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),item_id:s.z.string().min(1).max(20).describe("Item ID"),limit:s.z.number().int().min(1).max(100).default(20).describe("Max entries (default 20)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_get_history",async e=>{const{getHistoryHandler:t}=await Promise.resolve().then(()=>(Ce(),qe));return t(e)})),me(Nt,{appName:"mermaid",htmlFile:"mermaid-app.html",toolName:"atoms_export_mermaid",title:"Export Mermaid Diagram",description:"Generate a Mermaid diagram of the requirement/test hierarchy.\n\nOutput is paste-ready for markdown docs. Shows parent-child relationships\nand requirement-to-test-case verification links.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive pan/zoom diagram.\nFalls back to Mermaid text for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to visualize\n - root_item_id (string, optional): Start node (default: all roots)\n - depth (number, optional): Max depth (default 3, max 10)\n - include_tests (boolean, optional): Show test case links (default true)\n\nReturns:\n Mermaid graph string.",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),root_item_id:s.z.string().optional().describe("Root item ID to start from"),depth:s.z.number().int().min(1).max(10).default(3).describe("Max depth"),include_tests:s.z.boolean().default(!0).describe("Include test case links")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},extraResourceDomains:["cdn.jsdelivr.net","mermaid.ink"],handler:Ft("atoms_export_mermaid",async e=>{const{exportMermaidHandler:t}=await Promise.resolve().then(()=>($e(),Re));return t(e)})}),Nt.registerTool("atoms_create_item",{title:"Create ATOMS Item",description:"Create a new requirement, test case, or note in a project.\n\nRequires editor or admin role. Changes are logged with AI actor attribution.\n\nArgs:\n - project_id (string, UUID): Target project\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_ids (string[], optional): Parent item IDs to link\n\nReturns:\n Created item with generated ID (e.g., \"REQ-058\")\n\nSide effects:\n - Logs to change_history with actor='mcp_claude'\n - Creates relationships if parent_ids provided",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the target project"),type:s.z.enum(["requirement","test-case","note"]).describe("Item type"),title:s.z.string().min(1).max(500).describe("Item title"),body:s.z.string().optional().describe("Rich text body"),summary:s.z.string().optional().describe("Brief summary"),domains:s.z.array(s.z.string()).optional().describe("Domain tags"),level:s.z.string().optional().describe("System|Subsystem|Component"),parent_ids:s.z.array(s.z.string()).optional().describe("Parent item IDs to link"),echo:s.z.boolean().optional().describe("false → lean {id,type} response, saves ~580 tokens")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Ft("atoms_create_item",async e=>{const{createItemHandler:t}=await Promise.resolve().then(()=>(Ve(),Me));return t(e)})),Nt.registerTool("atoms_update_item",{title:"Update ATOMS Item",description:"Update an existing item's fields. Only provided fields are changed.\n\nRequires editor or admin role. Logs old/new data diff to change history.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to update\n - title, body, summary, domains, level, status: Fields to update (all optional)\n\nReturns:\n Updated item.",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),item_id:s.z.string().min(1).max(20).optional().describe("Item ID (single form)"),title:s.z.string().min(1).max(500).optional().describe("New title"),body:s.z.string().optional().describe("New body"),summary:s.z.string().optional().describe("New summary"),domains:s.z.array(s.z.string()).optional().describe("New domain tags"),level:s.z.string().optional().describe("New level"),status:s.z.enum(["passed","failed","blocked","not-run"]).optional().describe("Test case status"),echo:s.z.boolean().optional().describe("false → lean {id,updated_fields} response, saves ~580 tokens"),reason:s.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),updates:s.z.array(s.z.object({item_id:s.z.string().min(1).max(20),title:s.z.string().min(1).max(500).optional(),body:s.z.string().optional(),summary:s.z.string().optional(),domains:s.z.array(s.z.string()).optional(),level:s.z.string().optional(),status:s.z.enum(["passed","failed","blocked","not-run"]).optional()})).optional().describe("Array form: update many items in one call"),idempotency_key:s.z.string().max(128).optional().describe("Safe retry key (24h TTL)"),continue_on_error:s.z.boolean().optional().describe("Allow partial success (default false = atomic)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_update_item",async e=>{const{updateItemHandler:t}=await Promise.resolve().then(()=>(Fe(),We));return t(e)})),Nt.registerTool("atoms_delete_item",{title:"Delete ATOMS Item",description:"Soft-delete an item (sets deleted_at, preserves for audit trail).\n\nRequires editor or admin role. The item is never truly removed.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to delete\n\nReturns:\n Confirmation with deleted item summary.",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),item_id:s.z.string().min(1).max(20).describe("Item ID to soft-delete")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_delete_item",async e=>{const{deleteItemHandler:t}=await Promise.resolve().then(()=>(Ye(),Je));return t(e)})),Nt.registerTool("atoms_link_items",{title:"Link ATOMS Items",description:"Add or remove relationships between items.\n\nSupports: parent, child, related, verifies, verified_by.\nUpdates both items' JSONB data and the shadow table.\n\nArgs:\n - project_id (string, UUID): Project containing both items\n - from_id (string): Source item\n - to_id (string): Target item\n - type (string): parent|child|related|verifies|verified_by\n - action (string): add|remove\n\nReturns:\n Updated relationship state for both items.",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),from_id:s.z.string().min(1).max(20).optional().describe("Source item ID (single form)"),to_id:s.z.string().min(1).max(20).optional().describe("Target item ID (single form)"),type:s.z.enum(["parent","child","related","verifies","verified_by"]).optional().describe("Relationship type"),action:s.z.enum(["add","remove"]).optional().describe("Add or remove"),echo:s.z.boolean().optional().describe("false → lean response"),reason:s.z.string().max(500).optional().describe("Change rationale, persisted in audit history"),operations:s.z.array(s.z.object({action:s.z.enum(["add","remove"]),from_id:s.z.string().min(1).max(20),to_id:s.z.string().min(1).max(20),type:s.z.enum(["parent","child","related","verifies","verified_by"])})).optional().describe("Array form: batch relationship ops. Always atomic with DAG cycle detection."),idempotency_key:s.z.string().max(128).optional().describe("Safe retry key (24h TTL)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_link_items",async e=>{const{linkItemsHandler:t}=await Promise.resolve().then(()=>(Xe(),Ke));return t(e)})),me(Nt,{appName:"import",htmlFile:"import-app.html",toolName:"atoms_bulk_import",title:"Bulk Import ATOMS Items",description:"Bulk create multiple items in a single tool call. Essential for AI agents\nthat generate 20+ requirements at once.\n\nChecks write access once, generates sequential IDs, batch inserts all items,\nand reports per-item errors without aborting the entire batch.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive results table.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Target project\n - items (array): Up to 100 items to create, each with:\n - type (string): requirement|test-case|note\n - title (string): Item title (max 500 chars)\n - body (string, optional): Rich text body\n - summary (string, optional): Brief summary\n - domains (string[], optional): Domain tags\n - level (string, optional): System|Subsystem|Component\n - parent_id (string, optional): Parent item ID to link\n\nReturns:\n { created: number, items: [{ id, title, type }], errors: [] }\n\nLimits:\n - Maximum 100 items per call\n - If any item fails, others still succeed — errors reported separately\n\nSide effects:\n - Logs to change_history with actor='mcp_claude' for each created item\n - Creates parent relationships for items with parent_id",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the target project"),items:s.z.array(s.z.object({type:s.z.enum(["requirement","test-case","note"]).describe("Item type"),title:s.z.string().min(1).max(500).describe("Item title"),body:s.z.string().optional().describe("Rich text body"),summary:s.z.string().optional().describe("Brief summary"),domains:s.z.array(s.z.string()).optional().describe("Domain tags"),level:s.z.string().optional().describe("System|Subsystem|Component"),parent_id:s.z.string().optional().describe("Parent item ID to link")})).min(1).max(100).describe("Items to create (1-100)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},handler:Ft("atoms_bulk_import",async e=>{const{bulkImportHandler:t}=await Promise.resolve().then(()=>(nt(),et));return t(e)})}),Nt.registerTool("atoms_record_test_result",{title:"Record Test Result",description:"Record a pass/fail/blocked result for a test case.\n\nAppends to the test results history. Use atoms_get_item to see all results.\n\nArgs:\n - project_id (string, UUID): Project containing the test case\n - item_id (string): Test case ID (e.g., \"TC-001\")\n - result (string): passed|failed|blocked|not-run\n - note (string, optional): Reason or comment for this result\n\nReturns:\n Recorded result with timestamp.\n\nSide effects:\n - Appends to test_results table\n - Logs to change_history with actor='mcp_claude'",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),item_id:s.z.string().min(1).max(20).describe("Test case ID (e.g., TC-001)"),result:s.z.enum(["passed","failed","blocked","not-run"]).describe("Test result"),note:s.z.string().max(1e3).optional().describe("Reason or comment for this result")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Ft("atoms_record_test_result",async e=>{const{recordTestResultHandler:t}=await Promise.resolve().then(()=>(ct(),rt));return t(e)})),me(Nt,{appName:"trace",htmlFile:"trace-app.html",toolName:"atoms_trace",title:"Trace Item Relationships",description:'Walk the traceability graph from a starting item.\n\nAnswers questions like "which requirements does TC-003 verify?" or\n"if I change REQ-001, what\'s affected downstream?"\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive graph visualization.\nFalls back to flat list for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Starting item ID\n - direction (string): upstream|downstream|both\n - upstream: follow parent/verifies links (dependencies)\n - downstream: follow child/verified_by links (dependents)\n - both: trace in both directions\n - depth (number, optional): Max traversal depth (default 5, max 10)\n - relationship_types (string[], optional): Filter to specific types (parent, child, related, verifies, verified_by)\n\nReturns:\n { root, direction, items: [{ id, title, type, relationship, depth }], total_count }\n\nExamples:\n - "What does TC-003 verify?" → atoms_trace(project_id, "TC-003", "upstream")\n - "What\'s affected by REQ-001?" → atoms_trace(project_id, "REQ-001", "downstream")',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),item_id:s.z.string().min(1).max(20).describe("Starting item ID"),direction:s.z.enum(["upstream","downstream","both"]).describe("Traversal direction"),depth:s.z.number().int().min(1).max(10).default(5).describe("Max traversal depth (default 5)"),relationship_types:s.z.array(s.z.enum(["parent","child","related","verifies","verified_by"])).optional().describe("Filter to specific relationship types")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Ft("atoms_trace",async e=>{const{traceHandler:t}=await Promise.resolve().then(()=>(pt(),lt));return t(e)})}),Nt.registerTool("atoms_list_variables",{title:"List Project Variables",description:"List all parameterized variables defined in a project.\n\nVariables are shared values (e.g., backup_camera_latency = 2s) that can be\nreferenced in requirement bodies as {variable_name}.\n\nArgs:\n - project_id (string, UUID): Project to list variables for\n\nReturns:\n { variables: [{ id, name, value, unit, description }], total }",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_list_variables",async e=>{const{listVariablesHandler:t}=await Promise.resolve().then(()=>(bt(),ut));return t(e)})),Nt.registerTool("atoms_get_variable",{title:"Get Project Variable",description:'Get a specific variable by name, including which items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name (e.g., "backup_camera_latency")\n\nReturns:\n { variable, referenced_by: [{ id, title, type }], reference_count }',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),variable_name:s.z.string().min(1).describe("Variable name")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_get_variable",async e=>{const{getVariableHandler:t}=await Promise.resolve().then(()=>(bt(),ut));return t(e)})),Nt.registerTool("atoms_update_variable",{title:"Update Project Variable",description:"Update a variable's value, unit, or description.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - variable_name (string): Variable name\n - value (string, optional): New value\n - unit (string, optional): Unit abbreviation (e.g., 's', 'Hz')\n - description (string, optional): Human-readable description\n\nReturns:\n { variable }",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),variable_name:s.z.string().min(1).describe("Variable name"),value:s.z.string().optional().describe("New value"),unit:s.z.string().optional().describe("Unit abbreviation"),description:s.z.string().optional().describe("Description")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_update_variable",async e=>{const{updateVariableHandler:t}=await Promise.resolve().then(()=>(bt(),ut));return t(e)})),Nt.registerTool("atoms_create_variable",{title:"Create Project Variable",description:'Create one or many parameterized variables for a project.\n\nSingle form: provide name + value.\nArray form: provide variables[] for bulk creation (one atomic INSERT).\n\nVariables can then be embedded in requirement bodies as {variable_name}.\n\nArgs (single form):\n - project_id (string, UUID): Project to add the variable to\n - name (string): Variable name — letters, digits, underscores; must start with letter/underscore\n - value (string): Initial value (e.g., "100", "true", "nominal")\n - unit (string, optional): Unit abbreviation (e.g., "Hz", "ms", "m/s²")\n - description (string, optional): Human-readable description\n - echo (bool, optional): false → lean {name} response (default true)\n\nArgs (array form):\n - project_id (string, UUID): Project UUID\n - variables[]: Array of { name, value, unit?, description? }\n - echo (bool, optional): false → lean {name} list (default true)\n - idempotency_key (string, optional): Dedup key\n\nReturns (single): { variable, message }\nReturns (array): { batch_id, created, variables, message }',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),name:s.z.string().min(1).max(64).optional().describe("Variable name (single form)"),value:s.z.string().min(1).optional().describe("Initial value (single form)"),unit:s.z.string().optional().describe("Unit abbreviation"),description:s.z.string().optional().describe("Description"),echo:s.z.boolean().optional().describe("false → lean response (default true)"),variables:s.z.array(s.z.object({name:s.z.string().min(1).max(64).describe("Variable name"),value:s.z.string().min(1).describe("Initial value"),unit:s.z.string().optional().describe("Unit abbreviation"),description:s.z.string().optional().describe("Description")})).optional().describe("Array form: batch variable creation. Atomic — all or none."),idempotency_key:s.z.string().max(128).optional().describe("Dedup key for retries")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Ft("atoms_create_variable",async e=>{const{createVariableHandler:t}=await Promise.resolve().then(()=>(bt(),ut));return t(e)})),Nt.registerTool("atoms_delete_variable",{title:"Delete Project Variable",description:"Delete a project variable. Refuses by default if any items reference it.\n\nArgs:\n - project_id (string, UUID): Project containing the variable\n - name (string): Variable name to delete\n - force (bool, optional): Delete even if items still reference it (default false)\n\nReturns:\n { deleted, name, referenced_by_items, warning? }",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),name:s.z.string().min(1).describe("Variable name to delete"),force:s.z.boolean().optional().describe("Delete even if items reference it (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Ft("atoms_delete_variable",async e=>{const{deleteVariableHandler:t}=await Promise.resolve().then(()=>(bt(),ut));return t(e)})),Nt.registerTool("atoms_list_domains",{title:"List Project Domains",description:"List all domain tags registered in a project's taxonomy, with item counts.\n\nArgs:\n - project_id (string, UUID): Project to inspect\n\nReturns:\n { domains: [{ name, item_count }], total }",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_list_domains",async e=>{const{listDomainsHandler:t}=await Promise.resolve().then(()=>(kt(),wt));return t(e)})),Nt.registerTool("atoms_create_domain",{title:"Create Project Domain",description:'Register a new domain tag in the project taxonomy.\n\nOnce created, items can be tagged with this domain via atoms_create_item or atoms_update_item.\n\nArgs:\n - project_id (string, UUID): Project to add the domain to\n - name (string): Domain name (lowercased automatically, e.g., "safety", "can-bus")\n\nReturns:\n { domain: { name }, message }',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),name:s.z.string().min(1).max(64).describe("Domain name")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Ft("atoms_create_domain",async e=>{const{createDomainHandler:t}=await Promise.resolve().then(()=>(kt(),wt));return t(e)})),Nt.registerTool("atoms_update_domain",{title:"Rename Project Domain",description:"Rename a domain tag. Updates the taxonomy and propagates to all tagged items.\n\nUse dry_run=true first to see how many items will be affected before committing.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Current domain name\n - new_name (string): New domain name\n - dry_run (bool, optional): If true, return impact count without making changes (default false)\n\nReturns (dry_run=false):\n { domain: { name }, renamed_from, items_updated, message }\n\nReturns (dry_run=true):\n { dry_run: true, rename: { from, to }, items_affected, message }",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),name:s.z.string().min(1).describe("Current domain name"),new_name:s.z.string().min(1).describe("New domain name"),dry_run:s.z.boolean().optional().describe("Preview impact without applying (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1}},Ft("atoms_update_domain",async e=>{const{updateDomainHandler:t}=await Promise.resolve().then(()=>(kt(),wt));return t(e)})),Nt.registerTool("atoms_delete_domain",{title:"Delete Project Domain",description:"Delete a domain tag from the project taxonomy.\n\nRefuses by default if any items are tagged with it. With force=true, deletes the\ndomain and strips the tag from all items.\n\nArgs:\n - project_id (string, UUID): Project containing the domain\n - name (string): Domain name to delete\n - force (bool, optional): Strip from items and delete anyway (default false)\n\nReturns:\n { deleted, name, items_updated, message }",inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),name:s.z.string().min(1).describe("Domain name to delete"),force:s.z.boolean().optional().describe("Strip from all items and delete (default false)")},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},Ft("atoms_delete_domain",async e=>{const{deleteDomainHandler:t}=await Promise.resolve().then(()=>(kt(),wt));return t(e)})),me(Nt,{appName:"summary",htmlFile:"summary-app.html",toolName:"atoms_project_summary",title:"Project Compliance Summary",description:'One-call project health and compliance dashboard.\n\nReturns item counts by type, test execution status, requirement coverage\n(overall and by domain), and recent change activity.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive dashboard with charts.\nFalls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): Project to summarize\n\nReturns:\n { project_name, counts, test_status, coverage, coverage_by_domain, recent_changes, last_updated }\n\nExamples:\n - "Give me a compliance snapshot" → atoms_project_summary(project_id)\n - "How\'s our test coverage?" → atoms_project_summary(project_id)',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Ft("atoms_project_summary",async e=>{const{projectSummaryHandler:t}=await Promise.resolve().then(()=>(Ut(),Ht));return t(e)})}),me(Nt,{appName:"browse",htmlFile:"browse-app.html",toolName:"atoms_browse",title:"Browse ATOMS Items",description:'View and filter items in an ATOMS project with a visual browser.\n\nIn MCP App hosts (Claude, ChatGPT), renders an interactive filterable list\nwith expandable item details. Falls back to JSON for non-UI clients.\n\nArgs:\n - project_id (string, UUID): The project to browse\n - type (string, optional): Filter by type (requirement, test-case, note, table)\n - domain (string, optional): Filter by domain tag\n - level (string, optional): Filter by level (System, Subsystem, Component)\n - query (string, optional): Full-text search query\n - limit (number, optional): Max results (default 25, max 100)\n - offset (number, optional): Pagination offset (default 0)\n\nReturns:\n { items: [...], filters: { domains, levels, types }, meta: { total_count, limit, offset, has_more } }\n\nExamples:\n - "Show me the requirements" → atoms_browse(project_id, type="requirement")\n - "Browse safety items" → atoms_browse(project_id, domain="Safety")\n - "Find braking requirements" → atoms_browse(project_id, query="braking")',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),type:s.z.enum(["requirement","test-case","note","table"]).optional().describe("Filter by item type"),domain:s.z.string().optional().describe("Filter by domain tag"),level:s.z.string().optional().describe("Filter by level (System, Subsystem, Component)"),query:s.z.string().max(1e3).optional().describe("Full-text search query"),limit:s.z.number().int().min(1).max(100).default(25).describe("Max results (default 25, max 100)"),offset:s.z.number().int().min(0).default(0).describe("Pagination offset (default 0)")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},handler:Ft("atoms_browse",async e=>{const{browseHandler:t}=await Promise.resolve().then(()=>(At(),Dt));return t(e)})}),Nt.registerTool("atoms_impact_analysis",{title:"Analyze Impact of Changing an Item",description:'Analyze the blast radius of changing a specific item.\n\nTraverses the relationship graph from the given item and returns every item that\nwould be affected by a change — with their types, depths, and full relationship paths.\n\nArgs:\n - project_id (string, UUID): Project containing the item\n - item_id (string): Item to analyze (e.g., "REQ-001")\n - direction (string, optional): "downstream" (default) | "upstream" | "both"\n - downstream: what this item affects (children, verified_by)\n - upstream: what affects this item (parents, verifies)\n - both: full bidirectional traversal\n - depth (integer, optional): Max traversal depth. Omit for full depth (all reachable nodes).\n - include_variable_refs (boolean, optional): Reserved for future variable-aware impact. Default true.\n\nReturns:\n { root: { item_id, title, type }, impacted_items: [{ item_id, title, type, depth, relationship_path }], summary: { total_impacted, by_type, max_depth_reached } }\n\nExamples:\n - "What breaks if I change REQ-001?" → atoms_impact_analysis(project_id, "REQ-001")\n - "What\'s upstream of TC-005?" → atoms_impact_analysis(project_id, "TC-005", direction="upstream")\n - "Show direct dependencies only" → atoms_impact_analysis(project_id, "REQ-001", depth=1)\n\nErrors:\n - "Item not found" → verify item_id exists in the project',inputSchema:{project_id:s.z.string().uuid().describe("UUID of the project"),item_id:s.z.string().min(1).max(20).describe("Item ID to analyze (e.g., REQ-001)"),direction:s.z.enum(["downstream","upstream","both"]).default("downstream").describe("Traversal direction (default: downstream)"),depth:s.z.number().int().min(1).optional().describe("Max traversal depth. Omit for full depth."),include_variable_refs:s.z.boolean().default(!0).describe("Reserved for variable-aware impact (future). Default true.")},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},Ft("atoms_impact_analysis",async e=>{const{impactAnalysisHandler:t}=await Promise.resolve().then(()=>(Lt(),$t));return t(e)}))}}),Yt={};async function Kt(){const e=d.randomBytes(32).toString("base64url"),t=d.createHash("sha256").update(e).digest("base64url"),n=`http://localhost:${Bt}${Gt}`,r=new a.URL(`${C}/auth/mcp-consent`);return r.searchParams.set("redirect_uri",n),r.searchParams.set("code_challenge",t),r.searchParams.set("code_challenge_method","S256"),new Promise((t,n)=>{let i;function o(){clearTimeout(i)}const s=c.createServer(async(r,i)=>{const d=new a.URL(r.url??"/",`http://localhost:${Bt}`);if(d.pathname!==Gt)return i.writeHead(404),void i.end("Not found");try{if("access_denied"===d.searchParams.get("error"))return i.writeHead(200,{"Content-Type":"text/html"}),i.end(Xt("Authorization was cancelled.")),o(),s.close(),void n(new Error("Authorization cancelled by user."));const r=d.searchParams.get("code");if(r){const a=await fetch(`${q}/auth/v1/token?grant_type=pkce`,{method:"POST",headers:{"Content-Type":"application/json",apikey:O},body:JSON.stringify({auth_code:r,code_verifier:e})}),d=await a.json();if(!a.ok||!d.access_token){const e=d.error_description??d.msg??"Unknown error";return i.writeHead(200,{"Content-Type":"text/html"}),i.end(Xt(`Code exchange failed: ${e}`)),o(),s.close(),void n(new Error(`Code exchange failed: ${e}`))}let c="authenticated";try{c=JSON.parse(Buffer.from(d.access_token.split(".")[1],"base64").toString()).email??c}catch{}const{createClient:l}=await import("@supabase/supabase-js"),m=l(q,O,{global:{headers:{Authorization:`Bearer ${d.access_token}`}}}),{data:p,error:u}=await m.from("org_members").select("org_id").limit(1);return u||!p||0===p.length?(i.writeHead(200,{"Content-Type":"text/html"}),i.end(Xt('No ATOMS account found for this Google account.<br><br>Please sign up at <a href="https://x.atoms.tech">x.atoms.tech</a> first, then run this login command again.')),o(),s.close(),void n(new Error("No ATOMS account found. Sign up at x.atoms.tech first."))):(await H({access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Date.now()+1e3*(d.expires_in??3600),user_email:c}),i.writeHead(200,{"Content-Type":"text/html"}),i.end(Zt(c)),o(),s.close(),void t({email:c}))}const a=d.searchParams.get("access_token"),c=d.searchParams.get("refresh_token"),l=parseInt(d.searchParams.get("expires_in")??"3600",10);a&&c?(await H({access_token:a,refresh_token:c,expires_at:Date.now()+1e3*l}),i.writeHead(200,{"Content-Type":"text/html"}),i.end(Zt("authenticated")),o(),s.close(),t({email:"authenticated"})):(i.writeHead(200,{"Content-Type":"text/html"}),i.end("<!DOCTYPE html>\n<html>\n<head><title>ATOMS MCP Login</title></head>\n<body>\n <h1>Completing login...</h1>\n <script>\n const hash = window.location.hash.substring(1);\n const params = new URLSearchParams(hash);\n const data = {\n access_token: params.get('access_token'),\n refresh_token: params.get('refresh_token'),\n expires_in: params.get('expires_in'),\n user_email: ''\n };\n if (data.access_token) {\n // Decode JWT to get email\n try {\n const payload = JSON.parse(atob(data.access_token.split('.')[1]));\n data.user_email = payload.email || '';\n } catch(e) {}\n fetch('/token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(data)\n }).then(() => {\n document.body.innerHTML = '<h1>Login successful! You can close this tab.</h1>';\n }).catch(() => {\n document.body.innerHTML = '<h1>Login failed. Please try again.</h1>';\n });\n } else {\n document.body.innerHTML = '<h1>Login failed — no tokens received.</h1>';\n }\n <\/script>\n</body>\n</html>"))}catch(e){i.writeHead(500),i.end("Authentication failed"),o(),s.close(),n(e)}});s.on("request",async(e,r)=>{if("POST"===e.method&&"/token"===e.url){let i="";e.on("data",e=>{i+=e.toString()}),e.on("end",async()=>{try{const e=JSON.parse(i);await H({access_token:e.access_token,refresh_token:e.refresh_token,expires_at:Date.now()+1e3*(e.expires_in??3600),user_email:e.user_email}),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0})),o(),s.close(),t({email:e.user_email??"authenticated"})}catch(e){r.writeHead(500),r.end("Failed to store credentials"),o(),s.close(),n(e)}})}}),s.listen(Bt,"127.0.0.1",async()=>{process.stderr.write("\nOpening browser for ATOMS login...\n"),process.stderr.write(`If the browser doesn't open, visit:\n${r.toString()}\n\n`);try{const{default:e}=await import("open");await e(r.toString())}catch{process.stderr.write("Could not open browser automatically. Please open the URL above.\n")}}),i=setTimeout(()=>{s.close(),n(new Error("Login timed out after 60 seconds. Run 'npx @atoms-tech/atoms-mcp login' to try again."))},6e4)})}function Zt(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Authorized</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #052e16;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 {\n font-size: 22px;\n font-weight: 600;\n margin-bottom: 8px;\n color: #22c55e;\n }\n .email {\n font-size: 14px;\n color: #a3a3a3;\n margin-bottom: 32px;\n }\n .permissions {\n text-align: left;\n background: #0a0a0a;\n border: 1px solid #262626;\n border-radius: 12px;\n padding: 20px;\n margin-bottom: 24px;\n }\n .permissions h3 {\n font-size: 12px;\n font-weight: 600;\n color: #737373;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n margin-bottom: 12px;\n }\n .perm-item {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 6px 0;\n font-size: 14px;\n color: #d4d4d4;\n }\n .perm-item .dot {\n width: 6px;\n height: 6px;\n background: #22c55e;\n border-radius: 50%;\n flex-shrink: 0;\n }\n .closing {\n font-size: 13px;\n color: #525252;\n }\n .closing span { color: #a3a3a3; font-variant-numeric: tabular-nums; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#22c55e" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1>Authorization Granted</h1>\n <p class="email">${e}</p>\n\n <div class="permissions">\n <h3>ATOMS MCP can now</h3>\n <div class="perm-item"><span class="dot"></span> Read your projects and requirements</div>\n <div class="perm-item"><span class="dot"></span> Create and edit requirements and test cases</div>\n <div class="perm-item"><span class="dot"></span> Record test results (pass/fail)</div>\n <div class="perm-item"><span class="dot"></span> Manage traceability relationships</div>\n <div class="perm-item"><span class="dot"></span> Export coverage reports and diagrams</div>\n </div>\n\n <p class="closing">This tab will close in <span id="countdown">5</span>s</p>\n </div>\n\n <script>\n let seconds = 5;\n const el = document.getElementById('countdown');\n const timer = setInterval(() => {\n seconds--;\n el.textContent = seconds;\n if (seconds <= 0) {\n clearInterval(timer);\n window.close();\n // If window.close() is blocked (not opened by script), update message\n setTimeout(() => {\n document.querySelector('.closing').textContent = 'You can close this tab now.';\n }, 500);\n }\n }, 1000);\n <\/script>\n</body>\n</html>`}function Xt(e){return`<!DOCTYPE html>\n<html>\n<head>\n <title>ATOMS MCP — Failed</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n background: #0a0a0a;\n color: #fafafa;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n }\n .card {\n background: #171717;\n border: 1px solid #262626;\n border-radius: 16px;\n padding: 48px;\n max-width: 480px;\n width: 100%;\n text-align: center;\n }\n .icon {\n width: 56px;\n height: 56px;\n background: #450a0a;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 28px; height: 28px; }\n h1 { font-size: 22px; font-weight: 600; margin-bottom: 16px; color: #ef4444; }\n .reason { font-size: 14px; color: #a3a3a3; line-height: 1.6; }\n .reason a { color: #7c3aed; text-decoration: underline; }\n </style>\n</head>\n<body>\n <div class="card">\n <div class="icon">\n <svg fill="none" viewBox="0 0 24 24" stroke="#ef4444" stroke-width="2.5">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1>Authorization Failed</h1>\n <p class="reason">${e}</p>\n </div>\n</body>\n</html>`}S(Yt,{login:()=>Kt});var en=j({"src/auth/login.ts"(){R(),P(),Bt=19275,Gt="/callback"}});Qt();var tn=process.argv.slice(2)[0];(async function(){switch(tn){case"login":{const{login:e}=await Promise.resolve().then(()=>(en(),Yt));try{const{email:t}=await e();process.stderr.write(`\n ✓ Authenticated as ${t}\n`),process.stderr.write(" ✓ Credentials saved to ~/.atoms/credentials.json\n\n"),process.stderr.write(" Next steps:\n"),process.stderr.write(" $ claude mcp add atoms -- npx -y @atoms-tech/atoms-mcp\n"),process.stderr.write("\n Or add to Claude Desktop (Settings → MCP → Edit Config):\n"),process.stderr.write(' {\n "mcpServers": {\n "atoms": {\n "command": "npx",\n "args": ["-y", "@atoms-tech/atoms-mcp"]\n }\n }\n }\n\n')}catch(e){process.stderr.write(`\n ✗ ${e instanceof Error?e.message:String(e)}\n\n`),process.exit(1)}break}case"whoami":{const{getValidToken:e}=await Promise.resolve().then(()=>(F(),A));try{const{email:t,user_id:n}=await e();process.stderr.write(`\n ✓ Logged in as ${t}\n User ID: ${n}\n\n`)}catch(e){process.stderr.write("\n ✗ Not authenticated.\n Run: npx @atoms-tech/atoms-mcp login\n\n"),process.exit(1)}break}case"logout":{const{clearCredentials:e}=await Promise.resolve().then(()=>(R(),E));await e(),process.stderr.write("Logged out. Credentials removed.\n"),process.stderr.write("Run 'npx @atoms-tech/atoms-mcp login' to authenticate again.\n");break}case"--version":case"-v":process.stderr.write("@atoms-tech/atoms-mcp v0.4.0\n");break;case"--help":case"-h":process.stderr.write("ATOMS MCP Server — AI agent integration for requirements management\n\nUsage:\n npx @atoms-tech/atoms-mcp Start MCP server (stdio)\n npx @atoms-tech/atoms-mcp login Authenticate with ATOMS.tech\n npx @atoms-tech/atoms-mcp logout Switch account / clear credentials\n npx @atoms-tech/atoms-mcp whoami Show current user\n npx @atoms-tech/atoms-mcp --version Show version\n");break;default:{process.stderr.write("[atoms-mcp] Starting MCP server via stdio...\n");try{const{getValidToken:e}=await Promise.resolve().then(()=>(F(),A)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch{process.stderr.write("[atoms-mcp] No credentials found. Starting login flow...\n");try{const{login:e}=await Promise.resolve().then(()=>(en(),Yt)),{email:t}=await e();process.stderr.write(`[atoms-mcp] Authenticated as ${t}\n`)}catch(e){process.stderr.write(`[atoms-mcp] Login failed: ${e instanceof Error?e.message:String(e)}\n[atoms-mcp] Starting server without auth. Tools will fail until you run: npx @atoms-tech/atoms-mcp login\n`)}}const e=new l.StdioServerTransport;await Nt.connect(e),process.stderr.write("[atoms-mcp] MCP server running. Waiting for tool calls...\n")}}})().catch(e=>{process.stderr.write(`[atoms-mcp] Fatal: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)});