@likec4/mcp 1.59.3 → 1.59.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/app/render-view-client.css +1 -1
- package/dist/app/render-view-client.js +99 -105
- package/dist/chunks/src.mjs +44 -28
- package/package.json +15 -15
package/dist/chunks/src.mjs
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
-
import{configureLanguageServerLogger as e}from"@likec4/language-server";import{fromSources as t,fromWorkspace as n}from"@likec4/language-services/node";import{defu as r}from"defu";import{relative as i,resolve as a,sep as s}from"node:path";import{isDevelopment as c}from"std-env";import l from"tinyrainbow";import{createContext as u}from"unctx";import{StdioServerTransport as f}from"@modelcontextprotocol/sdk/server/stdio.js";import{hasProp as
|
|
2
|
-
`)}}]})),e}function projectResource(e){let t=useLanguageServices();return e.registerResource(`likec4-project`,new
|
|
1
|
+
import{configureLanguageServerLogger as e}from"@likec4/language-server";import{fromSources as t,fromWorkspace as n}from"@likec4/language-services/node";import{defu as r}from"defu";import{relative as i,resolve as a,sep as s}from"node:path";import{isDevelopment as c}from"std-env";import l from"tinyrainbow";import{createContext as u}from"unctx";import{StdioServerTransport as f}from"@modelcontextprotocol/sdk/server/stdio.js";import*as p from"zod/v4";import{z as m}from"zod/v4";import{FqnRef as h,GlobalFqn as g,hasProp as _,invariant as v}from"@likec4/core";import{loggable as y,logger as b}from"@likec4/log";import{isEmptyish as x,keys as S,pipe as C,piped as w,prop as T}from"remeda";import{McpServer as E,ResourceTemplate as D}from"@modelcontextprotocol/sdk/server/mcp.js";import{completable as O}from"@modelcontextprotocol/sdk/server/completable.js";import*as k from"zod/v3";import{RESOURCE_MIME_TYPE as A,registerAppResource as j,registerAppTool as M}from"@modelcontextprotocol/ext-apps/server";import{existsSync as N,readFileSync as P}from"node:fs";import{fileURLToPath as ee}from"node:url";import{MaxZoom as te,MinZoom as ne}from"@likec4/diagram";import{URI as F}from"vscode-uri";import{enhanceLayoutWithAI as I}from"@likec4/layouts/ai";import{isDeploymentNodeModel as L,modelConnection as re}from"@likec4/core/model";import{ifilter as R,invariant as z,isSameHierarchy as ie}from"@likec4/core/utils";import{ProjectId as ae}from"@likec4/core/types";import{randomUUID as oe}from"node:crypto";import{MemoryEventStore as se,StreamableHTTPTransport as ce}from"@hono/mcp";import{serve as le}from"@hono/node-server";import{Hono as ue}from"hono";import{cors as de}from"hono/cors";var B=Object.defineProperty,__name=(e,t)=>B(e,`name`,{value:t,configurable:!0});const V=u(),H=u();function useLanguageServices(){return H.use()}function setMcpServerCtx(e){return e?V.set(e,!0):V.unset(),e}function setLanguageServicesCtx(e){return e?H.set(e,!0):H.unset(),e}const U=b.getChild(`mcp`);function mcpToolSchema(e){return m.object(e).meta({$schema:`https://json-schema.org/draft/2020-12/schema`})}function likec4Tool(e){return t=>n=>{let{name:r,description:i,inputSchema:a,outputSchema:s,...c}=e,l=s!==void 0&&!x(s),u={description:i?.trim()??``,...c,...a===void 0?{}:{inputSchema:mcpToolSchema(a)},...s===void 0?{}:{outputSchema:mcpToolSchema(s)}};return n.registerTool(r,u,async(...e)=>{let n=useLanguageServices();U.debug(`Calling tool {name}, args: {args}`,{name:r,args:e});try{let r=await t.apply(null,[n,...e]);return typeof r==`string`?{content:[{type:`text`,text:r}]}:l?{content:[],structuredContent:r}:_(r,`content`)?r:{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return U.error(`Tool ${r} failed`,{err:e}),{content:[{type:`text`,text:y(e)}],isError:!0}}}),n}}var fe=`1.59.4`;function applySemanticLayoutPrompt(e){let t=useLanguageServices();return e.registerPrompt(`apply_semantic_layout`,{title:`Prepare prompt for applying semantic layout to a likec4 view`,argsSchema:{projectId:O(k.string().describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(T(`id`))),viewId:O(k.string().describe(`View ID`),async(n=``,r)=>{let i=r?.arguments?.projectId??t.projectsManager.default.id,a=await t.computedModel(i);return a?Array.from(a.views()).filter(e=>e.id.startsWith(n)).map(T(`id`)):(await e.sendLoggingMessage({level:`warning`,data:`Completing viewId for project ${i} with input value "${n}", model not found`}),[])})}},async({viewId:e,projectId:t},n)=>({messages:[{role:`user`,content:{type:`text`,text:["Call `apply-semantic-layout` tool from `likec4` MCP with these arguments:","projectId: `"+t+"`","viewId: `"+e+"`"].join(`
|
|
2
|
+
`)}}]})),e}function projectResource(e){let t=useLanguageServices();return e.registerResource(`likec4-project`,new D(`likec4://project/{projectId}`,{list:async()=>({resources:t.projects().map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,name:e.title}))}),complete:{projectId:e=>{if(!e)return t.projects().map(T(`id`));let n=e.toLowerCase();return t.projects().filter(e=>e.id.toLowerCase().includes(n)).map(T(`id`))}}}),{description:`LikeC4 project resource`,mimeType:`application/json`},async(e,{projectId:n})=>{if(!n)return{contents:[]};let r=typeof n==`string`?[n]:n;return{contents:t.projects().filter(e=>r.includes(e.id)).map(e=>({uri:`likec4://project/${encodeURIComponent(e.id)}`,text:JSON.stringify({id:e.id,title:e.title,folder:e.folder.fsPath})}))}}),e}function readDistAsset(e){let t=[new URL(`../dist/${e}`,import.meta.url),new URL(`../../dist/${e}`,import.meta.url)];for(let e of t){let t=ee(e);if(N(t))return P(t,`utf-8`)}throw Error(`Could not locate dist asset '${e}'; tried: ${t.map(String).join(`, `)}`)}function readRenderViewClientBundle(){return readDistAsset(`app/render-view-client.js`)}function readRenderViewClientStyles(){return readDistAsset(`app/render-view-client.css`)}const pe=p.object({name:p.string().describe(`Project identifier`),title:p.string().optional().describe(`Human-readable project title`),contactPerson:p.string().optional().describe(`Maintainer contact information`),metadata:p.record(p.string(),p.unknown()).optional().describe(`Custom project metadata as key-value pairs`),extends:p.union([p.string(),p.array(p.string())]).optional().describe(`Style inheritance paths`),exclude:p.array(p.string()).optional().describe(`File exclusion patterns`),include:p.object({paths:p.array(p.string()).describe(`Include paths`),maxDepth:p.number().describe(`Maximum directory depth`),fileThreshold:p.number().describe(`File threshold`)}).optional().describe(`Include configuration`),manualLayouts:p.object({outDir:p.string().describe(`Output directory for manual layouts`)}).optional().describe(`Manual layouts configuration`),styles:p.object({hasTheme:p.boolean().describe(`Whether theme customization is defined`),hasDefaults:p.boolean().describe(`Whether default style values are defined`),hasCustomCss:p.boolean().describe(`Whether custom CSS is defined`)}).optional().describe(`Simplified styles configuration (boolean flags)`)});function serializeConfig(e){let t={name:e.name};return e.title!=null&&(t.title=e.title),e.contactPerson!=null&&(t.contactPerson=e.contactPerson),e.metadata&&(t.metadata=e.metadata),e.extends&&(t.extends=e.extends),e.exclude&&(t.exclude=e.exclude),e.include&&(t.include={paths:e.include.paths||[],maxDepth:e.include.maxDepth??3,fileThreshold:e.include.fileThreshold??30}),e.manualLayouts&&(t.manualLayouts={outDir:e.manualLayouts.outDir??`.likec4`}),e.styles&&(t.styles={hasTheme:!!e.styles.theme,hasDefaults:!!e.styles.defaults,hasCustomCss:!!e.styles.customCss}),t}const W=p.object({id:p.string().describe(`Element id (FQN)`),name:p.string().describe(`Element name`),kind:p.string().describe(`Element kind`),title:p.string(),tags:p.array(p.string()),metadata:p.record(p.string(),p.union([p.string(),p.array(p.string())])),includedInViews:p.array(p.object({id:p.string().describe(`View id`),title:p.string().describe(`View title`),type:p.enum([`element`,`deployment`,`dynamic`]).describe(`View type`)})).describe(`Views that include this element`)});function serializeElement(e){return{id:e.id,name:e.name,kind:e.kind,title:e.title,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())}}function traverseGraph(e,t,n,r,i,a){let s=e.findElement(t);v(s,`Element "${t}" not found`);let c=new Set,l={},u=0,f=!1,p=[{elementId:t,depth:0}];for(;p.length>0;){let{elementId:t,depth:s}=p.shift();if(s>i||c.has(t))continue;if(c.size>=a){f=!0;break}let m=e.findElement(t);if(!m)continue;c.add(t),u=Math.max(u,s);let h=(n===`incoming`?[...m.incoming(r)]:[...m.outgoing(r)]).map(e=>{let t={elementId:n===`incoming`?e.source.id:e.target.id};return e.title&&(t.relationshipLabel=e.title),e.technology&&(t.technology=e.technology),t});l[t]={...serializeElement(m),neighbors:h,depth:s};for(let e of h)c.has(e.elementId)||p.push({elementId:e.elementId,depth:s+1})}for(let e of Object.values(l))e.neighbors=e.neighbors.filter(e=>e.elementId in l);return{target:t,totalNodes:c.size,maxDepth:u,truncated:f,nodes:l}}const G=p.object({path:p.string().describe(`Path to the file`),range:p.object({start:p.object({line:p.number(),character:p.number()}),end:p.object({line:p.number(),character:p.number()})}).describe(`Range in the file`)}).nullable(),K=p.array(p.object({title:p.string().nullable().describe(`Optional link title`),url:p.string().describe(`Link URL`),relative:p.string().nullable().describe(`Relative path (if URL is relative to workspace root)`)})).describe(`External links associated with this element`);function serializeLinks(e){return(e.links??[]).map(e=>({title:e.title??null,url:e.url,relative:e.relative??null}))}const q=p.string().refine(e=>!0).default(`default`).describe(`Project id (optional, will use "default" if not specified)`),J=p.array(p.object({id:p.string().describe(`View id`),title:p.string().describe(`View title`),type:p.enum([`element`,`deployment`,`dynamic`]).describe(`View type`)})),includedInViews=e=>[...e].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type})),mkLocate=(e,t)=>n=>{try{let r=e.locate({projectId:t,...n});return r?{path:F.parse(r.uri).fsPath,range:r.range}:null}catch(e){return U.debug(`Failed to locate {params}`,{error:e,params:n}),null}};function toolError(e){return{isError:!0,content:[{type:`text`,text:e}]}}function pickRecord(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}function buildViewScopedModel(e,t){let n=new Set,r=new Set,i=new Set,a=new Set,includeElement=t=>{let r=e.element(t);n.add(r.id);for(let e of r.ancestors())n.add(e.id)},includeDeployment=t=>{let n=e.deployment.element(t);r.add(n.id);for(let e of n.ancestors())r.add(e.id);n.isInstance()&&includeElement(n.element.id)},includeDeploymentRef=e=>{includeDeployment(e.deployment),h.isInsideInstanceRef(e)&&includeElement(e.element)};t._type===`element`&&t.viewOf&&includeElement(t.viewOf);for(let e of t.nodes)e.modelRef&&includeElement(e.modelRef),e.deploymentRef&&includeDeployment(e.deploymentRef);for(let n of t.edges)for(let t of n.relations){let n=e.relationship(t);n.isModelRelation()?(i.add(n.id),includeElement(n.source.id),includeElement(n.target.id)):(a.add(n.id),includeDeploymentRef(n.$relationship.source),includeDeploymentRef(n.$relationship.target))}let s=e.$data,c=Object.fromEntries(Object.entries(s.imports).flatMap(([e,t])=>{let r=t.filter(t=>n.has(g(e,t.id)));return r.length>0?[[e,r]]:[]}));return{...s,elements:pickRecord(s.elements,n),imports:c,relations:pickRecord(s.relations,i),deployments:{elements:pickRecord(s.deployments.elements,r),relations:pickRecord(s.deployments.relations,a)},views:{[t.id]:t},manualLayouts:{}}}function inlineLocalSvgIcon(e){if(typeof e!=`string`||!e.startsWith(`file:`)||!e.toLowerCase().split(/[?#]/)[0]?.endsWith(`.svg`))return e;try{return`data:image/svg+xml,${encodeURIComponent(P(F.parse(e).fsPath,`utf8`))}`}catch{return null}}function inlineLocalSvgIcons(e){return Array.isArray(e)?e.map(inlineLocalSvgIcons):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,e===`icon`?inlineLocalSvgIcon(t):inlineLocalSvgIcons(t)])):e}function buildRenderPayload(e){let t=e.fullModel?{...e.model.$data,views:{...e.model.$data.views,[e.viewId]:e.layoutedView}}:buildViewScopedModel(e.model,e.layoutedView);return{id:e.viewId,title:e.title,project:e.projectId,view:inlineLocalSvgIcons(e.layoutedView),model:inlineLocalSvgIcons(t)}}const Y=`ui://likec4/render-view.html`,X=p.object({size:p.enum([`compact`,`standard`,`large`]).default(`standard`),fitView:p.boolean().default(!0),initialZoom:p.number().min(ne).max(te).optional()}).default({size:`standard`,fitView:!0});function renderViewTool(e){return M(e,`render-view`,{title:`Render View`,description:`Renders a LikeC4 view as an interactive diagram (pan/zoom/fit) inline in the chat.
|
|
3
3
|
|
|
4
4
|
Request:
|
|
5
5
|
- viewId: string — view id (name)
|
|
6
6
|
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
7
|
+
- fullModel: boolean (optional) — include the complete model instead of data scoped to this view. Defaults to false.
|
|
8
|
+
- render.size: "compact", "standard", or "large" (optional) — initial canvas size hint. Defaults to "standard".
|
|
9
|
+
- render.fitView: boolean (optional) — fit the diagram into the canvas initially. Defaults to true.
|
|
10
|
+
- render.initialZoom: number (optional) — initial zoom level. This overrides render.fitView.
|
|
7
11
|
|
|
8
|
-
Use this when the user wants to *see* a view. Use "read-view" instead when only the view's structure (nodes/edges) is needed.`,inputSchema:{viewId:
|
|
12
|
+
Use this when the user wants to *see* a view. Use "read-view" instead when only the view's structure (nodes/edges) is needed.`,inputSchema:mcpToolSchema({viewId:p.string().describe(`View id (name)`),project:q,fullModel:p.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`),render:X}),outputSchema:mcpToolSchema({id:p.string(),title:p.string(),project:p.string(),view:p.record(p.string(),p.unknown()).describe(`Layouted view (nodes, edges, bounds), consumed by the paired render-view UI`),model:p.record(p.string(),p.unknown()).describe(`Layouted model data (specification, elements, relations, deployments), scoped to this view by default; complete when fullModel is true. Consumed by the paired UI to build a LikeC4Model for LikeC4ModelProvider — LikeC4Diagram requires one in context.`),render:X}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Render view`},_meta:{ui:{resourceUri:Y}}},async e=>{let t=useLanguageServices(),n=t.projectsManager.ensureProjectId(e.project),r=await t.layoutedModel(n),i=r.findView(e.viewId);if(!i)return toolError(`View with ID '${e.viewId}' not found in project ${n}`);if(!i.isLayouted())return toolError(`View '${e.viewId}' has no layout`);let a=i.$layouted,s=i.title??i.id;return{content:[{type:`text`,text:`Rendered view "${s}"`}],structuredContent:{...buildRenderPayload({projectId:n,viewId:i.id,title:s,layoutedView:a,model:r,fullModel:e.fullModel}),render:e.render}}}),e}function renderHtml(e,t){return`<!doctype html>
|
|
9
13
|
<html>
|
|
10
14
|
<head>
|
|
11
15
|
<meta charset="utf-8" />
|
|
@@ -19,11 +23,11 @@ Use this when the user wants to *see* a view. Use "read-view" instead when only
|
|
|
19
23
|
<div id="root"></div>
|
|
20
24
|
<script>${e}<\/script>
|
|
21
25
|
</body>
|
|
22
|
-
</html>`}function renderViewResource(e){return
|
|
26
|
+
</html>`}function renderViewResource(e){return j(e,`Render View UI`,Y,{description:`Interactive diagram UI for the render-view MCP App tool.`},async()=>({contents:[{uri:Y,mimeType:A,text:renderHtml(readRenderViewClientBundle(),readRenderViewClientStyles())}]})),e}function applySemanticLayoutTool(e){let t=useLanguageServices();return e.registerTool(`apply-semantic-layout`,{description:`Apply semantic layout to the likec4 view`,inputSchema:mcpToolSchema({projectId:O(p.string().default(`default`).describe(`Project id (optional, will use "default" if not specified)`),(e=``)=>t.projects().filter(t=>t.id.startsWith(e)).map(T(`id`))),viewId:O(p.string().describe(`View ID to apply semantic layout to`),async(e,n)=>{let r=n?.arguments?.projectId??t.projectsManager.default.id,i=await t.computedModel(r);if(!i)return[];let a=e??``;return Array.from(i.views()).filter(e=>e.id.startsWith(a)).map(T(`id`))})}),outputSchema:mcpToolSchema({reasoning:p.string().describe(`Reasoning behind the layout changes`),snapshotUri:p.string().nullish().describe(`Where snapshot was saved (after applying layout)`)})},async(n,r)=>{let i=t.projectsManager.ensureProjectId(n.projectId);i!==n.projectId&&await e.sendLoggingMessage({level:`notice`,data:`Using project "${i}" instead of "${n.projectId}"`},r.sessionId);let a=await t.computedModel(i),s=a.findView(n.viewId);if(!s)return toolError(`View "${n.viewId}" not found in project "${i}"`);let c=await I(s.$view,{name:`MCP`,async sendRequest({systemPrompt:e,userPrompt:t,diagram:n}){let i=await r.sendRequest({method:`sampling/createMessage`,params:{maxTokens:2e4,includeContext:`none`,systemPrompt:e,messages:[{role:`user`,content:{type:`text`,text:t+`
|
|
23
27
|
|
|
24
|
-
`+n}}]}},
|
|
28
|
+
`+n}}]}},p.object({content:p.object({type:p.literal(`text`),text:p.string()})}));return i.content.type===`text`?i.content.text:JSON.stringify(i.content)}},r.signal);if(!c)return await e.sendLoggingMessage({level:`error`,data:`Failed to generate layout hints`},r.sessionId),toolError(`Failed to generate layout hints`);await e.sendLoggingMessage({level:`info`,data:`Applying semantic layout...`},r.sessionId);let l=await t.views.layouter.aiLayout({view:s.$view,styles:a.$styles},c),u=await t.editor.applyChange({change:{op:`save-view-snapshot`,layout:l.diagram},viewId:s.id,projectId:i});return await e.sendLoggingMessage({level:`info`,data:`Layout applied successfully`},r.sessionId),{content:[],structuredContent:{reasoning:c.reasoning,...!!u.location&&{snapshotUri:u.location.uri.toString()}}}}),e}const me=W.extend({description:p.string().nullable().describe(`Element description`),technology:p.string().nullable().describe(`Element technology`),shape:p.string().describe(`Rendered shape`),color:p.string().describe(`Rendered color`),children:p.array(p.string()).describe(`Direct child element ids`),incomingCount:p.number().describe(`Number of incoming relationships`),outgoingCount:p.number().describe(`Number of outgoing relationships`),links:K,sourceLocation:G}),he=likec4Tool({name:`batch-read-elements`,description:`
|
|
25
29
|
Read details of multiple elements in a single call, reducing round-trips.
|
|
26
|
-
Returns a compact summary for each element including metadata, description, technology, shape, children, and
|
|
30
|
+
Returns a compact summary for each element including metadata, description, technology, shape, children, relationship counts, links and source location.
|
|
27
31
|
|
|
28
32
|
Request:
|
|
29
33
|
- ids: string[] — array of element ids (FQNs) to read (max 50)
|
|
@@ -45,6 +49,8 @@ Response (JSON object):
|
|
|
45
49
|
- incomingCount: number — number of incoming relationships
|
|
46
50
|
- outgoingCount: number — number of outgoing relationships
|
|
47
51
|
- includedInViews: View[] — views that include this element
|
|
52
|
+
- links: Array<{ title: string|null, url: string, relative: string|null }> — external links associated with this element
|
|
53
|
+
- sourceLocation: { path: string, range: { start: { line: number, character: number }, end: { line: number, character: number } } } | null — source location if available
|
|
48
54
|
- notFound: string[] — ids that were not found in the project
|
|
49
55
|
|
|
50
56
|
View (object) fields:
|
|
@@ -58,6 +64,8 @@ Notes:
|
|
|
58
64
|
- Maximum 50 element ids per call.
|
|
59
65
|
- Elements not found are listed in notFound array (not an error).
|
|
60
66
|
- More efficient than multiple read-element calls when you need summary data for many elements.
|
|
67
|
+
- Returns the same "links" and "sourceLocation" as read-element, so it fully replaces read-element for that case.
|
|
68
|
+
- Call read-element only when you also need relationships, deployedInstances, defaultView or project.
|
|
61
69
|
|
|
62
70
|
Example response:
|
|
63
71
|
{
|
|
@@ -78,12 +86,19 @@ Example response:
|
|
|
78
86
|
"outgoingCount": 3,
|
|
79
87
|
"includedInViews": [
|
|
80
88
|
{ "id": "system-overview", "title": "System Overview", "type": "element" }
|
|
81
|
-
]
|
|
89
|
+
],
|
|
90
|
+
"links": [
|
|
91
|
+
{ "title": "Documentation", "url": "https://docs.example.com/frontend", "relative": null }
|
|
92
|
+
],
|
|
93
|
+
"sourceLocation": {
|
|
94
|
+
"path": "/abs/path/project/model.c4",
|
|
95
|
+
"range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
|
|
96
|
+
}
|
|
82
97
|
}
|
|
83
98
|
],
|
|
84
99
|
"notFound": []
|
|
85
100
|
}
|
|
86
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Batch read elements`},inputSchema:{ids:
|
|
101
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Batch read elements`},inputSchema:{ids:p.array(p.string()).min(1).max(50).describe(`Array of element ids (FQNs) to read (max 50)`),project:q},outputSchema:{elements:p.array(me),notFound:p.array(p.string()).describe(`Element ids that were not found`)}})(async(e,t)=>{v(t.ids.length<=50,`Maximum 50 element ids per call`);let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=mkLocate(e,n),a=[],s=[];for(let e of t.ids){let t=r.findElement(e);if(!t){s.push(e);continue}a.push({...serializeElement(t),description:t.description.text,technology:t.technology,shape:t.shape,color:t.color,children:[...t.children()].map(e=>e.id),incomingCount:t.allIncoming.size,outgoingCount:t.allOutgoing.size,links:serializeLinks(t),sourceLocation:i({element:t.id})})}return{elements:a,notFound:s}}),Z=p.object({id:p.string(),kind:p.string(),title:p.string(),description:p.string().nullable(),technology:p.string().nullable(),shape:p.string(),color:p.string()}),ge=p.object({element1:Z,element2:Z,propertyDiffs:p.array(p.object({property:p.string().describe(`Property name`),element1Value:p.string().nullable().describe(`Value in element1`),element2Value:p.string().nullable().describe(`Value in element2`)})).describe(`Properties that differ between the two elements`),tags:p.object({onlyInElement1:p.array(p.string()).describe(`Tags present only in element1`),onlyInElement2:p.array(p.string()).describe(`Tags present only in element2`),common:p.array(p.string()).describe(`Tags present in both elements`)}),metadata:p.object({onlyInElement1:p.record(p.string(),p.union([p.string(),p.array(p.string())])).describe(`Metadata keys only in element1`),onlyInElement2:p.record(p.string(),p.union([p.string(),p.array(p.string())])).describe(`Metadata keys only in element2`),different:p.array(p.object({key:p.string(),element1Value:p.union([p.string(),p.array(p.string())]),element2Value:p.union([p.string(),p.array(p.string())])})).describe(`Metadata keys present in both but with different values`),common:p.record(p.string(),p.union([p.string(),p.array(p.string())])).describe(`Metadata keys with identical values in both`)}),relationships:p.object({incomingOnlyElement1:p.number().describe(`Count of unique source elements sending to element1 only`),incomingOnlyElement2:p.number().describe(`Count of unique source elements sending to element2 only`),incomingShared:p.number().describe(`Count of unique source elements sending to both`),outgoingOnlyElement1:p.number().describe(`Count of unique target elements receiving from element1 only`),outgoingOnlyElement2:p.number().describe(`Count of unique target elements receiving from element2 only`),outgoingShared:p.number().describe(`Count of unique target elements receiving from both`)})}),_e=likec4Tool({name:`element-diff`,description:`
|
|
87
102
|
Compare two elements side-by-side, showing differences in properties, tags, metadata, and relationships.
|
|
88
103
|
|
|
89
104
|
Request:
|
|
@@ -143,7 +158,7 @@ Example response:
|
|
|
143
158
|
"outgoingShared": 2
|
|
144
159
|
}
|
|
145
160
|
}
|
|
146
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Compare two elements`},inputSchema:{element1Id:
|
|
161
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Compare two elements`},inputSchema:{element1Id:p.string().describe(`First element id (FQN)`),element2Id:p.string().describe(`Second element id (FQN)`),project:q},outputSchema:ge.shape})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.element1Id);v(i,`Element "${t.element1Id}" not found in project "${n}"`);let a=r.findElement(t.element2Id);v(a,`Element "${t.element2Id}" not found in project "${n}"`);let s=[],c=[{name:`kind`,get:e=>e.kind},{name:`title`,get:e=>e.title},{name:`description`,get:e=>e.description.text},{name:`technology`,get:e=>e.technology},{name:`shape`,get:e=>e.shape},{name:`color`,get:e=>e.color}];for(let e of c){let t=e.get(i),n=e.get(a);t!==n&&s.push({property:e.name,element1Value:t,element2Value:n})}let l=new Set(i.tags),u=new Set(a.tags),f=[],p=[],m=[];for(let e of l)u.has(e)?f.push(e):p.push(e);for(let e of u)l.has(e)||m.push(e);let h=i.getMetadata(),g=a.getMetadata(),_=new Set([...Object.keys(h),...Object.keys(g)]),y={},b={},x=[],S={};for(let e of _){let t=h[e],n=g[e];t!==void 0&&n===void 0?y[e]=t:t===void 0&&n!==void 0?b[e]=n:t!==void 0&&n!==void 0&&(JSON.stringify(t)===JSON.stringify(n)?S[e]=t:x.push({key:e,element1Value:t,element2Value:n}))}let C=new Set([...i.incoming()].map(e=>e.source.id)),w=new Set([...a.incoming()].map(e=>e.source.id)),T=new Set([...i.outgoing()].map(e=>e.target.id)),E=new Set([...a.outgoing()].map(e=>e.target.id)),D=0,O=0,k=0;for(let e of C)w.has(e)?D++:O++;for(let e of w)C.has(e)||k++;let A=0,j=0,M=0;for(let e of T)E.has(e)?A++:j++;for(let e of E)T.has(e)||M++;return{element1:{id:i.id,kind:i.kind,title:i.title,description:i.description.text,technology:i.technology,shape:i.shape,color:i.color},element2:{id:a.id,kind:a.kind,title:a.title,description:a.description.text,technology:a.technology,shape:a.shape,color:a.color},propertyDiffs:s,tags:{onlyInElement1:p,onlyInElement2:m,common:f},metadata:{onlyInElement1:y,onlyInElement2:b,different:x,common:S},relationships:{incomingOnlyElement1:O,incomingOnlyElement2:k,incomingShared:D,outgoingOnlyElement1:j,outgoingOnlyElement2:M,outgoingShared:A}}}),ve=likec4Tool({name:`find-relationship-paths`,description:`
|
|
147
162
|
Discover all paths (chains of relationships) between two elements, supporting multi-hop traversal.
|
|
148
163
|
|
|
149
164
|
Request:
|
|
@@ -232,7 +247,7 @@ Example response:
|
|
|
232
247
|
}
|
|
233
248
|
]
|
|
234
249
|
}
|
|
235
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationship paths`},inputSchema:{sourceId:
|
|
250
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationship paths`},inputSchema:{sourceId:p.string().describe(`Source element FQN`),targetId:p.string().describe(`Target element FQN`),maxDepth:p.number().int().min(1).max(5).optional().default(3).describe(`Maximum path length (default: 3, max: 5)`),includeIndirect:p.boolean().optional().default(!1).describe(`Include indirect (implied) relationships through nested elements (default: false)`),project:q},outputSchema:{paths:p.array(p.object({length:p.number().describe(`Number of hops in the path`),steps:p.array(p.object({source:p.string().describe(`Source element FQN`),target:p.string().describe(`Target element FQN`),relationship:p.object({kind:p.string().nullable().describe(`Relationship kind`),title:p.string().nullable().describe(`Relationship title`),description:p.string().nullable().describe(`Relationship description`),technology:p.string().nullable().describe(`Relationship technology`),tags:p.array(p.string()).describe(`Relationship tags`)})})).describe(`Ordered sequence of relationships in the path`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.sourceId);v(i,`Source element "${t.sourceId}" not found in project "${n}"`);let a=r.findElement(t.targetId);v(a,`Target element "${t.targetId}" not found in project "${n}"`),v(i.id!==a.id,`Source and target must be different elements`);let s=t.maxDepth,c=t.includeIndirect?`all`:`direct`,l=[{elementId:i.id,path:[],visited:new Set([i.id])}],u=[];for(;l.length>0&&u.length<100;){let e=l.shift();if(e.path.length>=s)continue;let t=r.findElement(e.elementId);if(t)for(let n of t.outgoing(c)){let t=n.target.id;if(t===a.id){let t={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};if(u.push({length:e.path.length+1,steps:[...e.path,t]}),u.length>=100)break;continue}if(e.visited.has(t))continue;let r={source:n.source.id,target:n.target.id,relationship:{kind:n.kind,title:n.title,description:n.description.text,technology:n.technology,tags:[...n.tags]}};l.push({elementId:t,path:[...e.path,r],visited:new Set([...e.visited,t])})}}return u.sort((e,t)=>e.length-t.length),{paths:u}}),Q=p.object({id:p.string(),title:p.string(),kind:p.string()}),ye=p.object({type:p.enum([`direct`,`indirect`]).describe(`Type of relationship, "direct" for direct relationships, "indirect" for relationships through nested elements`),source:Q,target:Q,kind:p.string().nullable().describe(`Relationship kind`),title:p.string().nullable().describe(`Relationship title`),description:p.string().nullable().describe(`Relationship description`),technology:p.string().nullable().describe(`Relationship technology`),tags:p.array(p.string()).describe(`Relationship tags`),includedInViews:J.describe(`Views that include this relationship`),sourceLocation:G}),be=likec4Tool({name:`find-relationships`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Find relationships between two elements`},description:`
|
|
236
251
|
Find relationships between two LikeC4 elements within a project.
|
|
237
252
|
|
|
238
253
|
What it does:
|
|
@@ -303,7 +318,7 @@ Response:
|
|
|
303
318
|
}
|
|
304
319
|
]
|
|
305
320
|
}
|
|
306
|
-
`,inputSchema:{element1:
|
|
321
|
+
`,inputSchema:{element1:p.string().describe(`Element ID (FQN)`),element2:p.string().describe(`Element ID (FQN)`),project:q},outputSchema:{found:p.array(ye)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project);if(ie(t.element1,t.element2))throw Error(`No relationships possible between parent-child`);let r=[],i=await e.computedModel(n),a=i.findElement(t.element1);z(a,`Element "${t.element1}" not found in project "${n}"`);let s=i.findElement(t.element2);z(s,`Element "${t.element2}" not found in project "${n}"`);let c=mkLocate(e,n),l=re.findConnection(a,s,`both`).flatMap(e=>[...e.relations]);for(let e of l){let t=e.source===a&&e.target===s||e.source===s&&e.target===a;r.push({type:t?`direct`:`indirect`,source:{id:e.source.id,title:e.source.title,kind:e.source.kind},target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags],includedInViews:includedInViews(e.views()),sourceLocation:c({relation:e.id})})}return{found:r}}),xe=likec4Tool({name:`list-projects`,description:`
|
|
307
322
|
List LikeC4 projects discoverable in the current workspace.
|
|
308
323
|
|
|
309
324
|
Request:
|
|
@@ -336,12 +351,13 @@ Example response:
|
|
|
336
351
|
}
|
|
337
352
|
]
|
|
338
353
|
}
|
|
339
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List projects`},inputSchema:{},outputSchema:{projects:
|
|
340
|
-
`)}function previewViewTool(e){return
|
|
354
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`List projects`},inputSchema:{},outputSchema:{projects:p.array(p.object({id:p.string(),title:p.string(),folder:p.string(),sources:p.array(p.string())}))}})(async e=>({projects:e.projects().map(e=>({id:e.id,title:e.title,folder:e.folder.fsPath,sources:e.documents.map(e=>e.fsPath)}))}));function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}const Se=/^\s*view\s+([A-Za-z_][\w-]*)/;function extractViewId(e){let t=Se.exec(e);return t?t[1]:null}function wrapAsViewsBlock(e){return`views {\n${e}\n}\n`}function toPortablePath(e){return e.split(s).join(`/`)}function toVirtualSourcePath(e,t,n){let r=toPortablePath(i(e,t));return r===``||r.startsWith(`..`)?n:r}function formatDiagnostics(e){return e.map(e=>`- line ${e.range.start.line+1}, column ${e.range.start.character+1}: ${e.message}`).join(`
|
|
355
|
+
`)}function previewViewTool(e){return M(e,`preview-view`,{title:`Preview View`,description:`Renders a preview of a LikeC4 view defined by DSL text, in the context of an existing project's real elements — without saving anything to disk.
|
|
341
356
|
|
|
342
357
|
Request:
|
|
343
358
|
- dsl: string — a single \`view <id> ... { ... }\` definition. It must reference elements that already exist in the target project.
|
|
344
359
|
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
360
|
+
- fullModel: boolean (optional) — include the complete model instead of data scoped to this view. Defaults to false.
|
|
345
361
|
|
|
346
362
|
Behavior:
|
|
347
363
|
- The view id must be new (not already present in the project). If the view id matches an existing view, an error is returned — use a different id, or use "render-view" to render an existing view.
|
|
@@ -349,7 +365,7 @@ Behavior:
|
|
|
349
365
|
|
|
350
366
|
Note: preview styling may not exactly match the real project (custom theme/style extensions aren't applied to the preview). Only \`view <id> ...\` (element view) declarations are recognized for id-detection — a \`dynamic view <id> {...}\` or \`deployment view <id> {...}\` will fail with a generic "could not find a \`view <id>\`" error instead.
|
|
351
367
|
|
|
352
|
-
Use "preview-view" to iterate on a new view definition before creating it for real. Use "render-view" to render a view that's already saved.`,inputSchema:{dsl:
|
|
368
|
+
Use "preview-view" to iterate on a new view definition before creating it for real. Use "render-view" to render a view that's already saved.`,inputSchema:mcpToolSchema({dsl:p.string().describe("A single `view <id> ... { ... }` LikeC4 DSL definition"),project:q,fullModel:p.boolean().default(!1).describe(`Include the complete model instead of data scoped to this view`)}),outputSchema:mcpToolSchema({id:p.string(),title:p.string(),project:p.string(),view:p.record(p.string(),p.unknown()),model:p.record(p.string(),p.unknown())}),annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Preview view`},_meta:{ui:{resourceUri:Y}}},async e=>{try{var n=_usingCtx();let r=useLanguageServices(),i=r.projectsManager.ensureProjectId(e.project),a=extractViewId(e.dsl);if(!a)return toolError("Could not find a `view <id> ...` declaration at the start of `dsl`. Example: `view myView of someElement { include * }`");let s=r.project(i);if((await r.computedModel(i))?.findView(a))return toolError(`View "${a}" already exists in the project. Use a different view id for the preview, or use "render-view" to render the existing view.`);let c={};for(let[e,t]of s.documents.entries()){let n=toVirtualSourcePath(s.folder.fsPath,t.fsPath,`seed-${e}.c4`);c[n]=r.documentText(t.toString())??``}let l=`${oe()}.c4`;c[l]=wrapAsViewsBlock(e.dsl);let u=n.a(await t(c,{printErrors:!1,throwIfInvalid:!1})),f=u.getErrors();if(f.length>0)return toolError(`Failed to build preview:\n${formatDiagnostics(f)}`);let p=await u.computedModel(),m=p.findView(a);if(!m)return toolError(`View "${a}" was not found after building the preview.`);let h=u.projectsManager.ensureProjectId(ae(p.$data.projectId)),g=await u.viewsService.layoutView({viewId:m.id,projectId:h});if(!g)return toolError(`Failed to layout preview view "${a}".`);let _=m.title??m.id;return{content:[{type:`text`,text:`Rendered preview of view "${_}"`}],structuredContent:buildRenderPayload({projectId:i,viewId:m.id,title:_,layoutedView:g.diagram,model:p,fullModel:e.fullModel})}}catch(e){n.e=e}finally{await n.d()}}),e}const Ce=p.enum([`exact`,`contains`,`exists`]),we=likec4Tool({name:`query-by-metadata`,description:`
|
|
353
369
|
Search elements and deployment nodes by metadata key-value pairs with flexible matching modes.
|
|
354
370
|
|
|
355
371
|
Request:
|
|
@@ -415,7 +431,7 @@ Example response:
|
|
|
415
431
|
}
|
|
416
432
|
]
|
|
417
433
|
}
|
|
418
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by metadata`},inputSchema:{key:
|
|
434
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by metadata`},inputSchema:{key:p.string().describe(`Metadata key to filter by`),value:p.string().optional().describe(`Metadata value to match (ignored for exists mode)`),matchMode:Ce.optional().default(`exact`).describe(`Matching mode`),project:q},outputSchema:{results:p.array(W.extend({matchedValue:p.string().describe(`The metadata value that matched`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.matchMode,a=[],matches=(e,t,n)=>{let r=Array.isArray(e)?e:[e];switch(n){case`exists`:return!0;case`exact`:return t!==void 0&&r.some(e=>e===t);case`contains`:{if(t===void 0)return!1;let e=t.toLowerCase();return r.some(t=>t.toLowerCase().includes(e))}default:return!1}},getMatchedValue=(e,t,n)=>{let r=Array.isArray(e)?e:[e];if(n===`exists`||t===void 0)return r[0]||``;if(n===`exact`)return r.find(e=>e===t)||r[0]||``;if(n===`contains`){let e=t.toLowerCase();return r.find(t=>t.toLowerCase().includes(e))||r[0]||``}return r[0]||``};for(let e of r.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}if(a.length<50)for(let e of r.deployment.elements()){if(a.length>=50)break;let n=e.getMetadata();if(t.key in n){let r=n[t.key];r!==void 0&&matches(r,t.value,i)&&a.push({...serializeElement(e),matchedValue:getMatchedValue(r,t.value,i)})}}return{results:a}}),Te=likec4Tool({name:`query-by-tag-pattern`,description:`
|
|
419
435
|
Search elements by tag patterns using prefix or substring matching.
|
|
420
436
|
Useful for tag taxonomies with structured naming conventions (e.g., "schedule_*", "*_asil_*").
|
|
421
437
|
|
|
@@ -470,7 +486,7 @@ Example response:
|
|
|
470
486
|
"truncated": false,
|
|
471
487
|
"matchedTagValues": ["target_asil_qm", "target_asil_asil_b", "target_asil_qm__tbc"]
|
|
472
488
|
}
|
|
473
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tag pattern`},inputSchema:{pattern:
|
|
489
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tag pattern`},inputSchema:{pattern:p.string().min(1).describe(`Tag pattern to match`),matchMode:p.enum([`prefix`,`contains`,`suffix`]).optional().default(`prefix`).describe(`Pattern matching mode (default: prefix)`),project:q},outputSchema:{results:p.array(W.extend({matchedTags:p.array(p.string()).describe(`Tags that matched the pattern`)})),truncated:p.boolean().describe(`True if results were truncated`),matchedTagValues:p.array(p.string()).describe(`All unique tag values matching the pattern across all elements`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=t.pattern.toLowerCase(),matchesTag=e=>{let n=e.toLowerCase();switch(t.matchMode){case`prefix`:return n.startsWith(i);case`contains`:return n.includes(i);case`suffix`:return n.endsWith(i)}},a=[],s=!1,c=new Set;for(let e of r.elements()){let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}for(let e of r.deployment.elements()){if(!L(e))continue;let t=[...e.tags].filter(matchesTag);if(t.length>0){if(t.forEach(e=>c.add(e)),a.length>=50){s=!0;continue}a.push({...serializeElement(e),matchedTags:t})}}return{results:a,truncated:s,matchedTagValues:[...c].sort((e,t)=>e.localeCompare(t))}}),Ee=likec4Tool({name:`query-by-tags`,description:`
|
|
474
490
|
Advanced tag filtering with boolean logic (AND, OR, NOT).
|
|
475
491
|
|
|
476
492
|
Request:
|
|
@@ -534,7 +550,7 @@ Example response:
|
|
|
534
550
|
}
|
|
535
551
|
]
|
|
536
552
|
}
|
|
537
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tags`},inputSchema:{allOf:
|
|
553
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query by tags`},inputSchema:{allOf:p.array(p.string()).optional().describe(`Element must have ALL these tags (AND)`),anyOf:p.array(p.string()).optional().describe(`Element must have ANY of these tags (OR)`),noneOf:p.array(p.string()).optional().describe(`Element must have NONE of these tags (NOT)`),project:q},outputSchema:{results:p.array(W),truncated:p.boolean().describe(`True if results were truncated due to exceeding the 50-result limit`)}})(async(e,t)=>{v(t.allOf&&t.allOf.length>0||t.anyOf&&t.anyOf.length>0||t.noneOf&&t.noneOf.length>0,`At least one condition (allOf, anyOf, or noneOf) must be specified with at least one tag`);let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=[],a=!1,matchesTags=e=>{let n=e instanceof Set?e:new Set(e);return!(t.allOf&&t.allOf.length>0&&!t.allOf.every(e=>n.has(e))||t.anyOf&&t.anyOf.length>0&&!t.anyOf.some(e=>n.has(e))||t.noneOf&&t.noneOf.length>0&&t.noneOf.some(e=>n.has(e)))};for(let e of r.elements()){if(i.length>=50){a=!0;break}matchesTags(e.tags)&&i.push(serializeElement(e))}if(!a)for(let e of r.deployment.elements()){if(i.length>=50){a=!0;break}L(e)&&matchesTags(e.tags)&&i.push(serializeElement(e))}return{results:i,truncated:a}}),De=p.enum([`ancestors`,`descendants`,`siblings`,`children`,`parent`,`incomers`,`outgoers`]),Oe=likec4Tool({name:`query-graph`,description:`
|
|
538
554
|
Query element hierarchy and relationships in the architecture graph.
|
|
539
555
|
|
|
540
556
|
Request:
|
|
@@ -606,7 +622,7 @@ Example response:
|
|
|
606
622
|
],
|
|
607
623
|
"truncated": false
|
|
608
624
|
}
|
|
609
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query element graph`},inputSchema:{elementId:
|
|
625
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query element graph`},inputSchema:{elementId:p.string().describe(`Element id (FQN) to query`),queryType:De.describe(`Type of graph query`),includeIndirect:p.boolean().optional().default(!0).describe(`For incomers/outgoers: include indirect relationships (default: true)`),project:q},outputSchema:{results:p.array(W),truncated:p.boolean().describe(`True if results were truncated due to exceeding maximum limit`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.elementId);v(r,`Element "${t.elementId}" not found in project "${n}"`);let i=[],a=!1;switch(t.queryType){case`ancestors`:for(let e of r.ancestors()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`descendants`:for(let e of r.descendants()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`siblings`:for(let e of r.siblings()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`children`:for(let e of r.children()){if(i.length>=100){a=!0;break}i.push(serializeElement(e))}break;case`parent`:{let e=r.parent;e&&i.push(serializeElement(e));break}case`incomers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.incomers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}case`outgoers`:{let e=t.includeIndirect?`all`:`direct`;for(let t of r.outgoers(e)){if(i.length>=100){a=!0;break}i.push(serializeElement(t))}break}}return{results:i,truncated:a}}),ke=p.object({elementId:p.string().describe(`ID of the incoming element`),relationshipLabel:p.string().optional().describe(`Label on the relationship`),technology:p.string().optional().describe(`Technology specified on the relationship`)}),$=likec4Tool({name:`query-incomers-graph`,description:`
|
|
610
626
|
Query the complete graph of all elements that provide input to the target element (recursive incomers/producers).
|
|
611
627
|
|
|
612
628
|
This tool performs a breadth-first traversal to discover all upstream dependencies - elements that directly or
|
|
@@ -663,7 +679,7 @@ Notes:
|
|
|
663
679
|
Example:
|
|
664
680
|
For a database element, this returns all services, APIs, and components that write to it,
|
|
665
681
|
plus all their dependencies, recursively up to maxDepth levels.
|
|
666
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete incomers graph`},inputSchema:{elementId:
|
|
682
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete incomers graph`},inputSchema:{elementId:p.string().describe(`Target element id (FQN) to query incomers for`),includeIndirect:p.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:p.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:p.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:q},outputSchema:{target:p.string().describe(`Target element id`),totalNodes:p.number().describe(`Total number of nodes in the graph`),maxDepth:p.number().describe(`Maximum depth reached`),truncated:p.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:p.record(p.string(),W.extend({incomers:p.array(ke).describe(`Incoming relationships with details`),depth:p.number().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);v(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`incoming`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,incomers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),Ae=p.object({elementId:p.string().describe(`ID of the outgoing element`),relationshipLabel:p.string().optional().describe(`Label on the relationship`),technology:p.string().optional().describe(`Technology specified on the relationship`)}),je=likec4Tool({name:`query-outgoers-graph`,description:`
|
|
667
683
|
Query the complete graph of all elements that receive output from the target element (recursive outgoers/consumers).
|
|
668
684
|
|
|
669
685
|
This tool performs a breadth-first traversal to discover all downstream dependencies - elements that directly or
|
|
@@ -720,7 +736,7 @@ Notes:
|
|
|
720
736
|
Example:
|
|
721
737
|
For an API service, this returns all clients, services, and systems that consume its output,
|
|
722
738
|
plus all their consumers, recursively up to maxDepth levels.
|
|
723
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete outgoers graph`},inputSchema:{elementId:
|
|
739
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Query complete outgoers graph`},inputSchema:{elementId:p.string().describe(`Target element id (FQN) to query outgoers for`),includeIndirect:p.boolean().optional().default(!0).describe(`Include indirect relationships through nested elements (default: true)`),maxDepth:p.number().int().positive().max(50).optional().default(10).describe(`Maximum traversal depth (default: 10, max: 50)`),maxNodes:p.number().int().positive().max(2e3).optional().default(200).describe(`Maximum number of nodes to return (default: 200, max: 2000)`),project:q},outputSchema:{target:p.string().describe(`Target element id`),totalNodes:p.number().describe(`Total number of nodes in the graph`),maxDepth:p.number().describe(`Maximum depth reached`),truncated:p.boolean().describe(`True if result was truncated due to maxNodes limit`),nodes:p.record(p.string(),W.extend({outgoers:p.array(Ae).describe(`Outgoing relationships with details`),depth:p.number().describe(`Distance from target element (0 = target)`)}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=await e.computedModel(n),i=r.findElement(t.elementId);v(i,`Element "${t.elementId}" not found in project "${n}"`);let a=t.includeIndirect?`all`:`direct`,s=traverseGraph(r,t.elementId,`outgoing`,a,t.maxDepth,t.maxNodes),c={};for(let[e,t]of Object.entries(s.nodes)){let{neighbors:n,...r}=t;c[e]={...r,outgoers:n}}return{target:s.target,totalNodes:s.totalNodes,maxDepth:s.maxDepth,truncated:s.truncated,nodes:c}}),Me=likec4Tool({name:`read-deployment`,description:`
|
|
724
740
|
Read details about a deployment node or a deployed instance in a LikeC4 project.
|
|
725
741
|
|
|
726
742
|
What it does:
|
|
@@ -785,7 +801,7 @@ Example response (deployed instance):
|
|
|
785
801
|
"range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
|
|
786
802
|
}
|
|
787
803
|
}
|
|
788
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read deployment entity`},inputSchema:{id:
|
|
804
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read deployment entity`},inputSchema:{id:p.string().describe(`Deployment id (FQN)`),project:q},outputSchema:{type:p.enum([`deployment-node`,`deployed-instance`]),id:p.string().describe(`Deployment id (FQN)`),kind:p.string().describe(`Deployment node kind, or element kind for deployed instances`),name:p.string(),title:p.string(),description:p.string().nullable(),technology:p.string().nullable(),tags:p.array(p.string()),project:p.string(),metadata:p.record(p.string(),p.union([p.string(),p.array(p.string())])),links:K.describe(`External links associated with this deployment entity`),shape:p.string(),color:p.string(),children:p.array(p.string()).describe(`Children of this deployment node (Array of Deployment ids)`),includedInViews:J.describe(`Views that include this deployment node`),instanceof:p.object({id:p.string().describe(`Element ID (FQN)`),title:p.string(),kind:p.string()}).nullable().describe(`If type is "deployed-instance", the referenced element`),sourceLocation:G}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).deployment.findElement(t.id);v(r,`Deployment entity "${t.id}" not found in project "${n}"`);let i=mkLocate(e,n);return{type:r.isInstance()?`deployed-instance`:`deployment-node`,id:r.id,name:r.name,kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags],project:n,metadata:r.getMetadata(),links:serializeLinks(r),shape:r.shape,color:r.color,children:r.isInstance()?[]:[...r.children()].map(e=>e.id),includedInViews:includedInViews(r.views()),instanceof:r.isInstance()?{id:r.element.id,title:r.element.title,kind:r.element.kind}:null,sourceLocation:i({deployment:r.id})}}),Ne=likec4Tool({name:`read-element`,description:`
|
|
789
805
|
Read detailed information about a LikeC4 element.
|
|
790
806
|
|
|
791
807
|
Request:
|
|
@@ -872,7 +888,7 @@ Example response:
|
|
|
872
888
|
"range": { "start": { "line": 10, "character": 0 }, "end": { "line": 25, "character": 0 } }
|
|
873
889
|
}
|
|
874
890
|
}
|
|
875
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read element`},inputSchema:{id:
|
|
891
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read element`},inputSchema:{id:p.string().describe(`Element id (FQN)`),project:q},outputSchema:{id:p.string().describe(`Element id (FQN)`),kind:p.string().describe(`Element kind`),name:p.string().describe(`Element name`),title:p.string(),description:p.string().nullable(),technology:p.string().nullable(),tags:p.array(p.string()),project:p.string(),metadata:p.record(p.string(),p.union([p.string(),p.array(p.string())])),links:K,shape:p.string(),color:p.string(),children:p.array(p.string()).describe(`Children of this element (Array of FQNs)`),defaultView:p.string().nullable().describe(`Name of the default view of this element`),includedInViews:J.describe(`Views that include this element`),relationships:p.object({incoming:p.array(p.object({source:p.object({id:p.string(),title:p.string(),kind:p.string()}).describe(`Source element of this relationship`),kind:p.string().nullable().describe(`Relationship kind`),target:p.string().describe(`Target element id (FQN), either this element or nested element, if relationship is indirect`),title:p.string().nullable().describe(`Relationship title`),description:p.string().nullable().describe(`Relationship description`),technology:p.string().nullable().describe(`Relationship technology`),tags:p.array(p.string()).describe(`Relationship tags`)})).describe(`Incoming relationships of this element (direct and indirect, incoming to nested elements)`),outgoing:p.array(p.object({source:p.string().describe(`Source element id (FQN), either this element or nested element, if relationship is indirect`),target:p.object({id:p.string(),title:p.string(),kind:p.string()}).describe(`Target element of this relationship`),kind:p.string().nullable().describe(`Relationship kind`),title:p.string().nullable().describe(`Relationship title`),description:p.string().nullable().describe(`Relationship description`),technology:p.string().nullable().describe(`Relationship technology`),tags:p.array(p.string()).describe(`Relationship tags`)})).describe(`Outgoing relationships of this element (direct and indirect, outgoing from nested elements)`)}).describe(`Relationships of this element`),deployedInstances:p.array(p.string()).describe(`Deployed instances of this element (Array of Deployment FQNs)`),sourceLocation:G}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.id);v(r,`Element "${t.id}" not found in project "${n}"`);let i=mkLocate(e,n);return{id:r.id,name:r.name,kind:r.kind,title:r.title,description:r.description.text,technology:r.technology,tags:[...r.tags],project:n,metadata:r.getMetadata(),links:serializeLinks(r),shape:r.shape,color:r.color,children:[...r.children()].map(e=>e.id),defaultView:r.defaultView?.id||null,includedInViews:includedInViews(r.views()),relationships:{incoming:[...r.incoming()].map(e=>({source:{id:e.source.id,title:e.source.title,kind:e.source.kind},kind:e.kind,target:e.target.id,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]})),outgoing:[...r.outgoing()].map(e=>({source:e.source.id,target:{id:e.target.id,title:e.target.title,kind:e.target.kind},kind:e.kind,title:e.title,description:e.description.text,technology:e.technology,tags:[...e.tags]}))},deployedInstances:[...r.deployments()].map(e=>e.id),sourceLocation:i({element:r.id})}}),Pe=likec4Tool({name:`read-project-summary`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read project summary`},description:`
|
|
876
892
|
Request:
|
|
877
893
|
- project: string (optional) — project id. Defaults to "default" if omitted.
|
|
878
894
|
|
|
@@ -963,7 +979,7 @@ Example response:
|
|
|
963
979
|
}
|
|
964
980
|
]
|
|
965
981
|
}
|
|
966
|
-
`,inputSchema:{project:
|
|
982
|
+
`,inputSchema:{project:q},outputSchema:{title:p.string(),folder:p.string(),sources:p.array(p.string()),config:pe.describe(`Project configuration`),specification:p.object({elementKinds:p.array(p.string()),relationshipKinds:p.array(p.string()),deploymentKinds:p.array(p.string()),tags:p.array(p.string()),metadataKeys:p.array(p.string())}),elements:p.array(p.object({id:p.string(),kind:p.string(),title:p.string(),tags:p.array(p.string())})).describe(`List of elements in the project`),deployments:p.array(p.discriminatedUnion(`type`,[p.object({type:p.literal(`deployment-node`),id:p.string().describe(`Node ID`),kind:p.string().describe(`Deployment node kind`),title:p.string().describe(`Node title`),tags:p.array(p.string())}),p.object({type:p.literal(`deployed-instance`),id:p.string().describe(`Node ID`),title:p.string().describe(`Node title`),tags:p.array(p.string()),referencedElementId:p.string().describe(`Element ID (FQN)`)})])).describe(`List of deployment nodes and deployed instances in the project`),views:p.array(p.object({id:p.string(),title:p.string(),type:p.enum([`element`,`deployment`,`dynamic`])}))}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=await e.computedModel(n);return{title:r.title,folder:r.folder.fsPath,sources:r.documents?.map(e=>e.fsPath)??[],config:serializeConfig(r.config),specification:{elementKinds:S(i.specification.elements),relationshipKinds:S(i.specification.relationships),deploymentKinds:S(i.specification.deployments),tags:[...i.tags],metadataKeys:i.specification.metadataKeys??[]},elements:[...i.elements()].filter(e=>!e.imported).map(e=>({id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]})),deployments:[...i.deployment.elements()].map(e=>e.isInstance()?{type:`deployed-instance`,id:e.id,title:e.title,tags:[...e.tags],referencedElementId:e.element.id}:{type:`deployment-node`,id:e.id,kind:e.kind,title:e.title,tags:[...e.tags]}),views:[...i.views()].map(e=>({id:e.id,title:e.titleOrId,type:e.$view._type}))}}),modelRef=e=>e.hasElement()?e.element.id:e.hasDeployment()?e.deployment.id:null,Fe=p.discriminatedUnion(`type`,[p.object({type:p.literal(`element`),id:p.string().describe(`Node ID`),elementId:p.string().describe(`Element ID (FQN)`),kind:p.string().describe(`Element kind`),title:p.string().describe(`Node title`),description:p.string().nullable(),technology:p.string().nullable(),children:p.array(p.string()).describe(`Children nodes, array of node IDs`),shape:p.string().describe(`Rendered shape`),color:p.string().describe(`Rendered color`),tags:p.array(p.string())}),p.object({type:p.literal(`deployment-node`),id:p.string().describe(`Node ID`),deploymentId:p.string().describe(`Deployment entity ID (FQN)`),kind:p.string().describe(`Deployment kind`),title:p.string().describe(`Node title`),description:p.string().nullable(),technology:p.string().nullable(),children:p.array(p.string()).describe(`Children nodes, array of node IDs`),shape:p.string().describe(`Rendered shape`),color:p.string().describe(`Rendered color`),tags:p.array(p.string())}),p.object({type:p.literal(`deployed-instance`),id:p.string().describe(`Node ID`),deploymentId:p.string().describe(`Deployment entity ID (FQN)`),title:p.string().describe(`Node title`),description:p.string().nullable(),technology:p.string().nullable(),referencedElement:p.object({id:p.string().describe(`Element ID (FQN)`),kind:p.string().describe(`Element kind`),title:p.string().describe(`Element title`)}),shape:p.string().describe(`Rendered shape`),color:p.string().describe(`Rendered color`),tags:p.array(p.string())})]),Ie=likec4Tool({name:`read-view`,description:`
|
|
967
983
|
Read detailed information about a LikeC4 view.
|
|
968
984
|
|
|
969
985
|
Request:
|
|
@@ -1011,7 +1027,7 @@ Example response:
|
|
|
1011
1027
|
"range": { "start": { "line": 10, "character": 0 }, "end": { "line": 30, "character": 0 } }
|
|
1012
1028
|
}
|
|
1013
1029
|
}
|
|
1014
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read view`},inputSchema:{viewId:
|
|
1030
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Read view`},inputSchema:{viewId:p.string().describe(`View id (name)`),project:q},outputSchema:{id:p.string(),type:p.enum([`element`,`deployment`,`dynamic`]).describe(`View type`),title:p.string(),description:p.string().nullable(),tags:p.array(p.string()),project:p.string(),nodes:p.array(Fe),edges:p.array(p.object({source:p.string().describe(`Source node`),target:p.string().describe(`Target node`),label:p.string().nullable(),description:p.string().nullable(),technology:p.string().nullable(),tags:p.array(p.string())})).describe(`Edge represents relationship between nodes`),sourceLocation:G}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=e.project(n),i=(await e.computedModel(n)).findView(t.viewId);if(!i)throw Error(`View with ID '${t.viewId}' not found in project ${r.id}`);let a=mkLocate(e,r.id);return{id:i.id,type:i.$view._type,title:i.title??i.id,description:i.description.text,tags:[...i.tags],project:r.id,nodes:[...i.nodes()].flatMap(e=>{let t={id:e.id,title:e.title,description:e.description.text,technology:e.technology,shape:e.shape,color:e.color,tags:[...e.tags]};return e.hasDeployedInstance()?{...t,type:`deployed-instance`,deploymentId:e.deployment.id,referencedElement:{id:e.deployment.element.id,kind:e.deployment.element.kind,title:e.deployment.element.title}}:e.hasDeployment()?{...t,type:`deployment-node`,kind:e.deployment.kind,deploymentId:e.deployment.id,children:[...e.children()].map(e=>e.id)}:e.hasElement()?{...t,type:`element`,elementId:e.element.id,kind:e.element.kind,children:[...e.children()].flatMap(e=>modelRef(e)??[])}:[]}),edges:[...i.edges()].map(e=>({source:e.source.id,target:e.target.id,label:e.label,description:e.description.text,technology:e.technology,tags:[...e.tags]})),sourceLocation:a({view:i.id})}}),Le=p.array(p.discriminatedUnion(`type`,[p.object({type:p.literal(`element`),project:p.string().describe(`Project ID`),id:p.string().describe(`Element ID (FQN)`),name:p.string().describe(`Element name`),kind:p.string(),title:p.string(),technology:p.string().nullable(),shape:p.string(),includedInViews:J,metadata:p.record(p.string(),p.union([p.string(),p.array(p.string())])),tags:p.array(p.string())}),p.object({type:p.literal(`deployment-node`),project:p.string().describe(`Project ID`),id:p.string().describe(`Deployment ID (FQN)`),name:p.string().describe(`Deployment name`),kind:p.string(),title:p.string(),technology:p.string().nullable(),shape:p.string(),includedInViews:J,metadata:p.record(p.string(),p.union([p.string(),p.array(p.string())])),tags:p.array(p.string())})])),Re=likec4Tool({name:`search-element`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Search elements`},description:`
|
|
1015
1031
|
Search LikeC4 elements and deployment nodes across all projects.
|
|
1016
1032
|
|
|
1017
1033
|
Query syntax (case-insensitive):
|
|
@@ -1066,7 +1082,7 @@ Example response:
|
|
|
1066
1082
|
}
|
|
1067
1083
|
]
|
|
1068
1084
|
}
|
|
1069
|
-
`,inputSchema:{search:
|
|
1085
|
+
`,inputSchema:{search:p.string().min(2,`Search must be at least 2 characters long`)},outputSchema:{total:p.number(),found:Le}})(async(e,t)=>{let n=e.projects(),r=[],i=t.search.toLowerCase(),predicate;i.startsWith(`kind:`)?(i=i.slice(5),U.debug(`search by kind: {search}`,{search:i}),predicate=e=>e.kind.toLowerCase()===i):i.startsWith(`shape:`)?(i=i.slice(6),U.debug(`search by shape: {search}`,{search:i}),predicate=e=>e.shape.toLowerCase()===i):i.startsWith(`meta:`)?(i=i.slice(5),U.debug(`search by metadata: {search}`,{search:i}),predicate=e=>!!e.getMetadata(i)):i.startsWith(`#`)?(i=i.slice(1),U.debug(`search by tag: {search}`,{search:i}),predicate=e=>e.tags.some(e=>e.toLowerCase().includes(i))):(U.debug(`search by id/title: {search}`,{search:i}),predicate=e=>e.id.toLowerCase().includes(i)||e.title.toLowerCase().includes(i));for(let t of n)try{let n=await e.computedModel(t.id);for(let e of R(n.elements(),e=>!e.imported&&predicate(e)))r.push({type:`element`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())});for(let e of R(n.deployment.nodes(),predicate))r.push({type:`deployment-node`,project:t.id,id:e.id,name:e.name,kind:e.kind,title:e.title,technology:e.technology,shape:e.shape,tags:[...e.tags],metadata:e.getMetadata(),includedInViews:includedInViews(e.views())})}catch(e){U.error(`Error searching in project ${t.id}:`,{error:e})}return{total:r.length,found:r.slice(0,20)}}),ze=p.object({id:p.string().describe(`Element id (FQN)`),name:p.string().describe(`Element name`),kind:p.string().describe(`Element kind`),title:p.string().describe(`Human-readable title`),depth:p.number().describe(`Depth relative to the root element (1 = direct child)`),tags:p.array(p.string()).describe(`Assigned tags`),metadata:p.record(p.string(),p.union([p.string(),p.array(p.string())])).describe(`Element metadata`),childCount:p.number().describe(`Number of direct children`),incomingCount:p.number().describe(`Number of incoming relationships`),outgoingCount:p.number().describe(`Number of outgoing relationships`)}),Be=likec4Tool({name:`subgraph-summary`,description:`
|
|
1070
1086
|
Get a compact, table-friendly summary of all descendants of a parent element.
|
|
1071
1087
|
Returns each descendant with its depth, metadata, tags, and relationship counts in a single call.
|
|
1072
1088
|
Much more efficient than calling read-element for each descendant individually.
|
|
@@ -1132,7 +1148,7 @@ Example response:
|
|
|
1132
1148
|
"truncated": false,
|
|
1133
1149
|
"truncatedByDepth": false
|
|
1134
1150
|
}
|
|
1135
|
-
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Subgraph summary`},inputSchema:{elementId:
|
|
1151
|
+
`,annotations:{readOnlyHint:!0,idempotentHint:!0,title:`Subgraph summary`},inputSchema:{elementId:p.string().describe(`Parent element id (FQN) whose descendants to summarize`),maxDepth:p.number().int().min(1).max(20).optional().default(10).describe(`Maximum depth of descendants to include (default: 10, max: 20)`),metadataKeys:p.array(p.string()).optional().describe(`If provided, only include these metadata keys in the response`),project:q},outputSchema:{root:p.object({id:p.string(),kind:p.string(),title:p.string(),childCount:p.number()}),descendants:p.array(ze),totalDescendants:p.number().describe(`Total number of descendants found`),truncated:p.boolean().describe(`True if results were truncated due to exceeding the limit`),truncatedByDepth:p.boolean().describe(`True if deeper descendants exist beyond maxDepth`)}})(async(e,t)=>{let n=e.projectsManager.ensureProjectId(t.project),r=(await e.computedModel(n)).findElement(t.elementId);v(r,`Element "${t.elementId}" not found in project "${n}"`);let i=t.maxDepth,a=t.metadataKeys,s=[],c=0,l=!1,u=!1,f=[],p=[...r.children()];for(let e of p)f.push({element:e,depth:1});for(;f.length>0;){let{element:e,depth:t}=f.shift();if(t>i){u=!0;continue}c++;let n=[...e.children()];if(s.length<200){let r=e.getMetadata(),i=a?Object.fromEntries(a.filter(e=>e in r).map(e=>[e,r[e]])):r;s.push({id:e.id,name:e.name,kind:e.kind,title:e.title,depth:t,tags:[...e.tags],metadata:i,childCount:n.length,incomingCount:[...e.incoming()].length,outgoingCount:[...e.outgoing()].length})}else l=!0;for(let e of n)f.push({element:e,depth:t+1})}return{root:{id:r.id,kind:r.kind,title:r.title,childCount:p.length},descendants:s,totalDescendants:c,truncated:l,truncatedByDepth:u}});function createMCPServer(e){let t=new E({name:`LikeC4`,version:fe},{instructions:`LikeC4 MCP – query and navigate LikeC4 models.
|
|
1136
1152
|
|
|
1137
1153
|
Conventions:
|
|
1138
1154
|
- All tools are read-only and idempotent.
|
|
@@ -1154,7 +1170,7 @@ Available tools:
|
|
|
1154
1170
|
- query-by-metadata — Search elements by metadata key-value pairs with exact/contains/exists matching. Input: { key, value?, matchMode?, project? }.
|
|
1155
1171
|
- query-by-tags — Advanced tag filtering with boolean logic (allOf, anyOf, noneOf). Input: { allOf?, anyOf?, noneOf?, project? }.
|
|
1156
1172
|
- find-relationship-paths — Discover all paths (chains of relationships) between two elements with BFS traversal. Input: { sourceId, targetId, maxDepth?, includeIndirect?, project? }.
|
|
1157
|
-
- batch-read-elements — Read details of multiple elements in a single call, reducing round-trips. Input: { ids, project? }.
|
|
1173
|
+
- batch-read-elements — Read details of multiple elements in a single call, reducing round-trips. Includes links and sourceLocation, same as read-element. Input: { ids, project? }.
|
|
1158
1174
|
- query-by-tag-pattern — Search elements by tag prefix/contains/suffix patterns. Input: { pattern, matchMode?, project? }.
|
|
1159
1175
|
- element-diff — Compare two elements side-by-side showing differences in properties, tags, metadata, and relationships. Input: { element1Id, element2Id, project? }.
|
|
1160
1176
|
- subgraph-summary — Compact summary of all descendants of a parent element with metadata, tags, and relationship counts. Input: { elementId, maxDepth?, metadataKeys?, project? }.
|
|
@@ -1167,4 +1183,4 @@ Instructions:
|
|
|
1167
1183
|
- If response returns "sourceLocation", provide link to this location in the editor
|
|
1168
1184
|
|
|
1169
1185
|
Full documentation: https://likec4.dev/llms-full.txt
|
|
1170
|
-
`,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{
|
|
1186
|
+
`,enforceStrictCapabilities:!0,capabilities:{completions:{},tools:{},logging:{},prompts:{},resources:{}}});return t.server.onerror=e=>{b.error(y(e))},C(t,setMcpServerCtx,xe,Pe,Ne,Me,Ie,Re,be,ve,w(Oe,$,je,we,Ee,Te),w(he,_e,Be),w(applySemanticLayoutPrompt,applySemanticLayoutTool,renderViewTool,previewViewTool),w(projectResource,renderViewResource))}var StdioLikeC4MCPServer=class{services;options;transport=void 0;_mcp=void 0;constructor(e,t={}){this.services=e,this.options=t}get mcp(){if(!this._mcp)throw Error(`MCP server is not started`);return this._mcp}get isStarted(){return this.transport!==void 0}get port(){return NaN}async dispose(){await this.stop()}async start(){if(!this.transport){U.info(`Starting MCP stdio server`),this._mcp=createMCPServer(this.services),setMcpServerCtx(this._mcp),this.transport=new f(this.options.stdin,this.options.stdout);try{await this._mcp.connect(this.transport)}catch(e){throw await this.stop(),e}U.info(`LikeC4 MCP Server running on stdio`)}}async stop(){if(this.transport)try{U.info(`Stopping MCP stdio server`),await this.transport.close(),this._mcp&&await this._mcp.close()}finally{this._mcp=void 0,this.transport=void 0,setMcpServerCtx(void 0)}}};async function createHonoApp(e){let t=new ue;t.use(`*`,de({origin:`*`,allowHeaders:[`Content-Type`,`mcp-session-id`,`Last-Event-ID`,`mcp-protocol-version`],exposeHeaders:[`mcp-session-id`,`mcp-protocol-version`]})),t.get(`/health`,e=>e.json({status:`ok`}));let n=e();setMcpServerCtx(n);let r=new ce({eventStore:new se({})});return t.all(`/mcp`,async e=>(n.isConnected()||await n.connect(r),await r.handleRequest(e))),t.notFound(e=>(U.debug(`${e.req.method} ${e.req.url} not found`),e.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not found.`},id:null},{status:404}))),t.onError((e,t)=>(U.error(y(e)),t.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null},{status:500}))),t}async function startServer(e){let{factory:t,port:n}=e,r=await createHonoApp(t);return new Promise((e,t)=>{let i=le({fetch:r.fetch,hostname:`0.0.0.0`,port:n}).prependOnceListener(`error`,t).prependOnceListener(`listening`,()=>{i.removeListener(`error`,t),e(i.unref())})})}var StreamableLikeC4MCPServer=class{services;_port;server=void 0;constructor(e,t=33335){this.services=e,this._port=t}get mcp(){throw Error(`StreamableLikeC4MCPServer has access to McpServer only during the request`)}get isStarted(){return this.server?.listening===!0}get port(){return this._port}async dispose(){await this.stop()}async start(e=this._port){if(this.server){if(this.port===e)return;await this.stop()}U.info(`Starting MCP server on port {port}`,{port:e}),this._port=e,this.server=await startServer({factory:()=>createMCPServer(this.services),port:e}),U.info(`MCP server ready at http://0.0.0.0:{port}/mcp`,{port:e})}stop(){let e=this.server;return e?(U.info(`Stopping MCP server`),this.server=void 0,setMcpServerCtx(void 0),new Promise(t=>{e.close(e=>{e?U.error(`Failed to stop MCP server`,{err:e}):U.info(`MCP server stopped`),t()})})):(U.info(`MCP server is not running, nothing to stop`),Promise.resolve())}};async function initLikeC4MCP(t){let i=r(t,{workspacePath:`.`,mcp:`stdio`,graphviz:`wasm`,watch:!0,throwIfInvalid:!1,configureLogger:!0});i.configureLogger&&(e({useStdErr:i.mcp===`stdio`,colors:l.isColorSupported&&i.mcp!==`stdio`,logLevel:c?`debug`:`info`}),process.on(`uncaughtException`,e=>{U.error(`uncaughtException`,{err:e})}),process.on(`unhandledRejection`,e=>{U.error(`unhandledRejection`,{err:e})}));let s=a(i.workspacePath);U.info`Loading LikeC4 from workspace: ${s}`;let u=await n(s,{graphviz:i.graphviz,manualLayouts:!0,configureLogger:!1,watch:i.watch,throwIfInvalid:i.throwIfInvalid}),f=setLanguageServicesCtx(u.languageServices);return{server:i.mcp===`stdio`?new StdioLikeC4MCPServer(f,i.stdio):new StreamableLikeC4MCPServer(f,i.mcp.port),likec4:u}}async function startLikeC4MCP(e){let t=e?.mcp===void 0||e.mcp===`stdio`?e?.stdio?.stdin??process.stdin:void 0,n,r=!1,i=t?t.readableEnded||t.destroyed:!1,a,cleanup=async()=>{let e=n;e&&(a??=(async()=>{try{await e.server.stop()}finally{try{await e.likec4.dispose()}finally{setLanguageServicesCtx(void 0)}}})(),await a)};function stopObservingStdin(){t&&(t.off(`end`,onStdinClosed),t.off(`close`,onStdinClosed))}function onStdinClosed(){i=!0,stopObservingStdin(),r&&cleanup().catch(e=>{U.error(`Failed to stop MCP stdio server after stdin closed`,{err:e})})}t&&!i&&(t.once(`end`,onStdinClosed),t.once(`close`,onStdinClosed),i=t.readableEnded||t.destroyed);try{if(n=await initLikeC4MCP(e),n.server instanceof StdioLikeC4MCPServer){if(i)return stopObservingStdin(),await cleanup(),n;await n.server.start(),r=!0,i&&await cleanup()}else await n.server.start();return n}catch(e){if(stopObservingStdin(),n)try{await cleanup()}catch(e){U.error(`Failed to clean up MCP stdio server after start error`,{err:e})}throw e}}export{__name as i,startLikeC4MCP as n,U as r,initLikeC4MCP as t};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@likec4/mcp",
|
|
3
3
|
"description": "Model Context Protocol server for LikeC4",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"version": "1.59.
|
|
5
|
+
"version": "1.59.4",
|
|
6
6
|
"bugs": "https://github.com/likec4/likec4/issues",
|
|
7
7
|
"homepage": "https://likec4.dev",
|
|
8
8
|
"author": "Denis Davydkov <denis@davydkov.com>",
|
|
@@ -44,21 +44,21 @@
|
|
|
44
44
|
"@hono/mcp": "^0.3.2",
|
|
45
45
|
"@hono/node-server": "^2.1.1",
|
|
46
46
|
"@hpcc-js/wasm-graphviz": "1.22.2",
|
|
47
|
-
"@likec4/config": "1.59.
|
|
48
|
-
"@likec4/core": "1.59.
|
|
49
|
-
"@likec4/language-server": "1.59.
|
|
50
|
-
"@likec4/language-services": "1.59.
|
|
51
|
-
"@likec4/layouts": "1.59.
|
|
52
|
-
"@likec4/log": "1.59.
|
|
53
|
-
"@likec4/diagram": "1.59.
|
|
47
|
+
"@likec4/config": "1.59.4",
|
|
48
|
+
"@likec4/core": "1.59.4",
|
|
49
|
+
"@likec4/language-server": "1.59.4",
|
|
50
|
+
"@likec4/language-services": "1.59.4",
|
|
51
|
+
"@likec4/layouts": "1.59.4",
|
|
52
|
+
"@likec4/log": "1.59.4",
|
|
53
|
+
"@likec4/diagram": "1.59.4",
|
|
54
54
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
55
|
-
"@modelcontextprotocol/ext-apps": "^1.7.
|
|
55
|
+
"@modelcontextprotocol/ext-apps": "^1.7.5",
|
|
56
56
|
"@mantine/core": "9.6.0",
|
|
57
57
|
"bundle-require": "^5.1.0",
|
|
58
58
|
"citty": "^0.2.2",
|
|
59
59
|
"defu": "^6.1.7",
|
|
60
|
-
"esbuild": "0.28.
|
|
61
|
-
"hono": "^4.13.
|
|
60
|
+
"esbuild": "0.28.2",
|
|
61
|
+
"hono": "^4.13.8",
|
|
62
62
|
"remeda": "^2.45.0",
|
|
63
63
|
"react": "19.2.8",
|
|
64
64
|
"react-dom": "19.2.8",
|
|
@@ -70,15 +70,15 @@
|
|
|
70
70
|
"zod": "^4.4.3"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
|
-
"@likec4/devops": "1.59.
|
|
74
|
-
"@likec4/tsconfig": "1.59.
|
|
73
|
+
"@likec4/devops": "1.59.4",
|
|
74
|
+
"@likec4/tsconfig": "1.59.4",
|
|
75
75
|
"@types/node": "~22.19.19",
|
|
76
76
|
"@types/react": "19.2.18",
|
|
77
77
|
"@types/react-dom": "19.2.5",
|
|
78
78
|
"@vitest/ui": "4.1.11",
|
|
79
79
|
"langium": "3.5.0",
|
|
80
|
-
"tsdown": "^0.
|
|
81
|
-
"tsx": "4.
|
|
80
|
+
"tsdown": "^0.23.0",
|
|
81
|
+
"tsx": "4.23.13",
|
|
82
82
|
"turbo": "2.10.12",
|
|
83
83
|
"typescript": "6.0.3",
|
|
84
84
|
"type-fest": "^4.41.0",
|