vue-llm 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +1 -1
  2. package/README.ru.md +1 -1
  3. package/dist/components/MessageParts.vue.d.ts +6 -1
  4. package/dist/components.cjs +5 -5
  5. package/dist/components.js +84 -77
  6. package/dist/composables/mcp-server-mode.d.ts +77 -0
  7. package/dist/composables/use-chat.d.ts +1 -1
  8. package/dist/composables/use-mcp-servers.d.ts +83 -0
  9. package/dist/composables/use-mcp.d.ts +69 -0
  10. package/dist/index.cjs +3 -3
  11. package/dist/index.d.ts +7 -1
  12. package/dist/index.js +1267 -622
  13. package/dist/mcp/auth.d.ts +36 -0
  14. package/dist/mcp/callback.d.ts +25 -0
  15. package/dist/mcp/client.d.ts +44 -0
  16. package/dist/mcp/connector.d.ts +100 -0
  17. package/dist/mcp/crypto.d.ts +7 -0
  18. package/dist/mcp/errors.d.ts +23 -0
  19. package/dist/mcp/oauth.d.ts +56 -0
  20. package/dist/mcp/pkce.d.ts +7 -0
  21. package/dist/mcp/servers.d.ts +33 -0
  22. package/dist/mcp/ssrf.d.ts +31 -0
  23. package/dist/mcp/storage.d.ts +11 -0
  24. package/dist/mcp/tools.d.ts +78 -0
  25. package/dist/mcp/url.d.ts +12 -0
  26. package/dist/mcp.cjs +1 -3
  27. package/dist/mcp.d.ts +16 -76
  28. package/dist/mcp.js +19 -37
  29. package/dist/providers/types.d.ts +7 -0
  30. package/dist/providers.cjs +5 -5
  31. package/dist/providers.js +2 -2
  32. package/dist/server.cjs +8 -2
  33. package/dist/server.d.ts +4 -1
  34. package/dist/server.js +698 -87
  35. package/dist/sse-BDTygVRH.cjs +1 -0
  36. package/dist/sse-D2QqRQtL.js +56 -0
  37. package/dist/sse-parser-C5ic_1Md.js +51 -0
  38. package/dist/sse-parser-QKQOCZFZ.cjs +2 -0
  39. package/dist/storage-BHPyF4R0.js +111 -0
  40. package/dist/storage-COtyEXkO.cjs +1 -0
  41. package/dist/tools-D_woBxZR.cjs +3 -0
  42. package/dist/tools-oT9QbQYq.js +511 -0
  43. package/dist/types.d.ts +16 -1
  44. package/dist/url-B7vsi1v5.js +37 -0
  45. package/dist/url-DbGQTNRK.cjs +1 -0
  46. package/dist/vue-llm.css +1 -1
  47. package/package.json +3 -2
  48. package/dist/sse-CbFKaVA2.js +0 -104
  49. package/dist/sse-QNG6DnpI.cjs +0 -2
package/README.md CHANGED
@@ -28,7 +28,7 @@
28
28
  - **Streaming** — SSE parser, text/reasoning/tool-call deltas
29
29
  - **Security** — `dangerouslyAllowBrowser` guard protects API keys
30
30
  - **Chat UI** — a complete chat you own: `npx shadcn-vue add https://vue-llm.js.org/r/chat.json`, plus headless `usePromptInput` and `useAutoScroll`
31
- - **MCP** — tools of any MCP server (search, files, GitHub, databases) in `useChat` and on the server (`vue-llm/mcp`)
31
+ - **MCP** — tools of any MCP server (search, files, GitHub, databases) in `useChat` and on the server (`vue-llm/mcp`); users connect their own servers (Notion, Linear…) with OAuth sign-in via `useMCP` / `useMCPServers`, in the browser or through your backend (`createMCPConnector`)
32
32
  - **Vue DevTools** — an LLM tab with every chat, request timeline, time to first token, tool calls and token usage (`vue-llm/devtools`)
33
33
  - **Nuxt module** — auto-imports, components, DevTools in development, server-side runtime config
34
34
  - **Zero runtime deps** — only `vue` as peer dependency (Vue 3.3+, composables also on Vue 2.7)
package/README.ru.md CHANGED
@@ -28,7 +28,7 @@
28
28
  - **Стриминг** — SSE-парсер, дельты текста, рассуждений и вызовов инструментов
29
29
  - **Безопасность** — защита `dangerouslyAllowBrowser` бережёт API-ключи
30
30
  - **Chat UI** — готовый чат, код которого принадлежит вам: `npx shadcn-vue add https://vue-llm.js.org/r/chat.json`, плюс headless `usePromptInput` и `useAutoScroll`
31
- - **MCP** — инструменты любого MCP-сервера (поиск, файлы, GitHub, базы данных) в `useChat` и на сервере (`vue-llm/mcp`)
31
+ - **MCP** — инструменты любого MCP-сервера (поиск, файлы, GitHub, базы данных) в `useChat` и на сервере (`vue-llm/mcp`); пользователи подключают свои серверы (Notion, Linear…) со входом через OAuth — `useMCP` / `useMCPServers`, прямо из браузера или через ваш бэкенд (`createMCPConnector`)
32
32
  - **Vue DevTools** — вкладка LLM со всеми чатами, таймлайном запросов, временем до первого токена, вызовами инструментов и расходом токенов (`vue-llm/devtools`)
33
33
  - **Nuxt-модуль** — автоимпорты, компоненты, DevTools в режиме разработки, серверный runtime config
34
34
  - **Ноль runtime-зависимостей** — только `vue` в peer-зависимостях (Vue 3.3+, композаблы работают и на Vue 2.7)
@@ -1,9 +1,11 @@
1
1
  import type { Component } from 'vue';
2
- import type { ToolCallPart, UIMessage } from '../types.js';
2
+ import type { DataPart, ToolCallPart, UIMessage } from '../types.js';
3
3
  type __VLS_Props = {
4
4
  message: UIMessage;
5
5
  /** Components that render tool calls, keyed by tool name (Generative UI) */
6
6
  components?: Record<string, Component>;
7
+ /** Components that render data parts, keyed by their `name` */
8
+ dataComponents?: Record<string, Component>;
7
9
  /** Markdown renderer for text parts, see StreamMarkdown */
8
10
  render?: (markdown: string) => string;
9
11
  };
@@ -12,6 +14,9 @@ type __VLS_Slots = {
12
14
  part: ToolCallPart;
13
15
  addResult: (result: unknown) => void;
14
16
  }) => unknown;
17
+ data?: (props: {
18
+ part: DataPart;
19
+ }) => unknown;
15
20
  };
16
21
  declare const __VLS_component: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
17
22
  "tool-result": (payload: {
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),M=/^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;function h(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function y(o){const t=o.replace(/\r\n?/g,`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),C=/^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;function h(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function B(s){const t=s.replace(/\r\n?/g,`
2
2
  `).split(`
3
- `),l=[];let n=0;for(;n<t.length;){const r=t[n],m=/^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(r);if(m){const a=[];for(n++;n<t.length&&!t[n].trimStart().startsWith(m[1]);)a.push(t[n]),n++;n++;const i=m[2]?` class="language-${h(m[2])}"`:"";l.push(`<pre><code${i}>${h(a.join(`
4
- `))}</code></pre>`);continue}if(!r.trim()){n++;continue}const s=/^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(r);if(s){const a=s[1].length;l.push(`<h${a}>${p(s[2])}</h${a}>`),n++;continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(r)){l.push("<hr>"),n++;continue}if(/^\s*>/.test(r)){const a=[];for(;n<t.length&&/^\s*>/.test(t[n]);)a.push(t[n].replace(/^\s*>\s?/,"")),n++;l.push(`<blockquote>${y(a.join(`
5
- `))}</blockquote>`);continue}if(v(t,n)){const a=$(t[n]),i=$(t[n+1]).map(c=>c.endsWith(":")?c.startsWith(":")?"center":"right":c.startsWith(":")?"left":"");n+=2;const d=[];for(;n<t.length&&t[n].includes("|")&&t[n].trim();)d.push($(t[n])),n++;const k=(c,f,g)=>{const E=i[g]?` style="text-align:${i[g]}"`:"";return`<${c}${E}>${p(f)}</${c}>`};l.push("<table><thead><tr>"+a.map((c,f)=>k("th",c,f)).join("")+"</tr></thead><tbody>"+d.map(c=>"<tr>"+a.map((f,g)=>k("td",c[g]??"",g)).join("")+"</tr>").join("")+"</tbody></table>");continue}const u=/^\s*([-*+]|\d+[.)])\s+/.exec(r);if(u){const a=/\d/.test(u[1]),i=[];for(;n<t.length;){const c=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(t[n]);if(c&&/\d/.test(c[1])===a)i.push(c[2]);else if(t[n].trim()&&/^\s{2,}/.test(t[n])&&i.length>0)i[i.length-1]+=" "+t[n].trim();else break;n++}const d=a?"ol":"ul",k=a&&parseInt(u[1],10)!==1?` start="${parseInt(u[1],10)}"`:"";l.push(`<${d}${k}>${i.map(c=>`<li>${p(c)}</li>`).join("")}</${d}>`);continue}const _=[];for(;n<t.length&&t[n].trim()&&!b(t,n);)_.push(t[n].trim()),n++;l.push(`<p>${_.map(p).join("<br>")}</p>`)}return l.join(`
6
- `)}function p(o){return o.split(/(`+[^`]*`+)/).map((t,l)=>l%2===1?`<code>${h(t.replace(/^`+|`+$/g,""))}</code>`:x(h(t))).join("")}function x(o){return o.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(t,l,n)=>B(n)?`<img src="${n}" alt="${l}">`:l).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(t,l,n)=>B(n)?`<a href="${n}" target="_blank" rel="noopener noreferrer">${l}</a>`:l).replace(new RegExp("(\\*\\*|__)(?=\\S)(.+?)(?<=\\S)\\1","g"),"<strong>$2</strong>").replace(new RegExp("(?<![\\w*])\\*(?=\\S)(.+?)(?<=\\S)\\*(?![\\w*])","g"),"<em>$1</em>").replace(new RegExp("(?<![\\w_])_(?=\\S)(.+?)(?<=\\S)_(?![\\w_])","g"),"<em>$1</em>").replace(new RegExp("~~(?=\\S)(.+?)(?<=\\S)~~","g"),"<del>$1</del>")}function B(o){const t=o.replace(/&amp;/g,"&").replace(/&#(x?[0-9a-f]+);?/gi,"?");return M.test(t.trim())}function $(o){return o.trim().replace(/^\||\|$/g,"").split("|").map(t=>t.trim())}function v(o,t){return o[t].includes("|")&&t+1<o.length&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(o[t+1])}function b(o,t){const l=o[t];return/^\s*(`{3,}|~{3,})/.test(l)||/^#{1,6}\s/.test(l)||/^\s*>/.test(l)||/^\s*([-*+]|\d+[.)])\s+/.test(l)||/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)||v(o,t)}const I=["innerHTML"],j={key:0,class:"vue-llm-cursor","aria-hidden":"true"},C=e.defineComponent({__name:"StreamMarkdown",props:{content:{},streaming:{type:Boolean},render:{type:Function}},setup(o){const t=o,l=e.computed(()=>(t.render??y)(t.content));return(n,r)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createElementVNode("div",{class:"vue-llm-markdown",innerHTML:l.value},null,8,I),o.streaming?(e.openBlock(),e.createElementBlock("span",j,"▊")):e.createCommentVNode("",!0)],64))}}),S=(o,t)=>{const l=o.__vccOpts||o;for(const[n,r]of t)l[n]=r;return l},w=S(C,[["__scopeId","data-v-f225ccf4"]]),F=["data-role"],N={key:0,class:"vue-llm-text"},T=["open"],L=["src","alt"],R={key:1,class:"vue-llm-file"},P=["href"],q=e.defineComponent({__name:"MessageParts",props:{message:{},components:{},render:{type:Function}},emits:["tool-result"],setup(o,{emit:t}){const l=t,n=r=>({toolCallId:r.toolCallId,toolName:r.toolName,args:r.args,state:r.state,result:r.result,error:r.error,addResult:m=>l("tool-result",{toolCallId:r.toolCallId,result:m})});return(r,m)=>(e.openBlock(),e.createElementBlock("div",{class:"vue-llm-message","data-role":o.message.role},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(o.message.parts,(s,u)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:s.type==="tool-call"?s.toolCallId:u},[s.type==="text"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[o.message.role==="user"?(e.openBlock(),e.createElementBlock("div",N,e.toDisplayString(s.text),1)):(e.openBlock(),e.createBlock(w,{key:1,content:s.text,streaming:s.state==="streaming",render:o.render},null,8,["content","streaming","render"]))],64)):s.type==="reasoning"?(e.openBlock(),e.createElementBlock("details",{key:1,class:"vue-llm-reasoning",open:s.state==="streaming"},[m[0]||(m[0]=e.createElementVNode("summary",null,"Reasoning",-1)),e.createElementVNode("div",null,e.toDisplayString(s.text),1)],8,T)):s.type==="tool-call"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[o.components?.[s.toolName]?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(o.components[s.toolName]),e.mergeProps({key:0,ref_for:!0},n(s)),null,16)):e.renderSlot(r.$slots,"tool",{part:s,addResult:n(s).addResult},void 0,!0,1)],64)):s.type==="file"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[s.mediaType.startsWith("image/")?(e.openBlock(),e.createElementBlock("img",{key:0,class:"vue-llm-file",src:s.url,alt:s.filename??""},null,8,L)):(e.openBlock(),e.createElementBlock("span",R,e.toDisplayString(s.filename??s.mediaType),1))],64)):s.type==="source"&&/^https?:/i.test(s.url)?(e.openBlock(),e.createElementBlock("a",{key:4,class:"vue-llm-source",href:s.url,target:"_blank",rel:"noopener noreferrer"},e.toDisplayString(s.title??s.url),9,P)):e.createCommentVNode("",!0)],64))),128))],8,F))}}),D=S(q,[["__scopeId","data-v-f0d8c768"]]);exports.MessageParts=D;exports.StreamMarkdown=w;exports.escapeHTML=h;exports.renderInline=p;exports.renderMarkdown=y;
3
+ `),l=[];let n=0;for(;n<t.length;){const i=t[n],r=/^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(i);if(r){const a=[];for(n++;n<t.length&&!t[n].trimStart().startsWith(r[1]);)a.push(t[n]),n++;n++;const u=r[2]?` class="language-${h(r[2])}"`:"";l.push(`<pre><code${u}>${h(a.join(`
4
+ `))}</code></pre>`);continue}if(!i.trim()){n++;continue}const m=/^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(i);if(m){const a=m[1].length;l.push(`<h${a}>${p(m[2])}</h${a}>`),n++;continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(i)){l.push("<hr>"),n++;continue}if(/^\s*>/.test(i)){const a=[];for(;n<t.length&&/^\s*>/.test(t[n]);)a.push(t[n].replace(/^\s*>\s?/,"")),n++;l.push(`<blockquote>${B(a.join(`
5
+ `))}</blockquote>`);continue}if(v(t,n)){const a=y(t[n]),u=y(t[n+1]).map(c=>c.endsWith(":")?c.startsWith(":")?"center":"right":c.startsWith(":")?"left":"");n+=2;const d=[];for(;n<t.length&&t[n].includes("|")&&t[n].trim();)d.push(y(t[n])),n++;const f=(c,$,g)=>{const E=u[g]?` style="text-align:${u[g]}"`:"";return`<${c}${E}>${p($)}</${c}>`};l.push("<table><thead><tr>"+a.map((c,$)=>f("th",c,$)).join("")+"</tr></thead><tbody>"+d.map(c=>"<tr>"+a.map(($,g)=>f("td",c[g]??"",g)).join("")+"</tr>").join("")+"</tbody></table>");continue}const o=/^\s*([-*+]|\d+[.)])\s+/.exec(i);if(o){const a=/\d/.test(o[1]),u=[];for(;n<t.length;){const c=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(t[n]);if(c&&/\d/.test(c[1])===a)u.push(c[2]);else if(t[n].trim()&&/^\s{2,}/.test(t[n])&&u.length>0)u[u.length-1]+=" "+t[n].trim();else break;n++}const d=a?"ol":"ul",f=a&&parseInt(o[1],10)!==1?` start="${parseInt(o[1],10)}"`:"";l.push(`<${d}${f}>${u.map(c=>`<li>${p(c)}</li>`).join("")}</${d}>`);continue}const k=[];for(;n<t.length&&t[n].trim()&&!b(t,n);)k.push(t[n].trim()),n++;l.push(`<p>${k.map(p).join("<br>")}</p>`)}return l.join(`
6
+ `)}function p(s){return s.split(/(`+[^`]*`+)/).map((t,l)=>l%2===1?`<code>${h(t.replace(/^`+|`+$/g,""))}</code>`:M(h(t))).join("")}function M(s){return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(t,l,n)=>_(n)?`<img src="${n}" alt="${l}">`:l).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(t,l,n)=>_(n)?`<a href="${n}" target="_blank" rel="noopener noreferrer">${l}</a>`:l).replace(new RegExp("(\\*\\*|__)(?=\\S)(.+?)(?<=\\S)\\1","g"),"<strong>$2</strong>").replace(new RegExp("(?<![\\w*])\\*(?=\\S)(.+?)(?<=\\S)\\*(?![\\w*])","g"),"<em>$1</em>").replace(new RegExp("(?<![\\w_])_(?=\\S)(.+?)(?<=\\S)_(?![\\w_])","g"),"<em>$1</em>").replace(new RegExp("~~(?=\\S)(.+?)(?<=\\S)~~","g"),"<del>$1</del>")}function _(s){const t=s.replace(/&amp;/g,"&").replace(/&#(x?[0-9a-f]+);?/gi,"?");return C.test(t.trim())}function y(s){return s.trim().replace(/^\||\|$/g,"").split("|").map(t=>t.trim())}function v(s,t){return s[t].includes("|")&&t+1<s.length&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(s[t+1])}function b(s,t){const l=s[t];return/^\s*(`{3,}|~{3,})/.test(l)||/^#{1,6}\s/.test(l)||/^\s*>/.test(l)||/^\s*([-*+]|\d+[.)])\s+/.test(l)||/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)||v(s,t)}const x=["innerHTML"],I={key:0,class:"vue-llm-cursor","aria-hidden":"true"},j=e.defineComponent({__name:"StreamMarkdown",props:{content:{},streaming:{type:Boolean},render:{type:Function}},setup(s){const t=s,l=e.computed(()=>(t.render??B)(t.content));return(n,i)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createElementVNode("div",{class:"vue-llm-markdown",innerHTML:l.value},null,8,x),s.streaming?(e.openBlock(),e.createElementBlock("span",I,"▊")):e.createCommentVNode("",!0)],64))}}),S=(s,t)=>{const l=s.__vccOpts||s;for(const[n,i]of t)l[n]=i;return l},w=S(j,[["__scopeId","data-v-f225ccf4"]]),F=["data-role"],N={key:0,class:"vue-llm-text"},T=["open"],L=["src","alt"],R={key:1,class:"vue-llm-file"},D=["href"],P=e.defineComponent({__name:"MessageParts",props:{message:{},components:{},dataComponents:{},render:{type:Function}},emits:["tool-result"],setup(s,{emit:t}){const l=t,n=(r,m)=>r.type==="tool-call"?r.toolCallId:r.type==="data"&&r.id!==void 0?`data:${r.name}:${r.id}`:m,i=r=>({toolCallId:r.toolCallId,toolName:r.toolName,args:r.args,state:r.state,result:r.result,error:r.error,addResult:m=>l("tool-result",{toolCallId:r.toolCallId,result:m})});return(r,m)=>(e.openBlock(),e.createElementBlock("div",{class:"vue-llm-message","data-role":s.message.role},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(s.message.parts,(o,k)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:n(o,k)},[o.type==="text"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[s.message.role==="user"?(e.openBlock(),e.createElementBlock("div",N,e.toDisplayString(o.text),1)):(e.openBlock(),e.createBlock(w,{key:1,content:o.text,streaming:o.state==="streaming",render:s.render},null,8,["content","streaming","render"]))],64)):o.type==="reasoning"?(e.openBlock(),e.createElementBlock("details",{key:1,class:"vue-llm-reasoning",open:o.state==="streaming"},[m[0]||(m[0]=e.createElementVNode("summary",null,"Reasoning",-1)),e.createElementVNode("div",null,e.toDisplayString(o.text),1)],8,T)):o.type==="tool-call"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[s.components?.[o.toolName]?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(s.components[o.toolName]),e.mergeProps({key:0,ref_for:!0},i(o)),null,16)):e.renderSlot(r.$slots,"tool",{part:o,addResult:i(o).addResult},void 0,!0,1)],64)):o.type==="data"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[s.dataComponents?.[o.name]?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(s.dataComponents[o.name]),{key:0,name:o.name,data:o.data},null,8,["name","data"])):e.renderSlot(r.$slots,"data",{part:o},void 0,!0,1)],64)):o.type==="file"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:4},[o.mediaType.startsWith("image/")?(e.openBlock(),e.createElementBlock("img",{key:0,class:"vue-llm-file",src:o.url,alt:o.filename??""},null,8,L)):(e.openBlock(),e.createElementBlock("span",R,e.toDisplayString(o.filename??o.mediaType),1))],64)):o.type==="source"&&/^https?:/i.test(o.url)?(e.openBlock(),e.createElementBlock("a",{key:5,class:"vue-llm-source",href:o.url,target:"_blank",rel:"noopener noreferrer"},e.toDisplayString(o.title??o.url),9,D)):e.createCommentVNode("",!0)],64))),128))],8,F))}}),q=S(P,[["__scopeId","data-v-3868ad67"]]);exports.MessageParts=q;exports.StreamMarkdown=w;exports.escapeHTML=h;exports.renderInline=p;exports.renderMarkdown=B;
@@ -1,112 +1,112 @@
1
- import { defineComponent as I, computed as N, openBlock as a, createElementBlock as i, Fragment as g, createElementVNode as w, createCommentVNode as j, renderList as T, toDisplayString as _, createBlock as x, resolveDynamicComponent as B, mergeProps as W, renderSlot as q } from "vue";
1
+ import { defineComponent as j, computed as B, openBlock as r, createElementBlock as i, Fragment as g, createElementVNode as x, createCommentVNode as M, renderList as W, toDisplayString as _, createBlock as w, resolveDynamicComponent as C, mergeProps as q, renderSlot as b } from "vue";
2
2
  const E = /^(?:https?:|mailto:|\/(?!\/)|#|\.\.?\/)/i;
3
- function k(s) {
3
+ function v(s) {
4
4
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
5
5
  }
6
- function M(s) {
6
+ function R(s) {
7
7
  const e = s.replace(/\r\n?/g, `
8
8
  `).split(`
9
9
  `), o = [];
10
10
  let t = 0;
11
11
  for (; t < e.length; ) {
12
- const l = e[t], m = /^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(l);
13
- if (m) {
12
+ const u = e[t], l = /^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(u);
13
+ if (l) {
14
14
  const c = [];
15
- for (t++; t < e.length && !e[t].trimStart().startsWith(m[1]); )
15
+ for (t++; t < e.length && !e[t].trimStart().startsWith(l[1]); )
16
16
  c.push(e[t]), t++;
17
17
  t++;
18
- const u = m[2] ? ` class="language-${k(m[2])}"` : "";
19
- o.push(`<pre><code${u}>${k(c.join(`
18
+ const d = l[2] ? ` class="language-${v(l[2])}"` : "";
19
+ o.push(`<pre><code${d}>${v(c.join(`
20
20
  `))}</code></pre>`);
21
21
  continue;
22
22
  }
23
- if (!l.trim()) {
23
+ if (!u.trim()) {
24
24
  t++;
25
25
  continue;
26
26
  }
27
- const n = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(l);
28
- if (n) {
29
- const c = n[1].length;
30
- o.push(`<h${c}>${y(n[2])}</h${c}>`), t++;
27
+ const m = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(u);
28
+ if (m) {
29
+ const c = m[1].length;
30
+ o.push(`<h${c}>${k(m[2])}</h${c}>`), t++;
31
31
  continue;
32
32
  }
33
- if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)) {
33
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(u)) {
34
34
  o.push("<hr>"), t++;
35
35
  continue;
36
36
  }
37
- if (/^\s*>/.test(l)) {
37
+ if (/^\s*>/.test(u)) {
38
38
  const c = [];
39
39
  for (; t < e.length && /^\s*>/.test(e[t]); )
40
40
  c.push(e[t].replace(/^\s*>\s?/, "")), t++;
41
- o.push(`<blockquote>${M(c.join(`
41
+ o.push(`<blockquote>${R(c.join(`
42
42
  `))}</blockquote>`);
43
43
  continue;
44
44
  }
45
- if (C(e, t)) {
46
- const c = v(e[t]), u = v(e[t + 1]).map((r) => r.endsWith(":") ? r.startsWith(":") ? "center" : "right" : r.startsWith(":") ? "left" : "");
45
+ if (L(e, t)) {
46
+ const c = S(e[t]), d = S(e[t + 1]).map((a) => a.endsWith(":") ? a.startsWith(":") ? "center" : "right" : a.startsWith(":") ? "left" : "");
47
47
  t += 2;
48
48
  const h = [];
49
49
  for (; t < e.length && e[t].includes("|") && e[t].trim(); )
50
- h.push(v(e[t])), t++;
51
- const f = (r, $, p) => {
52
- const L = u[p] ? ` style="text-align:${u[p]}"` : "";
53
- return `<${r}${L}>${y($)}</${r}>`;
50
+ h.push(S(e[t])), t++;
51
+ const $ = (a, y, p) => {
52
+ const T = d[p] ? ` style="text-align:${d[p]}"` : "";
53
+ return `<${a}${T}>${k(y)}</${a}>`;
54
54
  };
55
55
  o.push(
56
- "<table><thead><tr>" + c.map((r, $) => f("th", r, $)).join("") + "</tr></thead><tbody>" + h.map((r) => "<tr>" + c.map(($, p) => f("td", r[p] ?? "", p)).join("") + "</tr>").join("") + "</tbody></table>"
56
+ "<table><thead><tr>" + c.map((a, y) => $("th", a, y)).join("") + "</tr></thead><tbody>" + h.map((a) => "<tr>" + c.map((y, p) => $("td", a[p] ?? "", p)).join("") + "</tr>").join("") + "</tbody></table>"
57
57
  );
58
58
  continue;
59
59
  }
60
- const d = /^\s*([-*+]|\d+[.)])\s+/.exec(l);
61
- if (d) {
62
- const c = /\d/.test(d[1]), u = [];
60
+ const n = /^\s*([-*+]|\d+[.)])\s+/.exec(u);
61
+ if (n) {
62
+ const c = /\d/.test(n[1]), d = [];
63
63
  for (; t < e.length; ) {
64
- const r = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(e[t]);
65
- if (r && /\d/.test(r[1]) === c)
66
- u.push(r[2]);
67
- else if (e[t].trim() && /^\s{2,}/.test(e[t]) && u.length > 0)
68
- u[u.length - 1] += " " + e[t].trim();
64
+ const a = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(e[t]);
65
+ if (a && /\d/.test(a[1]) === c)
66
+ d.push(a[2]);
67
+ else if (e[t].trim() && /^\s{2,}/.test(e[t]) && d.length > 0)
68
+ d[d.length - 1] += " " + e[t].trim();
69
69
  else
70
70
  break;
71
71
  t++;
72
72
  }
73
- const h = c ? "ol" : "ul", f = c && parseInt(d[1], 10) !== 1 ? ` start="${parseInt(d[1], 10)}"` : "";
74
- o.push(`<${h}${f}>${u.map((r) => `<li>${y(r)}</li>`).join("")}</${h}>`);
73
+ const h = c ? "ol" : "ul", $ = c && parseInt(n[1], 10) !== 1 ? ` start="${parseInt(n[1], 10)}"` : "";
74
+ o.push(`<${h}${$}>${d.map((a) => `<li>${k(a)}</li>`).join("")}</${h}>`);
75
75
  continue;
76
76
  }
77
- const S = [];
77
+ const f = [];
78
78
  for (; t < e.length && e[t].trim() && !P(e, t); )
79
- S.push(e[t].trim()), t++;
80
- o.push(`<p>${S.map(y).join("<br>")}</p>`);
79
+ f.push(e[t].trim()), t++;
80
+ o.push(`<p>${f.map(k).join("<br>")}</p>`);
81
81
  }
82
82
  return o.join(`
83
83
  `);
84
84
  }
85
- function y(s) {
86
- return s.split(/(`+[^`]*`+)/).map((e, o) => o % 2 === 1 ? `<code>${k(e.replace(/^`+|`+$/g, ""))}</code>` : F(k(e))).join("");
85
+ function k(s) {
86
+ return s.split(/(`+[^`]*`+)/).map((e, o) => o % 2 === 1 ? `<code>${v(e.replace(/^`+|`+$/g, ""))}</code>` : F(v(e))).join("");
87
87
  }
88
88
  function F(s) {
89
- return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (e, o, t) => b(t) ? `<img src="${t}" alt="${o}">` : o).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (e, o, t) => b(t) ? `<a href="${t}" target="_blank" rel="noopener noreferrer">${o}</a>` : o).replace(new RegExp("(\\*\\*|__)(?=\\S)(.+?)(?<=\\S)\\1", "g"), "<strong>$2</strong>").replace(new RegExp("(?<![\\w*])\\*(?=\\S)(.+?)(?<=\\S)\\*(?![\\w*])", "g"), "<em>$1</em>").replace(new RegExp("(?<![\\w_])_(?=\\S)(.+?)(?<=\\S)_(?![\\w_])", "g"), "<em>$1</em>").replace(new RegExp("~~(?=\\S)(.+?)(?<=\\S)~~", "g"), "<del>$1</del>");
89
+ return s.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (e, o, t) => I(t) ? `<img src="${t}" alt="${o}">` : o).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (e, o, t) => I(t) ? `<a href="${t}" target="_blank" rel="noopener noreferrer">${o}</a>` : o).replace(new RegExp("(\\*\\*|__)(?=\\S)(.+?)(?<=\\S)\\1", "g"), "<strong>$2</strong>").replace(new RegExp("(?<![\\w*])\\*(?=\\S)(.+?)(?<=\\S)\\*(?![\\w*])", "g"), "<em>$1</em>").replace(new RegExp("(?<![\\w_])_(?=\\S)(.+?)(?<=\\S)_(?![\\w_])", "g"), "<em>$1</em>").replace(new RegExp("~~(?=\\S)(.+?)(?<=\\S)~~", "g"), "<del>$1</del>");
90
90
  }
91
- function b(s) {
91
+ function I(s) {
92
92
  const e = s.replace(/&amp;/g, "&").replace(/&#(x?[0-9a-f]+);?/gi, "?");
93
93
  return E.test(e.trim());
94
94
  }
95
- function v(s) {
95
+ function S(s) {
96
96
  return s.trim().replace(/^\||\|$/g, "").split("|").map((e) => e.trim());
97
97
  }
98
- function C(s, e) {
98
+ function L(s, e) {
99
99
  return s[e].includes("|") && e + 1 < s.length && /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(s[e + 1]);
100
100
  }
101
101
  function P(s, e) {
102
102
  const o = s[e];
103
- return /^\s*(`{3,}|~{3,})/.test(o) || /^#{1,6}\s/.test(o) || /^\s*>/.test(o) || /^\s*([-*+]|\d+[.)])\s+/.test(o) || /^\s*([-*_])(\s*\1){2,}\s*$/.test(o) || C(s, e);
103
+ return /^\s*(`{3,}|~{3,})/.test(o) || /^#{1,6}\s/.test(o) || /^\s*>/.test(o) || /^\s*([-*+]|\d+[.)])\s+/.test(o) || /^\s*([-*_])(\s*\1){2,}\s*$/.test(o) || L(s, e);
104
104
  }
105
105
  const H = ["innerHTML"], D = {
106
106
  key: 0,
107
107
  class: "vue-llm-cursor",
108
108
  "aria-hidden": "true"
109
- }, U = /* @__PURE__ */ I({
109
+ }, U = /* @__PURE__ */ j({
110
110
  __name: "StreamMarkdown",
111
111
  props: {
112
112
  content: {},
@@ -114,36 +114,37 @@ const H = ["innerHTML"], D = {
114
114
  render: { type: Function }
115
115
  },
116
116
  setup(s) {
117
- const e = s, o = N(() => (e.render ?? M)(e.content));
118
- return (t, l) => (a(), i(g, null, [
119
- w("div", {
117
+ const e = s, o = B(() => (e.render ?? R)(e.content));
118
+ return (t, u) => (r(), i(g, null, [
119
+ x("div", {
120
120
  class: "vue-llm-markdown",
121
121
  innerHTML: o.value
122
122
  }, null, 8, H),
123
- s.streaming ? (a(), i("span", D, "▊")) : j("", !0)
123
+ s.streaming ? (r(), i("span", D, "▊")) : M("", !0)
124
124
  ], 64));
125
125
  }
126
- }), R = (s, e) => {
126
+ }), N = (s, e) => {
127
127
  const o = s.__vccOpts || s;
128
- for (const [t, l] of e)
129
- o[t] = l;
128
+ for (const [t, u] of e)
129
+ o[t] = u;
130
130
  return o;
131
- }, V = /* @__PURE__ */ R(U, [["__scopeId", "data-v-f225ccf4"]]), A = ["data-role"], O = {
131
+ }, V = /* @__PURE__ */ N(U, [["__scopeId", "data-v-f225ccf4"]]), A = ["data-role"], K = {
132
132
  key: 0,
133
133
  class: "vue-llm-text"
134
- }, z = ["open"], G = ["src", "alt"], J = {
134
+ }, O = ["open"], z = ["src", "alt"], G = {
135
135
  key: 1,
136
136
  class: "vue-llm-file"
137
- }, K = ["href"], Q = /* @__PURE__ */ I({
137
+ }, J = ["href"], Q = /* @__PURE__ */ j({
138
138
  __name: "MessageParts",
139
139
  props: {
140
140
  message: {},
141
141
  components: {},
142
+ dataComponents: {},
142
143
  render: { type: Function }
143
144
  },
144
145
  emits: ["tool-result"],
145
146
  setup(s, { emit: e }) {
146
- const o = e, t = (l) => ({
147
+ const o = e, t = (l, m) => l.type === "tool-call" ? l.toolCallId : l.type === "data" && l.id !== void 0 ? `data:${l.name}:${l.id}` : m, u = (l) => ({
147
148
  toolCallId: l.toolCallId,
148
149
  toolName: l.toolName,
149
150
  args: l.args,
@@ -152,57 +153,63 @@ const H = ["innerHTML"], D = {
152
153
  error: l.error,
153
154
  addResult: (m) => o("tool-result", { toolCallId: l.toolCallId, result: m })
154
155
  });
155
- return (l, m) => (a(), i("div", {
156
+ return (l, m) => (r(), i("div", {
156
157
  class: "vue-llm-message",
157
158
  "data-role": s.message.role
158
159
  }, [
159
- (a(!0), i(g, null, T(s.message.parts, (n, d) => (a(), i(g, {
160
- key: n.type === "tool-call" ? n.toolCallId : d
160
+ (r(!0), i(g, null, W(s.message.parts, (n, f) => (r(), i(g, {
161
+ key: t(n, f)
161
162
  }, [
162
- n.type === "text" ? (a(), i(g, { key: 0 }, [
163
- s.message.role === "user" ? (a(), i("div", O, _(n.text), 1)) : (a(), x(V, {
163
+ n.type === "text" ? (r(), i(g, { key: 0 }, [
164
+ s.message.role === "user" ? (r(), i("div", K, _(n.text), 1)) : (r(), w(V, {
164
165
  key: 1,
165
166
  content: n.text,
166
167
  streaming: n.state === "streaming",
167
168
  render: s.render
168
169
  }, null, 8, ["content", "streaming", "render"]))
169
- ], 64)) : n.type === "reasoning" ? (a(), i("details", {
170
+ ], 64)) : n.type === "reasoning" ? (r(), i("details", {
170
171
  key: 1,
171
172
  class: "vue-llm-reasoning",
172
173
  open: n.state === "streaming"
173
174
  }, [
174
- m[0] || (m[0] = w("summary", null, "Reasoning", -1)),
175
- w("div", null, _(n.text), 1)
176
- ], 8, z)) : n.type === "tool-call" ? (a(), i(g, { key: 2 }, [
177
- s.components?.[n.toolName] ? (a(), x(B(s.components[n.toolName]), W({
175
+ m[0] || (m[0] = x("summary", null, "Reasoning", -1)),
176
+ x("div", null, _(n.text), 1)
177
+ ], 8, O)) : n.type === "tool-call" ? (r(), i(g, { key: 2 }, [
178
+ s.components?.[n.toolName] ? (r(), w(C(s.components[n.toolName]), q({
178
179
  key: 0,
179
180
  ref_for: !0
180
- }, t(n)), null, 16)) : q(l.$slots, "tool", {
181
+ }, u(n)), null, 16)) : b(l.$slots, "tool", {
181
182
  part: n,
182
- addResult: t(n).addResult
183
+ addResult: u(n).addResult
183
184
  }, void 0, !0, 1)
184
- ], 64)) : n.type === "file" ? (a(), i(g, { key: 3 }, [
185
- n.mediaType.startsWith("image/") ? (a(), i("img", {
185
+ ], 64)) : n.type === "data" ? (r(), i(g, { key: 3 }, [
186
+ s.dataComponents?.[n.name] ? (r(), w(C(s.dataComponents[n.name]), {
187
+ key: 0,
188
+ name: n.name,
189
+ data: n.data
190
+ }, null, 8, ["name", "data"])) : b(l.$slots, "data", { part: n }, void 0, !0, 1)
191
+ ], 64)) : n.type === "file" ? (r(), i(g, { key: 4 }, [
192
+ n.mediaType.startsWith("image/") ? (r(), i("img", {
186
193
  key: 0,
187
194
  class: "vue-llm-file",
188
195
  src: n.url,
189
196
  alt: n.filename ?? ""
190
- }, null, 8, G)) : (a(), i("span", J, _(n.filename ?? n.mediaType), 1))
191
- ], 64)) : n.type === "source" && /^https?:/i.test(n.url) ? (a(), i("a", {
192
- key: 4,
197
+ }, null, 8, z)) : (r(), i("span", G, _(n.filename ?? n.mediaType), 1))
198
+ ], 64)) : n.type === "source" && /^https?:/i.test(n.url) ? (r(), i("a", {
199
+ key: 5,
193
200
  class: "vue-llm-source",
194
201
  href: n.url,
195
202
  target: "_blank",
196
203
  rel: "noopener noreferrer"
197
- }, _(n.title ?? n.url), 9, K)) : j("", !0)
204
+ }, _(n.title ?? n.url), 9, J)) : M("", !0)
198
205
  ], 64))), 128))
199
206
  ], 8, A));
200
207
  }
201
- }), Y = /* @__PURE__ */ R(Q, [["__scopeId", "data-v-f0d8c768"]]);
208
+ }), Y = /* @__PURE__ */ N(Q, [["__scopeId", "data-v-3868ad67"]]);
202
209
  export {
203
210
  Y as MessageParts,
204
211
  V as StreamMarkdown,
205
- k as escapeHTML,
206
- y as renderInline,
207
- M as renderMarkdown
212
+ v as escapeHTML,
213
+ k as renderInline,
214
+ R as renderMarkdown
208
215
  };
@@ -0,0 +1,77 @@
1
+ import { type MaybeRefOrGetter } from '../utils/vue.js';
2
+ import type { MCPState } from './use-mcp.js';
3
+ /** Options shared by `useMCP` and `useMCPServers` when they talk to `createMCPConnector` */
4
+ export interface MCPServerModeOptions {
5
+ /** Where `createMCPConnector`'s handler is mounted, e.g. `'/api/mcp'` (its `basePath`) */
6
+ server: string;
7
+ /** Used for every request to `server`; default `globalThis.fetch` */
8
+ fetch?: typeof fetch;
9
+ /** Sent with every request to `server`, e.g. `{ Authorization: 'Bearer …' }` for bearer-token apps */
10
+ headers?: MaybeRefOrGetter<Record<string, string> | undefined>;
11
+ /** Default `'include'`, so session cookies reach a backend on another origin */
12
+ credentials?: RequestCredentials;
13
+ }
14
+ /** One server in `GET {server}/servers` (`MCPConnectorEntry`) */
15
+ export interface MCPBackendEntry {
16
+ id: string;
17
+ name: string;
18
+ url: string;
19
+ custom: boolean;
20
+ enabled: boolean;
21
+ state: 'connected' | 'needs-auth' | 'unsupported' | 'error';
22
+ error?: string;
23
+ }
24
+ export interface MCPBackendAPI {
25
+ list(): Promise<MCPBackendEntry[]>;
26
+ /** Adds a server; when the backend already has its URL, resolves with that server's id */
27
+ add(body: {
28
+ url: string;
29
+ name?: string;
30
+ }): Promise<{
31
+ id: string;
32
+ servers: MCPBackendEntry[];
33
+ }>;
34
+ remove(id: string): Promise<MCPBackendEntry[]>;
35
+ action(id: string, verb: 'enable' | 'disable' | 'logout'): Promise<MCPBackendEntry[]>;
36
+ /** The provider's sign-in URL and the flow's `state`, or `null` when the server is already connected */
37
+ authorize(id: string): Promise<{
38
+ url: string;
39
+ state: string;
40
+ } | null>;
41
+ /** Finishes a sign-in with the authorization response relayed by the callback page */
42
+ complete(id: string, body: {
43
+ state: string;
44
+ code?: string;
45
+ error?: string;
46
+ errorDescription?: string;
47
+ }): Promise<MCPBackendEntry[]>;
48
+ }
49
+ /** The routes of `createMCPConnector`; nothing is fetched until a method is called */
50
+ export declare function createMCPBackend(o: MCPServerModeOptions): MCPBackendAPI;
51
+ /**
52
+ * A backend entry as a `useMCP` state: `connected` → `ready`, `needs-auth` → `needs-auth`,
53
+ * `unsupported`/`error` → `failed` with the entry's error; a disabled server is `idle`
54
+ * (its tools don't run), except an unsupported one, which can never connect.
55
+ */
56
+ export declare function mapBackendState(e: MCPBackendEntry): {
57
+ state: MCPState;
58
+ error: Error | undefined;
59
+ };
60
+ export declare function closePopup(popup: Window | null): void;
61
+ /**
62
+ * Signs in to server `id` through the backend in `popup`, which the caller opened with
63
+ * `about:blank` within the user gesture: POSTs `/authorize`, navigates the popup to the
64
+ * provider and waits for the callback page's message (same `id` and `state`) or for the popup
65
+ * to close. The callback page completes nothing: the message's authorization response is
66
+ * POSTed to `/complete` with this user's session, so the backend can check that the flow is
67
+ * theirs. Resolves when the flow is over (the caller then refetches the state); rejects when
68
+ * a request fails or `signal` aborts.
69
+ */
70
+ export declare function authorizeThroughBackend(api: MCPBackendAPI, o: {
71
+ id: string;
72
+ server: string;
73
+ popup: Window | null;
74
+ signal: AbortSignal;
75
+ onUrl: (url: string) => void;
76
+ }): Promise<void>;
77
+ export declare const toError: (e: unknown) => Error;
@@ -21,7 +21,7 @@ export interface UseChatOptions {
21
21
  body?: MaybeRef<Record<string, unknown>>;
22
22
  providerOptions?: Record<string, unknown>;
23
23
  /** Tools with `execute` run automatically; others go to `onToolCall` or wait for `addToolResult` */
24
- tools?: ChatTool[];
24
+ tools?: MaybeRefOrGetter<ChatTool[] | undefined>;
25
25
  /** Return a result to resolve the call, or `undefined` to resolve it later with `addToolResult` */
26
26
  onToolCall?: (toolCall: {
27
27
  toolCallId: string;
@@ -0,0 +1,83 @@
1
+ import { type Ref } from 'vue';
2
+ import type { MCPServerPreset, MCPToolFilter } from '../mcp/servers.js';
3
+ import { type MCPStorageOption } from '../mcp/storage.js';
4
+ import type { MCPTool } from '../mcp/tools.js';
5
+ import { type MCPServerModeOptions } from './mcp-server-mode.js';
6
+ import { type MCPState } from './use-mcp.js';
7
+ /** A catalog entry that isn't a preset: any Streamable HTTP endpoint */
8
+ export interface MCPServerEntry extends MCPToolFilter {
9
+ /** Stable id; also the prefix of the server's tools (`docs_search`) */
10
+ id: string;
11
+ url: string;
12
+ /** Shown in the list; default the id */
13
+ name?: string;
14
+ }
15
+ export interface UseMCPServersOptions extends Partial<MCPServerModeOptions> {
16
+ /**
17
+ * Servers the user can turn on and off; all are off until the user enables them.
18
+ * Optional with `server`: the backend's list is the source of truth (shown until it loads).
19
+ * `include` / `exclude` limit a server's tools (browser mode; in server mode set them on the connector)
20
+ */
21
+ catalog?: ((MCPServerPreset & MCPToolFilter) | MCPServerEntry)[];
22
+ /** Lets the user add servers by URL with `add()`. Default `false`. With `server` the backend's `allowCustom` decides */
23
+ allowCustom?: boolean;
24
+ /** OAuth redirect URI for every server; default `${location.origin}/mcp/callback` */
25
+ callbackUrl?: string;
26
+ /** Shown on the providers' consent screens; default `document.title` */
27
+ clientName?: string;
28
+ /** Where tokens and the list (enabled servers, added servers) are kept. Default `'local'` */
29
+ storage?: MCPStorageOption;
30
+ }
31
+ export interface MCPServerItem {
32
+ readonly id: string;
33
+ readonly name: string;
34
+ readonly url: string;
35
+ /** Added by the user with `add()` */
36
+ readonly custom: boolean;
37
+ readonly enabled: boolean;
38
+ readonly state: MCPState;
39
+ readonly error: Error | undefined;
40
+ /** The authorization URL while `authorizing`; render it as a link when the popup was blocked */
41
+ readonly authUrl: string | undefined;
42
+ /** This server's tools, prefixed with its id; `[]` until `ready` */
43
+ readonly tools: MCPTool[];
44
+ }
45
+ export interface UseMCPServersReturn {
46
+ list: Readonly<Ref<MCPServerItem[]>>;
47
+ /** The tools of every enabled server in `ready`, ready for `useChat({ tools })` */
48
+ tools: Readonly<Ref<MCPTool[]>>;
49
+ /** Turns a server on and connects it with stored credentials (never opens a popup) */
50
+ enable: (id: string) => void;
51
+ /** Turns a server off: closes its session and keeps its credentials */
52
+ disable: (id: string) => Promise<void>;
53
+ /** Signs in to a server through a popup (enabling it); call it from a user gesture (click) */
54
+ authorize: (id: string) => Promise<void>;
55
+ /**
56
+ * Adds a server by URL (needs `allowCustom`) and returns its id, derived from the host.
57
+ * An invalid URL doesn't throw: the entry is added in `failed` with the reason in `error`.
58
+ * With `server` the backend assigns the id; the returned one is derived the same way.
59
+ */
60
+ add: (server: {
61
+ url: string;
62
+ name?: string;
63
+ }) => string;
64
+ /** Forgets a server added with `add()` and its tokens; throws for catalog servers */
65
+ remove: (id: string) => Promise<void>;
66
+ /** Reconnects every enabled server; with `server`, refetches the list from the backend */
67
+ refresh: () => Promise<void>;
68
+ }
69
+ /**
70
+ * Manages several remote MCP servers: a catalog the developer defines (the user turns entries
71
+ * on and off) and, with `allowCustom`, servers the user adds by URL. One `useMCP` per server;
72
+ * each server's tools are prefixed with its id so they never collide.
73
+ *
74
+ * ```ts
75
+ * const connectors = useMCPServers({ catalog: [mcpServers.notion, mcpServers.linear], allowCustom: true })
76
+ * useChat({ provider, tools: () => connectors.tools.value })
77
+ * ```
78
+ *
79
+ * With `server: '/api/mcp'` the list, states and actions come from `createMCPConnector` on your
80
+ * backend, which keeps the tokens and runs the tools (`tools` stays `[]`). The list is refetched
81
+ * on `refresh()`, when the window regains focus and after a sign-in popup closes.
82
+ */
83
+ export declare function useMCPServers(o?: UseMCPServersOptions): UseMCPServersReturn;
@@ -0,0 +1,69 @@
1
+ import { type Ref } from 'vue';
2
+ import { type MCPStorageOption } from '../mcp/storage.js';
3
+ import { type MCPTool } from '../mcp/tools.js';
4
+ import { type MCPServerModeOptions } from './mcp-server-mode.js';
5
+ export type MCPState = 'idle' | 'connecting' | 'needs-auth' | 'authorizing' | 'ready' | 'failed';
6
+ /** Browser mode: the browser talks to the MCP server and keeps the tokens */
7
+ export interface UseMCPBrowserOptions {
8
+ /** The Streamable HTTP endpoint of the MCP server */
9
+ url: string;
10
+ server?: undefined;
11
+ /** Shown on the provider's consent screen; default `document.title` (or `'vue-llm'`) */
12
+ clientName?: string;
13
+ /** OAuth redirect URI; default `${location.origin}/mcp/callback`, relative values resolve against the page */
14
+ callbackUrl?: string;
15
+ /** Added before each tool name as `prefix_name` */
16
+ prefix?: string;
17
+ /** Only these tools, by their name on the MCP server */
18
+ include?: string[];
19
+ /** Leave out these tools, by their name on the MCP server */
20
+ exclude?: string[];
21
+ /** Connect on mount with stored credentials (never opens a popup). Default `true` */
22
+ autoConnect?: boolean;
23
+ /** Where tokens and client registrations are kept. Default `'local'` */
24
+ storage?: MCPStorageOption;
25
+ }
26
+ /**
27
+ * Server mode: the backend (`createMCPConnector`) connects to the server, keeps the tokens and
28
+ * runs the tools; this tracks its state and signs in through it. `tools` stays `[]`.
29
+ */
30
+ export interface UseMCPServerModeOptions extends MCPServerModeOptions {
31
+ /** The server's id in the backend's list */
32
+ id: string;
33
+ /** Read the state on mount. Default `true` */
34
+ autoConnect?: boolean;
35
+ }
36
+ export type UseMCPOptions = UseMCPBrowserOptions | UseMCPServerModeOptions;
37
+ export interface UseMCPReturn {
38
+ state: Ref<MCPState>;
39
+ /** The server's tools, ready for `useChat({ tools })`; `[]` until `ready` (always `[]` in server mode) */
40
+ tools: Ref<MCPTool[]>;
41
+ error: Ref<Error | undefined>;
42
+ /** The authorization URL while `authorizing`; render it as a link when the popup was blocked */
43
+ authUrl: Ref<string | undefined>;
44
+ serverInfo: Ref<{
45
+ name: string;
46
+ version: string;
47
+ } | undefined>;
48
+ /** Connects with stored credentials; ends in `ready` or `needs-auth` */
49
+ connect: () => Promise<void>;
50
+ /** Signs in through a popup; call it from a user gesture (click) */
51
+ authorize: () => Promise<void>;
52
+ /** Closes the session and keeps the credentials */
53
+ disconnect: () => Promise<void>;
54
+ /** Closes the session and forgets the tokens */
55
+ logout: () => Promise<void>;
56
+ }
57
+ /**
58
+ * Connects the browser to one remote MCP server over Streamable HTTP, signs in with OAuth
59
+ * (PKCE, popup) when the server asks for it, and exposes its tools as reactive vue-llm tools.
60
+ *
61
+ * ```ts
62
+ * const notion = useMCP({ url: 'https://mcp.notion.com/mcp', prefix: 'notion' })
63
+ * useChat({ provider, tools: () => notion.tools.value })
64
+ * ```
65
+ *
66
+ * With `server` (and `id`) it drives a server of `createMCPConnector` instead: `connect` enables
67
+ * it, `disconnect` disables it, `authorize` signs in through the backend; the tools run there.
68
+ */
69
+ export declare function useMCP(o: UseMCPOptions): UseMCPReturn;