@usex/mikrotik-mcp 3.58.0 → 3.59.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 (36) hide show
  1. package/dist/cli.js +31 -3
  2. package/dist/index.d.ts +5 -0
  3. package/dist/index.js +1 -1
  4. package/dist/shared/{cli-zq0rg72c.js → cli-2dyvnv9v.js} +1 -1
  5. package/dist/shared/{cli-r5p22dag.js → cli-jq168zrj.js} +7 -5
  6. package/dist/shared/{library-41tn0b6b.js → library-0zd2tej9.js} +1 -1
  7. package/dist/shared/{library-84jwmz7a.js → library-21t1cncr.js} +7 -5
  8. package/dist/ui/aaa.html +1 -1
  9. package/dist/ui/connected-devices.html +1 -1
  10. package/dist/ui/dashboard.html +1 -1
  11. package/dist/ui/firewall-audit.html +1 -1
  12. package/dist/ui/firewall.html +1 -1
  13. package/dist/ui/interfaces.html +1 -1
  14. package/dist/ui/observability.html +1 -1
  15. package/dist/ui/records.html +1 -1
  16. package/package.json +1 -1
  17. package/schemas/README.md +5 -5
  18. package/schemas/config.schema.json +47 -10
  19. package/schemas/tool-catalog.json +2941 -736
  20. package/schemas/tools/check_server_pulse.json +12 -0
  21. package/schemas/tools/config_check_drift.json +5 -1
  22. package/schemas/tools/config_reconcile.json +3 -1
  23. package/schemas/tools/config_set_baseline.json +4 -1
  24. package/schemas/tools/correlate_events.json +4 -1
  25. package/schemas/tools/diagnose.json +3 -1
  26. package/schemas/tools/get_filter_rule.json +1 -1
  27. package/schemas/tools/memory_add_observations.json +7 -2
  28. package/schemas/tools/memory_create_entities.json +7 -2
  29. package/schemas/tools/memory_create_relations.json +8 -2
  30. package/schemas/tools/memory_delete_entities.json +3 -1
  31. package/schemas/tools/memory_delete_observations.json +7 -2
  32. package/schemas/tools/memory_delete_relations.json +8 -2
  33. package/schemas/tools/memory_open_nodes.json +3 -1
  34. package/schemas/tools/memory_search_nodes.json +3 -1
  35. package/schemas/tools/suggest_fix.json +3 -1
  36. package/schemas/tools/trace_path.json +5 -1
package/dist/cli.js CHANGED
@@ -106,7 +106,7 @@ import {
106
106
  updateAaaEntity,
107
107
  updateSummaryLine,
108
108
  writeBackup
109
- } from "./shared/cli-r5p22dag.js";
109
+ } from "./shared/cli-jq168zrj.js";
110
110
 
111
111
  // src/cli.ts
112
112
  import { existsSync as existsSync2 } from "fs";
@@ -1765,12 +1765,12 @@ async function configRoutes(req, url, admin) {
1765
1765
  }
1766
1766
  async function modulesRoutes(req, url) {
1767
1767
  const p = url.pathname;
1768
- if (p !== "/api/modules" && p !== "/api/modules/toggle")
1768
+ if (p !== "/api/modules" && p !== "/api/modules/toggle" && p !== "/api/modules/app-views")
1769
1769
  return null;
1770
1770
  if (p === "/api/modules" && req.method === "GET") {
1771
1771
  const cfg = getConfig();
1772
1772
  const src = getConfigSource();
1773
- return json3({ ...moduleSurface(cfg.tools), filter: cfg.tools, source: src });
1773
+ return json3({ ...moduleSurface(cfg.tools), filter: cfg.tools, source: src, appViews: cfg.mcp.appViews });
1774
1774
  }
1775
1775
  if (p === "/api/modules/toggle" && req.method === "POST") {
1776
1776
  const b = await readJson(req);
@@ -1807,6 +1807,34 @@ async function modulesRoutes(req, url) {
1807
1807
  source: getConfigSource()
1808
1808
  });
1809
1809
  }
1810
+ if (p === "/api/modules/app-views" && req.method === "POST") {
1811
+ const b = await readJson(req);
1812
+ if (typeof b?.enabled !== "boolean") {
1813
+ return json3({ error: "enabled (boolean) is required" }, 400);
1814
+ }
1815
+ const cfg = getConfig();
1816
+ const next = { ...cfg, mcp: { ...cfg.mcp, appViews: b.enabled } };
1817
+ setConfig(next);
1818
+ let persisted = true;
1819
+ let warning;
1820
+ try {
1821
+ atomicWrite(getConfigSource().path, serializeConfig(next));
1822
+ } catch (e) {
1823
+ persisted = false;
1824
+ warning = `applied live but not saved to disk: ${e instanceof Error ? e.message : String(e)}`;
1825
+ }
1826
+ if (persisted) {
1827
+ recordVersion(getConfig(), "auto", Date.now(), `app views ${b.enabled ? "enabled" : "disabled"}`);
1828
+ }
1829
+ return json3({
1830
+ ok: true,
1831
+ persisted,
1832
+ requiresReconnect: true,
1833
+ warning,
1834
+ appViews: b.enabled,
1835
+ source: getConfigSource()
1836
+ });
1837
+ }
1810
1838
  return null;
1811
1839
  }
1812
1840
  async function captureRoutes(req, url) {
package/dist/index.d.ts CHANGED
@@ -136,6 +136,11 @@ interface ToolDef<Shape extends ZodRawShape> {
136
136
  * view (it still returns `text` for non-UI hosts).
137
137
  */
138
138
  ui?: UiLink;
139
+ /**
140
+ * When true, skip the multi-device `device` selector injection for this tool.
141
+ * Use for server-introspection tools that never contact a RouterOS device.
142
+ */
143
+ noDevice?: boolean;
139
144
  /** Handler returning the result shown to the model (text, or text + structured data). */
140
145
  handler: (args: any, ctx: ToolContext) => Promise<HandlerOutput> | HandlerOutput;
141
146
  }
package/dist/index.js CHANGED
@@ -29,7 +29,7 @@ import {
29
29
  selectToolModules,
30
30
  setConfig,
31
31
  updateSummaryLine
32
- } from "./shared/library-84jwmz7a.js";
32
+ } from "./shared/library-21t1cncr.js";
33
33
  // src/server.ts
34
34
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
35
35
  import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
@@ -4,7 +4,7 @@ import {
4
4
  allToolModules,
5
5
  moduleCatalog,
6
6
  selectToolModules
7
- } from "./cli-r5p22dag.js";
7
+ } from "./cli-jq168zrj.js";
8
8
  export {
9
9
  selectToolModules,
10
10
  moduleCatalog,
@@ -310,7 +310,7 @@ var McpServerSettingsSchema = z.object({
310
310
  allowedOrigins: z.string().default(""),
311
311
  corsOrigins: z.string().default(""),
312
312
  toolPageSize: z.coerce.number().int().min(0).default(0),
313
- appViews: z.boolean().default(true)
313
+ appViews: z.boolean().default(false)
314
314
  });
315
315
  var JumpHostSchema = z.object({
316
316
  host: z.string(),
@@ -2478,7 +2478,7 @@ function defineTool(def) {
2478
2478
  handler: def.handler,
2479
2479
  register(server, opts = {}) {
2480
2480
  const { sendLog, deviceNames, deviceAliases, deviceDirectory: deviceDirectory2, appViews } = opts;
2481
- const multiDevice = !!deviceNames && deviceNames.length > 1;
2481
+ const multiDevice = !def.noDevice && !!deviceNames && deviceNames.length > 1;
2482
2482
  const { ui, auto } = appViews === false ? { ui: undefined, auto: false } : effectiveUi(def);
2483
2483
  const selectorNames = multiDevice && deviceNames ? [...new Set([...deviceNames, ...deviceAliases ?? []])] : [];
2484
2484
  let inputSchema = multiDevice ? {
@@ -8330,7 +8330,7 @@ var cache = null;
8330
8330
  async function gateway() {
8331
8331
  if (cache)
8332
8332
  return cache;
8333
- const { moduleCatalog } = await import("./cli-zq0rg72c.js");
8333
+ const { moduleCatalog } = await import("./cli-2dyvnv9v.js");
8334
8334
  const forIndex = [];
8335
8335
  const byName = new Map;
8336
8336
  for (const mod of moduleCatalog) {
@@ -25027,6 +25027,7 @@ var serverPulseTools = [
25027
25027
  defineTool({
25028
25028
  name: "check_server_pulse",
25029
25029
  title: "Server Pulse & Update Check",
25030
+ noDevice: true,
25030
25031
  annotations: READ,
25031
25032
  description: "Check the MCP server's own heartbeat: running version, whether a newer release " + "is available, release notes for the latest version, upgrade commands, and server " + "vitals (tool count, uptime). This is server self-awareness \u2014 no RouterOS device " + "is contacted. Call this when the user asks about the MCP server version, updates, " + "what's new, or 'is my server up to date'. Returns rich release notes from GitHub " + "so you can summarize what changed.",
25032
25033
  inputSchema: {
@@ -25056,8 +25057,9 @@ var serverPulseTools = [
25056
25057
  }
25057
25058
  sections.push("", `Release: ${result.release.url}`);
25058
25059
  }
25059
- if (includeNotes && result.release.body && result.release.isNewer) {
25060
- sections.push("", `WHAT'S NEW IN v${result.release.version}`, sep, result.release.body);
25060
+ if (includeNotes && result.release.body) {
25061
+ const notesHeader = result.release.isNewer ? `WHAT'S NEW IN v${result.release.version}` : `RELEASE NOTES \u2014 v${result.release.version}`;
25062
+ sections.push("", notesHeader, sep, result.release.body);
25061
25063
  }
25062
25064
  } else {
25063
25065
  sections.push("", "UPDATE STATUS: UNKNOWN", sep, `Could not check for updates${result.error ? `: ${result.error}` : "."}`, `Current version: v${VERSION}`, result.fromCache ? "(showing cached data)" : "(no cached data available \u2014 check network connectivity)");
@@ -4,7 +4,7 @@ import {
4
4
  allToolModules,
5
5
  moduleCatalog,
6
6
  selectToolModules
7
- } from "./library-84jwmz7a.js";
7
+ } from "./library-21t1cncr.js";
8
8
  export {
9
9
  selectToolModules,
10
10
  moduleCatalog,
@@ -310,7 +310,7 @@ var McpServerSettingsSchema = z.object({
310
310
  allowedOrigins: z.string().default(""),
311
311
  corsOrigins: z.string().default(""),
312
312
  toolPageSize: z.coerce.number().int().min(0).default(0),
313
- appViews: z.boolean().default(true)
313
+ appViews: z.boolean().default(false)
314
314
  });
315
315
  var JumpHostSchema = z.object({
316
316
  host: z.string(),
@@ -2430,7 +2430,7 @@ function defineTool(def) {
2430
2430
  handler: def.handler,
2431
2431
  register(server, opts = {}) {
2432
2432
  const { sendLog, deviceNames, deviceAliases, deviceDirectory: deviceDirectory2, appViews } = opts;
2433
- const multiDevice = !!deviceNames && deviceNames.length > 1;
2433
+ const multiDevice = !def.noDevice && !!deviceNames && deviceNames.length > 1;
2434
2434
  const { ui, auto } = appViews === false ? { ui: undefined, auto: false } : effectiveUi(def);
2435
2435
  const selectorNames = multiDevice && deviceNames ? [...new Set([...deviceNames, ...deviceAliases ?? []])] : [];
2436
2436
  let inputSchema = multiDevice ? {
@@ -8260,7 +8260,7 @@ var cache = null;
8260
8260
  async function gateway() {
8261
8261
  if (cache)
8262
8262
  return cache;
8263
- const { moduleCatalog } = await import("./library-41tn0b6b.js");
8263
+ const { moduleCatalog } = await import("./library-0zd2tej9.js");
8264
8264
  const forIndex = [];
8265
8265
  const byName = new Map;
8266
8266
  for (const mod of moduleCatalog) {
@@ -24956,6 +24956,7 @@ var serverPulseTools = [
24956
24956
  defineTool({
24957
24957
  name: "check_server_pulse",
24958
24958
  title: "Server Pulse & Update Check",
24959
+ noDevice: true,
24959
24960
  annotations: READ,
24960
24961
  description: "Check the MCP server's own heartbeat: running version, whether a newer release " + "is available, release notes for the latest version, upgrade commands, and server " + "vitals (tool count, uptime). This is server self-awareness \u2014 no RouterOS device " + "is contacted. Call this when the user asks about the MCP server version, updates, " + "what's new, or 'is my server up to date'. Returns rich release notes from GitHub " + "so you can summarize what changed.",
24961
24962
  inputSchema: {
@@ -24985,8 +24986,9 @@ var serverPulseTools = [
24985
24986
  }
24986
24987
  sections.push("", `Release: ${result.release.url}`);
24987
24988
  }
24988
- if (includeNotes && result.release.body && result.release.isNewer) {
24989
- sections.push("", `WHAT'S NEW IN v${result.release.version}`, sep, result.release.body);
24989
+ if (includeNotes && result.release.body) {
24990
+ const notesHeader = result.release.isNewer ? `WHAT'S NEW IN v${result.release.version}` : `RELEASE NOTES \u2014 v${result.release.version}`;
24991
+ sections.push("", notesHeader, sep, result.release.body);
24990
24992
  }
24991
24993
  } else {
24992
24994
  sections.push("", "UPDATE STATUS: UNKNOWN", sep, `Could not check for updates${result.error ? `: ${result.error}` : "."}`, `Current version: v${VERSION}`, result.fromCache ? "(showing cached data)" : "(no cached data available \u2014 check network connectivity)");
package/dist/ui/aaa.html CHANGED
@@ -116,7 +116,7 @@ Boolean requesting whether a visible border and background is provided by the ho
116
116
  - omitted: host decides border`)}),I({method:V(`ui/request-display-mode`),params:I({mode:hv.describe(`The display mode being requested.`)})});var jv=I({mode:hv.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),Mv=R([V(`model`),V(`app`)]).describe(`Tool visibility scope - who can access the tool.`);I({resourceUri:j().optional(),visibility:F(Mv).optional().describe(`Who can access this tool. Default: ["model", "app"]
117
117
  - "model": Tool visible to and callable by the agent
118
118
  - "app": Tool callable by the app from this server only`),csp:Jf().optional(),permissions:Jf().optional()}),I({mimeTypes:F(j()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),I({method:V(`ui/download-file`),params:I({contents:F(R([i_,a_])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),I({method:V(`ui/message`),params:I({role:V(`user`).describe(`Message role, currently only "user" is supported.`),content:F(o_).describe(`Message content blocks (text, image, etc.).`)})}),I({method:V(`ui/notifications/sandbox-resource-ready`),params:I({html:j().describe(`HTML content to load into the inner iframe.`),sandbox:j().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:bv.optional().describe(`CSP configuration from resource metadata.`),permissions:xv.optional().describe(`Sandbox permissions from resource metadata.`)})});var Nv=I({method:V(`ui/notifications/tool-result`),params:h_.describe(`Standard MCP tool execution result.`)}),Pv=I({toolInfo:I({id:Fh.optional().describe(`JSON-RPC id of the tools/call request.`),tool:f_.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:mv.optional().describe(`Current color theme preference.`),styles:Ev.optional().describe(`Style configuration for theming the app.`),displayMode:hv.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:F(hv).optional().describe(`Display modes the host supports.`),containerDimensions:R([I({height:M().describe(`Fixed container height in pixels.`)}),I({maxHeight:R([M(),Gf()]).optional().describe(`Maximum container height in pixels.`)})]).and(R([I({width:M().describe(`Fixed container width in pixels.`)}),I({maxWidth:R([M(),Gf()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
119
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),Fv=I({method:V(`ui/notifications/host-context-changed`),params:Pv.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(o_).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:Xh.describe(`App identification (name and version).`),appCapabilities:Av.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var Iv=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Xh.describe(`Host application identification and version.`),hostCapabilities:kv.describe(`Features and capabilities provided by the host.`),hostContext:Pv.describe(`Rich context about the host environment.`)}).passthrough(),Lv={target:`draft-2020-12`};async function Rv(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](Lv);if(n.vendor===`zod`){let{z:n}=await uv(async()=>{let{z:e}=await Promise.resolve().then(()=>(Ch(),xh));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function zv(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function Bv(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function Vv(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function Hv(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function Uv(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}var Wv=class e extends dv{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Sv,toolinputpartial:Cv,toolresult:Nv,toolcancelled:wv,hostcontextchanged:Fv};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||a({jitless:!0}),this.setRequestHandler(og,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=ov(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await zv(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await zv(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Rv(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Rv(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(Dv,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(__,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(p_,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},h_,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},Bg,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},Pg,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?N_:M_;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},yv,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Gh,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},_v,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},vv,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},jv,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new pv(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:fv}},Iv,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function Q(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))e===`class`?r.className=n:r.setAttribute(e,n);for(let e of n.flat())e===!1||e==null||r.append(e instanceof Node?e:document.createTextNode(String(e)));return r}function Gv(e,t,n={}){let r=Q(`button`,{class:`btn${n.class?` ${n.class}`:``}`,...n.title?{title:n.title}:{}});return r.textContent=e,n.disabled&&(r.disabled=!0),r.addEventListener(`click`,t),r}function Kv(e){e.onhostcontextchanged=e=>{if(e.theme&&Vv(e.theme),e.styles?.variables&&Hv(e.styles.variables),e.styles?.css?.fonts&&Uv(e.styles.css.fonts),e.safeAreaInsets){let{top:t,right:n,bottom:r,left:i}=e.safeAreaInsets;document.body.style.padding=`${t+16}px ${n+16}px ${r+16}px ${i+16}px`}},Vv(Bv())}var qv=[{slug:`radius`,label:`RADIUS Servers`,idKey:`.id`,toggle:!0,columns:[{key:`address`,label:`Address`},{key:`service`,label:`Service`},{key:`authentication-port`,label:`Auth`},{key:`accounting-port`,label:`Acct`},{key:`_status`,label:`Status`}],fields:[{key:`address`,label:`Address`,required:!0},{key:`secret`,label:`Secret`,type:`password`,required:!0},{key:`service`,label:`Service`,required:!0,placeholder:`login,ppp,hotspot,…`},{key:`authentication-port`,label:`Auth port`,type:`number`,placeholder:`1812`},{key:`accounting-port`,label:`Acct port`,type:`number`,placeholder:`1813`},{key:`timeout`,label:`Timeout`,placeholder:`300ms`},{key:`src-address`,label:`Src address`},{key:`realm`,label:`Realm`},{key:`called-id`,label:`Called ID`},{key:`domain`,label:`Domain`},{key:`protocol`,label:`Protocol`,type:`select`,options:[`udp`,`radsec`]},{key:`certificate`,label:`Certificate`},{key:`accounting-backup`,label:`Acct backup`,type:`bool`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},{slug:`um-users`,label:`Users`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared`},{key:`comment`,label:`Comment`},{key:`_status`,label:`Status`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`password`,label:`Password`,type:`password`,required:!0},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared users`,type:`number`},{key:`attributes`,label:`Attributes`},{key:`caller-id`,label:`Caller ID`},{key:`otp-secret`,label:`OTP secret`,type:`password`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},{slug:`um-profiles`,label:`Profiles`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`validity`,label:`Validity`},{key:`price`,label:`Price`},{key:`starts-when`,label:`Starts`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`name-for-users`,label:`Display name`},{key:`validity`,label:`Validity`,placeholder:`30d`},{key:`price`,label:`Price`,type:`number`},{key:`starts-when`,label:`Starts when`,type:`select`,options:[`assigned`,`first-auth`]},{key:`override-shared-users`,label:`Override shared`},{key:`comment`,label:`Comment`}]},{slug:`um-limitations`,label:`Limitations`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`rate-limit-rx`,label:`Rate ↓`},{key:`rate-limit-tx`,label:`Rate ↑`},{key:`transfer-limit`,label:`Transfer`},{key:`uptime-limit`,label:`Uptime`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`rate-limit-rx`,label:`Download rate`,placeholder:`10M`},{key:`rate-limit-tx`,label:`Upload rate`,placeholder:`10M`},{key:`rate-limit-min-rx`,label:`Min ↓ (CIR)`},{key:`rate-limit-min-tx`,label:`Min ↑ (CIR)`},{key:`rate-limit-burst-rx`,label:`Burst ↓`},{key:`rate-limit-burst-tx`,label:`Burst ↑`},{key:`rate-limit-priority`,label:`Priority`,type:`number`},{key:`transfer-limit`,label:`Transfer cap`,placeholder:`10G`},{key:`uptime-limit`,label:`Uptime cap`,placeholder:`1d`},{key:`comment`,label:`Comment`}]},{slug:`um-routers`,label:`NAS Clients`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`address`,label:`Address`},{key:`coa-port`,label:`CoA`},{key:`_status`,label:`Status`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`address`,label:`Address`,required:!0},{key:`shared-secret`,label:`Shared secret`,type:`password`,required:!0},{key:`coa-port`,label:`CoA port`,type:`number`},{key:`protocol`,label:`Protocol`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},{slug:`um-user-profiles`,label:`Assignments`,idKey:`.id`,addOnly:!0,columns:[{key:`user`,label:`User`},{key:`profile`,label:`Profile`},{key:`state`,label:`State`}],fields:[{key:`user`,label:`User`,required:!0},{key:`profile`,label:`Profile`,required:!0}]},{slug:`um-sessions`,label:`Sessions`,idKey:`.id`,readonly:!0,columns:[{key:`user`,label:`User`},{key:`calling-station-id`,label:`Caller`},{key:`started`,label:`Started`},{key:`uptime`,label:`Uptime`},{key:`status`,label:`Status`}],fields:[]}],Jv={slug:`settings`,label:`Settings`},Yv=e=>qv.find(t=>t.slug===e),Xv=e=>(e.flags??``).includes(`X`)||e.disabled===`yes`,Zv=document.getElementById(`app`),Qv=new Wv({name:`mikrotik-aaa`,version:`1.0.0`}),$v=`radius`,ey=!0,ty=[],ny=null,ry={},iy=null,ay=!1,oy=null;function sy(e){return e?.structuredContent}function cy(e){if(!e||e.__mikrotikView!==`aaa-section`)return;typeof e.slug==`string`&&($v=e.slug),ey=e.available!==!1,ty=e.rows??[];let t=e.lastOp;oy=t&&!t.ok?t.message:null}function ly(e){if(!e||e.__mikrotikView!==`aaa-settings`)return;iy={radiusIncoming:e.radiusIncoming??{},umAvailable:e.umAvailable!==!1,umSettings:e.umSettings??{}};let t=e.lastOp;oy=t&&!t.ok?t.message:null}async function uy(e){$v=e,ny=null,oy=null,ay=!0,$();try{cy(sy(await Qv.callServerTool({name:`get_aaa_section`,arguments:{slug:e}})))}catch(e){oy=String(e)}finally{ay=!1,$()}}async function dy(){$v=`settings`,oy=null,ay=!0,$();try{ly(sy(await Qv.callServerTool({name:`get_aaa_settings`,arguments:{}})))}catch(e){oy=String(e)}finally{ay=!1,$()}}async function fy(e,t){if(!ay){ay=!0,oy=null,$();try{cy(sy(await Qv.callServerTool({name:`aaa_mutate`,arguments:{op:e,slug:$v,...t}}))),ny=null}catch(e){oy=String(e)}finally{ay=!1,$()}}}async function py(e,t){if(!ay){ay=!0,oy=null,$();try{ly(sy(await Qv.callServerTool({name:`set_aaa_settings`,arguments:{target:e,fields:t}})))}catch(e){oy=String(e)}finally{ay=!1,$()}}}function my(e){if(e.type===`bool`||e.type===`select`){let t=Q(`select`,{class:`aaa-input`}),n=e.type===`bool`?[``,`no`,`yes`]:[``,...e.options??[]];for(let e of n){let n=Q(`option`,{value:e},e||`—`);t.append(n)}return t.value=ry[e.key]??``,t.addEventListener(`change`,()=>{ry[e.key]=t.value}),t}let t=Q(`input`,{class:`aaa-input`,type:e.type===`password`?`password`:e.type===`number`?`number`:`text`,placeholder:e.placeholder??(e.type===`password`?`(unchanged)`:``)});return t.value=ry[e.key]??``,t.addEventListener(`input`,()=>{ry[e.key]=t.value}),t}function hy(e){let t=Q(`div`,{class:`aaa-form-grid`},...e.fields.map(e=>Q(`label`,{class:`aaa-field`},Q(`span`,{class:`aaa-field-label`},`${e.label}${e.required&&ny===`new`?` *`:``}`),my(e)))),n=Gv(ny===`new`?`Create`:`Save`,()=>{ny===`new`?fy(`add`,{fields:{...ry}}):fy(`update`,{id:ny,fields:{...ry}})},{class:`primary`}),r=Gv(`Cancel`,()=>{ny=null,$()});return Q(`div`,{class:`aaa-form`},Q(`div`,{class:`aaa-form-title`},ny===`new`?`New ${e.label}`:`Edit ${ny}`),t,Q(`div`,{class:`aaa-form-actions`},n,r))}function gy(e,t){ny=t[e.idKey],ry={};for(let n of e.fields)n.type!==`password`&&(n.key===`disabled`?ry.disabled=Xv(t)?`yes`:`no`:t[n.key]!=null&&(ry[n.key]=t[n.key]));$()}function _y(e){let t=Q(`div`,{class:`aaa-row aaa-head`},...e.columns.map(e=>Q(`span`,{},e.label)),Q(`span`,{class:`aaa-actions`},e.readonly?``:`Actions`)),n=ty.map(t=>{let n=t[e.idKey],r=Xv(t),i=e.columns.map(e=>e.key===`_status`?Q(`span`,{},Q(`span`,{class:`aaa-badge ${r?`off`:`on`}`},r?`disabled`:`enabled`)):Q(`span`,{class:`aaa-cell`,title:t[e.key]??``},t[e.key]??``)),a=[];return e.readonly||(e.toggle&&a.push(Gv(r?`Enable`:`Disable`,()=>void fy(`toggle`,{id:n,enable:r}))),e.addOnly||a.push(Gv(`Edit`,()=>gy(e,t))),a.push(Gv(`Remove`,()=>void fy(`remove`,{id:n}),{class:`danger`}))),Q(`div`,{class:`aaa-row${r?` is-off`:``}`},...i,Q(`span`,{class:`aaa-actions`},...a))});return Q(`div`,{class:`aaa-table`,style:`--cols:${e.columns.length}`},t,...n)}function vy(e,t,n,r,i){let a={},o=Q(`div`,{class:`aaa-form-grid`},...n.map(e=>{let n=Q(`label`,{class:`aaa-field`},Q(`span`,{class:`aaa-field-label`},e.label)),r;if(e.type===`bool`){let t=Q(`select`,{class:`aaa-input`});for(let e of[``,`no`,`yes`])t.append(Q(`option`,{value:e},e||`(unchanged)`));t.addEventListener(`change`,()=>{a[e.key]=t.value}),r=t}else{let n=Q(`input`,{class:`aaa-input`,type:e.type===`number`?`number`:`text`,placeholder:t[e.key]??e.placeholder??``});n.addEventListener(`input`,()=>{a[e.key]=n.value}),r=n}return n.append(r),n})),s=Q(`div`,{class:`aaa-current`},n.map(e=>`${e.label}: ${t[e.key]??`—`}`).join(` · `)),c=Q(`div`,{class:`aaa-form-actions`},Gv(`Save`,()=>void py(r,a),{class:`primary`}),i??null);return Q(`div`,{class:`aaa-card`},Q(`div`,{class:`aaa-form-title`},e),s,o,c)}function yy(){return iy?Q(`div`,{class:`aaa-settings`},vy(`RADIUS Incoming (CoA listener)`,iy.radiusIncoming,[{key:`accept`,label:`Accept CoA`,type:`bool`},{key:`port`,label:`CoA port`,type:`number`,placeholder:`3799`}],`radius-incoming`,Gv(`Reset counters`,()=>void py(`radius-reset-counters`,{}))),iy.umAvailable?vy(`User Manager (built-in RADIUS server)`,iy.umSettings,[{key:`enabled`,label:`Enabled`,type:`bool`},{key:`use-profiles`,label:`Use profiles`,type:`bool`},{key:`certificate`,label:`Certificate`},{key:`authentication-port`,label:`Auth port`,type:`number`},{key:`accounting-port`,label:`Acct port`,type:`number`}],`um-settings`):Q(`div`,{class:`aaa-card`},Q(`div`,{class:`aaa-form-title`},`User Manager`),Q(`div`,{class:`muted`},`The user-manager package is not installed on this device.`))):Q(`div`,{class:`muted`},`Loading settings…`)}function $(){let e=Q(`div`,{class:`aaa-tabs`},...[...qv,Jv].map(e=>Q(`button`,{class:`aaa-tab${$v===e.slug?` is-active`:``}`},e.label)));[...e.children].forEach((e,t)=>{let n=[...qv,Jv][t];e.addEventListener(`click`,()=>{n.slug===`settings`?dy():uy(n.slug)})});let t=[Q(`div`,{class:`aaa-titlebar`},Q(`div`,{class:`aaa-title`},`RADIUS & User Manager`)),e];if(oy&&t.push(Q(`div`,{class:`aaa-error`},oy)),$v===`settings`)t.push(yy());else{let e=Yv($v);if(!e)t.push(Q(`div`,{class:`muted`},`Unknown section.`));else if(!ey)t.push(Q(`div`,{class:`aaa-notice`},`User Manager is not installed on this device. Install the user-manager package (System → Packages) and reboot.`));else{let n=Q(`div`,{class:`aaa-bar`});n.append(Q(`span`,{class:`muted`},`${ty.length} row(s)`)),n.append(Q(`span`,{class:`spacer`})),n.append(Gv(`↻ Refresh`,()=>void uy($v))),e.readonly||n.append(Gv(`+ Add`,()=>{ny=`new`,ry={},$()},{class:`primary`})),t.push(n),ny&&t.push(hy(e)),t.push(ty.length||!e?_y(e):Q(`div`,{class:`muted`},`No rows.`))}}Zv.replaceChildren(Q(`div`,{class:`aaa-wrap`},...t))}Qv.ontoolresult=e=>{let t=e.structuredContent;t?.__mikrotikView===`aaa-settings`?ly(t):cy(t),$()},Qv.ontoolinput=()=>$(),Kv(Qv),$(),Qv.connect().catch(e=>console.error(`[aaa] connect failed`,e));
119
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),Fv=I({method:V(`ui/notifications/host-context-changed`),params:Pv.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(o_).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:Xh.describe(`App identification (name and version).`),appCapabilities:Av.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var Iv=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Xh.describe(`Host application identification and version.`),hostCapabilities:kv.describe(`Features and capabilities provided by the host.`),hostContext:Pv.describe(`Rich context about the host environment.`)}).passthrough(),Lv={target:`draft-2020-12`};async function Rv(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](Lv);if(n.vendor===`zod`){let{z:n}=await uv(async()=>{let{z:e}=await Promise.resolve().then(()=>(Ch(),xh));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function zv(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function Bv(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function Vv(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function Hv(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function Uv(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}var Wv=class e extends dv{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Sv,toolinputpartial:Cv,toolresult:Nv,toolcancelled:wv,hostcontextchanged:Fv};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||a({jitless:!0}),this.setRequestHandler(og,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=ov(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await zv(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await zv(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Rv(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Rv(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(Dv,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(__,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(p_,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},h_,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},Bg,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},Pg,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?N_:M_;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},yv,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Gh,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},_v,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},vv,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},jv,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new pv(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:fv}},Iv,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function Q(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))e===`class`?r.className=n:r.setAttribute(e,n);for(let e of n.flat())e===!1||e==null||r.append(e instanceof Node?e:document.createTextNode(String(e)));return r}function Gv(e,t,n={}){let r=Q(`button`,{class:`btn${n.class?` ${n.class}`:``}`,...n.title?{title:n.title}:{}});return r.textContent=e,n.disabled&&(r.disabled=!0),r.addEventListener(`click`,t),r}function Kv(e){e.onhostcontextchanged=e=>{if(e.theme&&Vv(e.theme),e.styles?.variables&&Hv(e.styles.variables),e.styles?.css?.fonts&&Uv(e.styles.css.fonts),e.safeAreaInsets){let{top:t,right:n,bottom:r,left:i}=e.safeAreaInsets;document.body.style.padding=`${t+16}px ${n+16}px ${r+16}px ${i+16}px`}},Vv(Bv())}var qv=1e4;async function Jv(e,t,n){try{return await e.connect(void 0,{timeout:qv}),console.warn(`[${t}] connected`,{host:e.getHostVersion(),caps:e.getHostCapabilities()}),!0}catch(e){console.error(`[${t}] connect failed`,e);let r=e instanceof Error&&/timed?\s*out/i.test(e.message)?`The MCP App host did not respond — make sure your client supports MCP Apps (ext-apps).`:`Connection failed: ${e instanceof Error?e.message:String(e)}`;return n.replaceChildren(Q(`div`,{class:`skeleton`},r)),!1}}var Yv=[{slug:`radius`,label:`RADIUS Servers`,idKey:`.id`,toggle:!0,columns:[{key:`address`,label:`Address`},{key:`service`,label:`Service`},{key:`authentication-port`,label:`Auth`},{key:`accounting-port`,label:`Acct`},{key:`_status`,label:`Status`}],fields:[{key:`address`,label:`Address`,required:!0},{key:`secret`,label:`Secret`,type:`password`,required:!0},{key:`service`,label:`Service`,required:!0,placeholder:`login,ppp,hotspot,…`},{key:`authentication-port`,label:`Auth port`,type:`number`,placeholder:`1812`},{key:`accounting-port`,label:`Acct port`,type:`number`,placeholder:`1813`},{key:`timeout`,label:`Timeout`,placeholder:`300ms`},{key:`src-address`,label:`Src address`},{key:`realm`,label:`Realm`},{key:`called-id`,label:`Called ID`},{key:`domain`,label:`Domain`},{key:`protocol`,label:`Protocol`,type:`select`,options:[`udp`,`radsec`]},{key:`certificate`,label:`Certificate`},{key:`accounting-backup`,label:`Acct backup`,type:`bool`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},{slug:`um-users`,label:`Users`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared`},{key:`comment`,label:`Comment`},{key:`_status`,label:`Status`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`password`,label:`Password`,type:`password`,required:!0},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared users`,type:`number`},{key:`attributes`,label:`Attributes`},{key:`caller-id`,label:`Caller ID`},{key:`otp-secret`,label:`OTP secret`,type:`password`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},{slug:`um-profiles`,label:`Profiles`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`validity`,label:`Validity`},{key:`price`,label:`Price`},{key:`starts-when`,label:`Starts`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`name-for-users`,label:`Display name`},{key:`validity`,label:`Validity`,placeholder:`30d`},{key:`price`,label:`Price`,type:`number`},{key:`starts-when`,label:`Starts when`,type:`select`,options:[`assigned`,`first-auth`]},{key:`override-shared-users`,label:`Override shared`},{key:`comment`,label:`Comment`}]},{slug:`um-limitations`,label:`Limitations`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`rate-limit-rx`,label:`Rate ↓`},{key:`rate-limit-tx`,label:`Rate ↑`},{key:`transfer-limit`,label:`Transfer`},{key:`uptime-limit`,label:`Uptime`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`rate-limit-rx`,label:`Download rate`,placeholder:`10M`},{key:`rate-limit-tx`,label:`Upload rate`,placeholder:`10M`},{key:`rate-limit-min-rx`,label:`Min ↓ (CIR)`},{key:`rate-limit-min-tx`,label:`Min ↑ (CIR)`},{key:`rate-limit-burst-rx`,label:`Burst ↓`},{key:`rate-limit-burst-tx`,label:`Burst ↑`},{key:`rate-limit-priority`,label:`Priority`,type:`number`},{key:`transfer-limit`,label:`Transfer cap`,placeholder:`10G`},{key:`uptime-limit`,label:`Uptime cap`,placeholder:`1d`},{key:`comment`,label:`Comment`}]},{slug:`um-routers`,label:`NAS Clients`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`address`,label:`Address`},{key:`coa-port`,label:`CoA`},{key:`_status`,label:`Status`}],fields:[{key:`name`,label:`Name`,required:!0},{key:`address`,label:`Address`,required:!0},{key:`shared-secret`,label:`Shared secret`,type:`password`,required:!0},{key:`coa-port`,label:`CoA port`,type:`number`},{key:`protocol`,label:`Protocol`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},{slug:`um-user-profiles`,label:`Assignments`,idKey:`.id`,addOnly:!0,columns:[{key:`user`,label:`User`},{key:`profile`,label:`Profile`},{key:`state`,label:`State`}],fields:[{key:`user`,label:`User`,required:!0},{key:`profile`,label:`Profile`,required:!0}]},{slug:`um-sessions`,label:`Sessions`,idKey:`.id`,readonly:!0,columns:[{key:`user`,label:`User`},{key:`calling-station-id`,label:`Caller`},{key:`started`,label:`Started`},{key:`uptime`,label:`Uptime`},{key:`status`,label:`Status`}],fields:[]}],Xv={slug:`settings`,label:`Settings`},Zv=e=>Yv.find(t=>t.slug===e),Qv=e=>(e.flags??``).includes(`X`)||e.disabled===`yes`,$v=document.getElementById(`app`),ey=new Wv({name:`mikrotik-aaa`,version:`1.0.0`}),ty=`radius`,ny=!0,ry=[],iy=null,ay={},oy=null,sy=!1,cy=null;function ly(e){return e?.structuredContent}function uy(e){if(!e||e.__mikrotikView!==`aaa-section`)return;typeof e.slug==`string`&&(ty=e.slug),ny=e.available!==!1,ry=e.rows??[];let t=e.lastOp;cy=t&&!t.ok?t.message:null}function dy(e){if(!e||e.__mikrotikView!==`aaa-settings`)return;oy={radiusIncoming:e.radiusIncoming??{},umAvailable:e.umAvailable!==!1,umSettings:e.umSettings??{}};let t=e.lastOp;cy=t&&!t.ok?t.message:null}async function fy(e){ty=e,iy=null,cy=null,sy=!0,$();try{uy(ly(await ey.callServerTool({name:`get_aaa_section`,arguments:{slug:e}})))}catch(e){cy=String(e)}finally{sy=!1,$()}}async function py(){ty=`settings`,cy=null,sy=!0,$();try{dy(ly(await ey.callServerTool({name:`get_aaa_settings`,arguments:{}})))}catch(e){cy=String(e)}finally{sy=!1,$()}}async function my(e,t){if(!sy){sy=!0,cy=null,$();try{uy(ly(await ey.callServerTool({name:`aaa_mutate`,arguments:{op:e,slug:ty,...t}}))),iy=null}catch(e){cy=String(e)}finally{sy=!1,$()}}}async function hy(e,t){if(!sy){sy=!0,cy=null,$();try{dy(ly(await ey.callServerTool({name:`set_aaa_settings`,arguments:{target:e,fields:t}})))}catch(e){cy=String(e)}finally{sy=!1,$()}}}function gy(e){if(e.type===`bool`||e.type===`select`){let t=Q(`select`,{class:`aaa-input`}),n=e.type===`bool`?[``,`no`,`yes`]:[``,...e.options??[]];for(let e of n){let n=Q(`option`,{value:e},e||`—`);t.append(n)}return t.value=ay[e.key]??``,t.addEventListener(`change`,()=>{ay[e.key]=t.value}),t}let t=Q(`input`,{class:`aaa-input`,type:e.type===`password`?`password`:e.type===`number`?`number`:`text`,placeholder:e.placeholder??(e.type===`password`?`(unchanged)`:``)});return t.value=ay[e.key]??``,t.addEventListener(`input`,()=>{ay[e.key]=t.value}),t}function _y(e){let t=Q(`div`,{class:`aaa-form-grid`},...e.fields.map(e=>Q(`label`,{class:`aaa-field`},Q(`span`,{class:`aaa-field-label`},`${e.label}${e.required&&iy===`new`?` *`:``}`),gy(e)))),n=Gv(iy===`new`?`Create`:`Save`,()=>{iy===`new`?my(`add`,{fields:{...ay}}):my(`update`,{id:iy,fields:{...ay}})},{class:`primary`}),r=Gv(`Cancel`,()=>{iy=null,$()});return Q(`div`,{class:`aaa-form`},Q(`div`,{class:`aaa-form-title`},iy===`new`?`New ${e.label}`:`Edit ${iy}`),t,Q(`div`,{class:`aaa-form-actions`},n,r))}function vy(e,t){iy=t[e.idKey],ay={};for(let n of e.fields)n.type!==`password`&&(n.key===`disabled`?ay.disabled=Qv(t)?`yes`:`no`:t[n.key]!=null&&(ay[n.key]=t[n.key]));$()}function yy(e){let t=Q(`div`,{class:`aaa-row aaa-head`},...e.columns.map(e=>Q(`span`,{},e.label)),Q(`span`,{class:`aaa-actions`},e.readonly?``:`Actions`)),n=ry.map(t=>{let n=t[e.idKey],r=Qv(t),i=e.columns.map(e=>e.key===`_status`?Q(`span`,{},Q(`span`,{class:`aaa-badge ${r?`off`:`on`}`},r?`disabled`:`enabled`)):Q(`span`,{class:`aaa-cell`,title:t[e.key]??``},t[e.key]??``)),a=[];return e.readonly||(e.toggle&&a.push(Gv(r?`Enable`:`Disable`,()=>void my(`toggle`,{id:n,enable:r}))),e.addOnly||a.push(Gv(`Edit`,()=>vy(e,t))),a.push(Gv(`Remove`,()=>void my(`remove`,{id:n}),{class:`danger`}))),Q(`div`,{class:`aaa-row${r?` is-off`:``}`},...i,Q(`span`,{class:`aaa-actions`},...a))});return Q(`div`,{class:`aaa-table`,style:`--cols:${e.columns.length}`},t,...n)}function by(e,t,n,r,i){let a={},o=Q(`div`,{class:`aaa-form-grid`},...n.map(e=>{let n=Q(`label`,{class:`aaa-field`},Q(`span`,{class:`aaa-field-label`},e.label)),r;if(e.type===`bool`){let t=Q(`select`,{class:`aaa-input`});for(let e of[``,`no`,`yes`])t.append(Q(`option`,{value:e},e||`(unchanged)`));t.addEventListener(`change`,()=>{a[e.key]=t.value}),r=t}else{let n=Q(`input`,{class:`aaa-input`,type:e.type===`number`?`number`:`text`,placeholder:t[e.key]??e.placeholder??``});n.addEventListener(`input`,()=>{a[e.key]=n.value}),r=n}return n.append(r),n})),s=Q(`div`,{class:`aaa-current`},n.map(e=>`${e.label}: ${t[e.key]??`—`}`).join(` · `)),c=Q(`div`,{class:`aaa-form-actions`},Gv(`Save`,()=>void hy(r,a),{class:`primary`}),i??null);return Q(`div`,{class:`aaa-card`},Q(`div`,{class:`aaa-form-title`},e),s,o,c)}function xy(){return oy?Q(`div`,{class:`aaa-settings`},by(`RADIUS Incoming (CoA listener)`,oy.radiusIncoming,[{key:`accept`,label:`Accept CoA`,type:`bool`},{key:`port`,label:`CoA port`,type:`number`,placeholder:`3799`}],`radius-incoming`,Gv(`Reset counters`,()=>void hy(`radius-reset-counters`,{}))),oy.umAvailable?by(`User Manager (built-in RADIUS server)`,oy.umSettings,[{key:`enabled`,label:`Enabled`,type:`bool`},{key:`use-profiles`,label:`Use profiles`,type:`bool`},{key:`certificate`,label:`Certificate`},{key:`authentication-port`,label:`Auth port`,type:`number`},{key:`accounting-port`,label:`Acct port`,type:`number`}],`um-settings`):Q(`div`,{class:`aaa-card`},Q(`div`,{class:`aaa-form-title`},`User Manager`),Q(`div`,{class:`muted`},`The user-manager package is not installed on this device.`))):Q(`div`,{class:`muted`},`Loading settings…`)}function $(){let e=Q(`div`,{class:`aaa-tabs`},...[...Yv,Xv].map(e=>Q(`button`,{class:`aaa-tab${ty===e.slug?` is-active`:``}`},e.label)));[...e.children].forEach((e,t)=>{let n=[...Yv,Xv][t];e.addEventListener(`click`,()=>{n.slug===`settings`?py():fy(n.slug)})});let t=[Q(`div`,{class:`aaa-titlebar`},Q(`div`,{class:`aaa-title`},`RADIUS & User Manager`)),e];if(cy&&t.push(Q(`div`,{class:`aaa-error`},cy)),ty===`settings`)t.push(xy());else{let e=Zv(ty);if(!e)t.push(Q(`div`,{class:`muted`},`Unknown section.`));else if(!ny)t.push(Q(`div`,{class:`aaa-notice`},`User Manager is not installed on this device. Install the user-manager package (System → Packages) and reboot.`));else{let n=Q(`div`,{class:`aaa-bar`});n.append(Q(`span`,{class:`muted`},`${ry.length} row(s)`)),n.append(Q(`span`,{class:`spacer`})),n.append(Gv(`↻ Refresh`,()=>void fy(ty))),e.readonly||n.append(Gv(`+ Add`,()=>{iy=`new`,ay={},$()},{class:`primary`})),t.push(n),iy&&t.push(_y(e)),t.push(ry.length||!e?yy(e):Q(`div`,{class:`muted`},`No rows.`))}}$v.replaceChildren(Q(`div`,{class:`aaa-wrap`},...t))}ey.ontoolresult=e=>{let t=e.structuredContent;t?.__mikrotikView===`aaa-settings`?dy(t):uy(t),$()},ey.ontoolinput=()=>$(),Kv(ey),$(),Jv(ey,`aaa`,$v);
120
120
  </script>
121
121
  <style>
122
122
  :root{--bg:#0b0d10;--surface:#14181d;--surface-2:#1b2027;--border:#2a313a;--text:#e8eaed;--text-dim:#9aa0a6;--accent:#7c9cff;--danger:#f2685a;--ok:#4ade80}@media (prefers-color-scheme:light){:root{--bg:#fff;--surface:#f6f8fa;--surface-2:#eef1f4;--border:#d8dee4;--text:#1c2024;--text-dim:#5b6470;--accent:#3b5bdb}}*{box-sizing:border-box}body{background:var(--bg);color:var(--text);margin:0;font:13px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}.muted{color:var(--text-dim)}.aaa-wrap{padding:4px 2px 16px}.aaa-titlebar{padding:6px 8px 10px}.aaa-title{font-size:15px;font-weight:600}.aaa-tabs{border-bottom:1px solid var(--border);flex-wrap:wrap;gap:2px;margin-bottom:12px;display:flex}.aaa-tab{appearance:none;color:var(--text-dim);font:inherit;cursor:pointer;background:0 0;border:none;border-bottom:2px solid #0000;margin-bottom:-1px;padding:7px 11px;font-size:12.5px}.aaa-tab:hover{color:var(--text)}.aaa-tab.is-active{color:var(--text);border-bottom-color:var(--accent)}.aaa-bar{align-items:center;gap:8px;padding:0 8px 10px;display:flex}.aaa-bar .spacer{flex:1}.btn{font:inherit;color:var(--text);background:var(--surface-2);border:1px solid var(--border);cursor:pointer;border-radius:8px;padding:4px 10px;font-size:12px}.btn:hover{border-color:var(--accent)}.btn.primary{border-color:color-mix(in srgb, var(--accent) 55%, var(--border));color:var(--accent)}.btn.danger{border-color:color-mix(in srgb, var(--danger) 45%, var(--border));color:var(--danger)}.aaa-error{color:var(--danger);background:color-mix(in srgb, var(--danger) 12%, transparent);border:1px solid color-mix(in srgb, var(--danger) 35%, var(--border));border-radius:8px;margin:0 8px 10px;padding:8px 10px;font-size:12px}.aaa-notice{color:var(--text-dim);background:var(--surface);border:1px solid var(--border);border-radius:10px;margin:0 8px;padding:14px;font-size:12.5px}.aaa-table{padding:0 8px}.aaa-row{grid-template-columns:repeat(var(--cols), minmax(70px, 1fr)) minmax(150px, auto);border-radius:8px;align-items:center;gap:8px;padding:7px 8px;font-size:12.5px;display:grid}.aaa-row.aaa-head{color:var(--text-dim);text-transform:uppercase;letter-spacing:.04em;font-size:10.5px}.aaa-row:not(.aaa-head):hover{background:var(--surface)}.aaa-row.is-off .aaa-cell{color:var(--text-dim)}.aaa-cell{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.aaa-actions{justify-content:flex-end;gap:5px;display:flex}.aaa-actions .btn{padding:3px 8px}.aaa-badge{border-radius:100px;padding:1px 7px;font-size:10.5px;display:inline-block}.aaa-badge.on{background:color-mix(in srgb, var(--ok) 20%, transparent);color:var(--ok)}.aaa-badge.off{background:color-mix(in srgb, var(--text-dim) 22%, transparent);color:var(--text-dim)}.aaa-form,.aaa-card{border:1px solid var(--border);background:var(--surface-2);border-radius:10px;margin:0 8px 12px;padding:12px}.aaa-form-title{margin-bottom:10px;font-size:12.5px;font-weight:600}.aaa-current{color:var(--text-dim);margin-bottom:10px;font-size:11.5px}.aaa-form-grid{grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:9px 12px;display:grid}.aaa-field{flex-direction:column;gap:3px;display:flex}.aaa-field-label{color:var(--text-dim);font-size:11px}.aaa-input{font:inherit;color:var(--text);background:var(--bg);border:1px solid var(--border);border-radius:7px;padding:5px 8px;font-size:12.5px}.aaa-input:focus{border-color:var(--accent);outline:none}.aaa-form-actions{align-items:center;gap:8px;margin-top:12px;display:flex}.aaa-settings{flex-direction:column;gap:4px;display:flex}
@@ -116,7 +116,7 @@ Boolean requesting whether a visible border and background is provided by the ho
116
116
  - omitted: host decides border`)}),I({method:V(`ui/request-display-mode`),params:I({mode:mv.describe(`The display mode being requested.`)})});var Av=I({mode:mv.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),jv=R([V(`model`),V(`app`)]).describe(`Tool visibility scope - who can access the tool.`);I({resourceUri:j().optional(),visibility:F(jv).optional().describe(`Who can access this tool. Default: ["model", "app"]
117
117
  - "model": Tool visible to and callable by the agent
118
118
  - "app": Tool callable by the app from this server only`),csp:Jf().optional(),permissions:Jf().optional()}),I({mimeTypes:F(j()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),I({method:V(`ui/download-file`),params:I({contents:F(R([r_,i_])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),I({method:V(`ui/message`),params:I({role:V(`user`).describe(`Message role, currently only "user" is supported.`),content:F(a_).describe(`Message content blocks (text, image, etc.).`)})}),I({method:V(`ui/notifications/sandbox-resource-ready`),params:I({html:j().describe(`HTML content to load into the inner iframe.`),sandbox:j().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:yv.optional().describe(`CSP configuration from resource metadata.`),permissions:bv.optional().describe(`Sandbox permissions from resource metadata.`)})});var Mv=I({method:V(`ui/notifications/tool-result`),params:m_.describe(`Standard MCP tool execution result.`)}),Nv=I({toolInfo:I({id:Ph.optional().describe(`JSON-RPC id of the tools/call request.`),tool:d_.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:pv.optional().describe(`Current color theme preference.`),styles:Tv.optional().describe(`Style configuration for theming the app.`),displayMode:mv.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:F(mv).optional().describe(`Display modes the host supports.`),containerDimensions:R([I({height:M().describe(`Fixed container height in pixels.`)}),I({maxHeight:R([M(),Gf()]).optional().describe(`Maximum container height in pixels.`)})]).and(R([I({width:M().describe(`Fixed container width in pixels.`)}),I({maxWidth:R([M(),Gf()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
119
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),Pv=I({method:V(`ui/notifications/host-context-changed`),params:Nv.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(a_).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:Yh.describe(`App identification (name and version).`),appCapabilities:kv.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var Fv=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Yh.describe(`Host application identification and version.`),hostCapabilities:Ov.describe(`Features and capabilities provided by the host.`),hostContext:Nv.describe(`Rich context about the host environment.`)}).passthrough(),Iv={target:`draft-2020-12`};async function Lv(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](Iv);if(n.vendor===`zod`){let{z:n}=await lv(async()=>{let{z:e}=await Promise.resolve().then(()=>(Ch(),xh));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Rv(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function zv(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function Bv(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function Vv(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function Hv(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}var Uv=class e extends uv{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:xv,toolinputpartial:Sv,toolresult:Mv,toolcancelled:Cv,hostcontextchanged:Pv};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||a({jitless:!0}),this.setRequestHandler(ag,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=av(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Rv(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Rv(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Lv(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Lv(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(Ev,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(g_,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(f_,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},m_,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},zg,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},Ng,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?M_:j_;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},vv,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Wh,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},gv,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},_v,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},Av,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new fv(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:dv}},Fv,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function $(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))e===`class`?r.className=n:r.setAttribute(e,n);for(let e of n.flat())e===!1||e==null||r.append(e instanceof Node?e:document.createTextNode(String(e)));return r}function Wv(e,t,n={}){let r=$(`button`,{class:`btn${n.class?` ${n.class}`:``}`,...n.title?{title:n.title}:{}});return r.textContent=e,n.disabled&&(r.disabled=!0),r.addEventListener(`click`,t),r}function Gv(e){if(e==null)return`—`;let t=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],n=0,r=e;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(+(r<10&&n>0))} ${t[n]}`}function Kv(e){e.onhostcontextchanged=e=>{if(e.theme&&Bv(e.theme),e.styles?.variables&&Vv(e.styles.variables),e.styles?.css?.fonts&&Hv(e.styles.css.fonts),e.safeAreaInsets){let{top:t,right:n,bottom:r,left:i}=e.safeAreaInsets;document.body.style.padding=`${t+16}px ${n+16}px ${r+16}px ${i+16}px`}},Bv(zv())}var qv=document.getElementById(`app`),Jv=`http://www.w3.org/2000/svg`,Yv=40,Xv=2e3,Zv=null,Qv=null,$v=[],ey=null,ty=!1,ny=null,ry=null,iy=new Uv({name:`mikrotik-connected-devices`,version:`1.0.0`});function ay(e){return`${(e/1e6).toFixed(2)} Mbps`}function oy(){return Zv?.devices.find(e=>e.mac===Qv)}function sy(){ny&&clearInterval(ny),ny=null}function cy(e){sy(),$v=[],ey=null;let t=async()=>{try{let t=(await iy.callServerTool({name:`get_device_traffic`,arguments:{ip:e}})).structuredContent;if(!t||t.ip!==e)return;ey=t,$v.push({rx:t.rxBitsPerSec,tx:t.txBitsPerSec}),$v.length>Yv&&$v.shift(),uy()}catch(e){console.error(`[connected-devices] traffic poll failed`,e)}};t(),ny=setInterval(()=>void t(),Xv)}function ly(){let e=document.createElementNS(Jv,`svg`);e.setAttribute(`viewBox`,`0 0 460 140`),e.setAttribute(`class`,`traffic-chart`);let t=Math.max(1,...$v.flatMap(e=>[e.rx,e.tx])),n=e=>6+e*448/Math.max(1,Yv-1),r=e=>134-e/t*128,i=(t,i)=>{if($v.length<2)return;let a=$v.map((e,i)=>`${n(i).toFixed(1)},${r(t(e)).toFixed(1)}`).join(` `),o=document.createElementNS(Jv,`polygon`),s=n(0).toFixed(1),c=n($v.length-1).toFixed(1);o.setAttribute(`points`,`${s},134 ${a} ${c},134`),o.setAttribute(`class`,`${i} area`),e.appendChild(o);let l=document.createElementNS(Jv,`polyline`);l.setAttribute(`points`,a),l.setAttribute(`class`,`${i} line`),e.appendChild(l)};return i(e=>e.rx,`rx`),i(e=>e.tx,`tx`),e}function uy(){let e=document.getElementById(`detail`);if(!e)return;let t=oy();if(e.replaceChildren(),!t){e.appendChild($(`div`,{class:`muted`},`Select a device to see its traffic.`));return}e.appendChild($(`div`,{class:`detail-title`},t.host||t.comment||t.ip)),e.appendChild($(`div`,{class:`detail-sub`},`${t.ip} · ${t.mac} · ${t.iface||`?`} · ${t.status}`)),ey&&ey.source===`none`?e.appendChild($(`div`,{class:`muted note`},`No per-device counter. Ask: “create a simple queue for this device” to enable Download/Upload tracking.`)):(e.appendChild($(`div`,{class:`rates`},$(`span`,{class:`rate rx`},`↓ ${ey?ay(ey.rxBitsPerSec):`…`}`),$(`span`,{class:`rate tx`},`↑ ${ey?ay(ey.txBitsPerSec):`…`}`))),e.appendChild(ly()),ey&&e.appendChild($(`div`,{class:`totals muted`},`total ↓ ${Gv(ey.rxBytes)} · ↑ ${Gv(ey.txBytes)}`)))}function dy(e){e&&typeof e==`object`&&e.__mikrotikView===`connected-devices`&&(Zv=e,my())}async function fy(e,t){if(!ty){ty=!0,my();try{dy((await iy.callServerTool({name:e,arguments:{mac:t}})).structuredContent)}catch(t){console.error(`[connected-devices] ${e} failed`,t)}finally{ty=!1,my()}}}async function py(){if(!ty){ty=!0,my();try{dy((await iy.callServerTool({name:`list_connected_devices`,arguments:{}})).structuredContent)}catch(e){console.error(`[connected-devices] refresh failed`,e)}finally{ty=!1,my()}}}function my(){if(!Zv){qv.replaceChildren($(`div`,{class:`muted loading`},`Loading connected devices…`));return}let e=Zv.counts,t=$(`div`,{class:`toolbar`},$(`div`,{class:`title`},`Connected Devices`),$(`div`,{class:`counts muted`},`${e.total} total · ${e.static} static · ${e.blocked} blocked`),Wv(`↻ Refresh`,()=>void py(),{class:ty?`is-busy`:``})),n=Zv.devices.map(e=>{let t=$(`div`,{class:`row${e.mac===Qv?` is-selected`:``}${e.blocked?` is-blocked`:``}`},$(`span`,{class:`cell ip`},e.ip||`—`),$(`span`,{class:`cell name`},e.host||e.comment||`(unknown)`),$(`span`,{class:`cell mac mono`},e.mac),$(`span`,{class:`cell iface`},e.iface||``),$(`span`,{class:`cell badges`},e.static?$(`span`,{class:`badge static`},`static`):null,e.blocked?$(`span`,{class:`badge blocked`},`blocked`):null),$(`span`,{class:`cell actions`},e.blocked?Wv(`Allow`,()=>void fy(`allow_device`,e.mac),{class:`ok`}):Wv(`Block`,()=>void fy(`block_device`,e.mac),{class:`danger`}),e.static?null:Wv(`Pin IP`,()=>void fy(`make_device_static`,e.mac),{class:``})));return t.addEventListener(`click`,t=>{t.target.closest(`.actions`)||(Qv=e.mac,e.ip?cy(e.ip):sy(),my())}),t});qv.replaceChildren(t,$(`div`,{class:`table`},$(`div`,{class:`row header`},$(`span`,{class:`cell ip`},`IP`),$(`span`,{class:`cell name`},`Name`),$(`span`,{class:`cell mac`},`MAC`),$(`span`,{class:`cell iface`},`Iface`),$(`span`,{class:`cell badges`},``),$(`span`,{class:`cell actions`},``)),...n),$(`div`,{id:`detail`,class:`detail`})),uy()}iy.ontoolresult=e=>{console.debug(`[connected-devices] ontoolresult fired`,e),dy(e.structuredContent)},iy.ontoolinput=()=>{Zv||my()},Kv(iy),iy.onteardown=async()=>(sy(),ry&&clearInterval(ry),{}),my(),iy.connect().then(()=>console.debug(`[connected-devices] connect OK`,{hostCaps:iy.getHostCapabilities()})).catch(e=>console.error(`[connected-devices] connect failed`,e)),ry=setInterval(()=>void py(),15e3);
119
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),Pv=I({method:V(`ui/notifications/host-context-changed`),params:Nv.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(a_).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:Yh.describe(`App identification (name and version).`),appCapabilities:kv.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var Fv=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Yh.describe(`Host application identification and version.`),hostCapabilities:Ov.describe(`Features and capabilities provided by the host.`),hostContext:Nv.describe(`Rich context about the host environment.`)}).passthrough(),Iv={target:`draft-2020-12`};async function Lv(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](Iv);if(n.vendor===`zod`){let{z:n}=await lv(async()=>{let{z:e}=await Promise.resolve().then(()=>(Ch(),xh));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Rv(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function zv(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function Bv(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function Vv(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function Hv(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}var Uv=class e extends uv{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:xv,toolinputpartial:Sv,toolresult:Mv,toolcancelled:Cv,hostcontextchanged:Pv};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||a({jitless:!0}),this.setRequestHandler(ag,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=av(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Rv(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Rv(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Lv(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Lv(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(Ev,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(g_,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(f_,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},m_,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},zg,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},Ng,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?M_:j_;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},vv,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Wh,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},gv,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},_v,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},Av,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new fv(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:dv}},Fv,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function $(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))e===`class`?r.className=n:r.setAttribute(e,n);for(let e of n.flat())e===!1||e==null||r.append(e instanceof Node?e:document.createTextNode(String(e)));return r}function Wv(e,t,n={}){let r=$(`button`,{class:`btn${n.class?` ${n.class}`:``}`,...n.title?{title:n.title}:{}});return r.textContent=e,n.disabled&&(r.disabled=!0),r.addEventListener(`click`,t),r}function Gv(e){if(e==null)return`—`;let t=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],n=0,r=e;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(+(r<10&&n>0))} ${t[n]}`}function Kv(e){e.onhostcontextchanged=e=>{if(e.theme&&Bv(e.theme),e.styles?.variables&&Vv(e.styles.variables),e.styles?.css?.fonts&&Hv(e.styles.css.fonts),e.safeAreaInsets){let{top:t,right:n,bottom:r,left:i}=e.safeAreaInsets;document.body.style.padding=`${t+16}px ${n+16}px ${r+16}px ${i+16}px`}},Bv(zv())}var qv=1e4;async function Jv(e,t,n){try{return await e.connect(void 0,{timeout:qv}),console.warn(`[${t}] connected`,{host:e.getHostVersion(),caps:e.getHostCapabilities()}),!0}catch(e){console.error(`[${t}] connect failed`,e);let r=e instanceof Error&&/timed?\s*out/i.test(e.message)?`The MCP App host did not respond — make sure your client supports MCP Apps (ext-apps).`:`Connection failed: ${e instanceof Error?e.message:String(e)}`;return n.replaceChildren($(`div`,{class:`skeleton`},r)),!1}}var Yv=document.getElementById(`app`),Xv=`http://www.w3.org/2000/svg`,Zv=40,Qv=2e3,$v=null,ey=null,ty=[],ny=null,ry=!1,iy=null,ay=null,oy=new Uv({name:`mikrotik-connected-devices`,version:`1.0.0`});function sy(e){return`${(e/1e6).toFixed(2)} Mbps`}function cy(){return $v?.devices.find(e=>e.mac===ey)}function ly(){iy&&clearInterval(iy),iy=null}function uy(e){ly(),ty=[],ny=null;let t=async()=>{try{let t=(await oy.callServerTool({name:`get_device_traffic`,arguments:{ip:e}})).structuredContent;if(!t||t.ip!==e)return;ny=t,ty.push({rx:t.rxBitsPerSec,tx:t.txBitsPerSec}),ty.length>Zv&&ty.shift(),fy()}catch(e){console.error(`[connected-devices] traffic poll failed`,e)}};t(),iy=setInterval(()=>void t(),Qv)}function dy(){let e=document.createElementNS(Xv,`svg`);e.setAttribute(`viewBox`,`0 0 460 140`),e.setAttribute(`class`,`traffic-chart`);let t=Math.max(1,...ty.flatMap(e=>[e.rx,e.tx])),n=e=>6+e*448/Math.max(1,Zv-1),r=e=>134-e/t*128,i=(t,i)=>{if(ty.length<2)return;let a=ty.map((e,i)=>`${n(i).toFixed(1)},${r(t(e)).toFixed(1)}`).join(` `),o=document.createElementNS(Xv,`polygon`),s=n(0).toFixed(1),c=n(ty.length-1).toFixed(1);o.setAttribute(`points`,`${s},134 ${a} ${c},134`),o.setAttribute(`class`,`${i} area`),e.appendChild(o);let l=document.createElementNS(Xv,`polyline`);l.setAttribute(`points`,a),l.setAttribute(`class`,`${i} line`),e.appendChild(l)};return i(e=>e.rx,`rx`),i(e=>e.tx,`tx`),e}function fy(){let e=document.getElementById(`detail`);if(!e)return;let t=cy();if(e.replaceChildren(),!t){e.appendChild($(`div`,{class:`muted`},`Select a device to see its traffic.`));return}e.appendChild($(`div`,{class:`detail-title`},t.host||t.comment||t.ip)),e.appendChild($(`div`,{class:`detail-sub`},`${t.ip} · ${t.mac} · ${t.iface||`?`} · ${t.status}`)),ny&&ny.source===`none`?e.appendChild($(`div`,{class:`muted note`},`No per-device counter. Ask: “create a simple queue for this device” to enable Download/Upload tracking.`)):(e.appendChild($(`div`,{class:`rates`},$(`span`,{class:`rate rx`},`↓ ${ny?sy(ny.rxBitsPerSec):`…`}`),$(`span`,{class:`rate tx`},`↑ ${ny?sy(ny.txBitsPerSec):`…`}`))),e.appendChild(dy()),ny&&e.appendChild($(`div`,{class:`totals muted`},`total ↓ ${Gv(ny.rxBytes)} · ↑ ${Gv(ny.txBytes)}`)))}function py(e){e&&typeof e==`object`&&e.__mikrotikView===`connected-devices`&&($v=e,gy())}async function my(e,t){if(!ry){ry=!0,gy();try{py((await oy.callServerTool({name:e,arguments:{mac:t}})).structuredContent)}catch(t){console.error(`[connected-devices] ${e} failed`,t)}finally{ry=!1,gy()}}}async function hy(){if(!ry){ry=!0,gy();try{py((await oy.callServerTool({name:`list_connected_devices`,arguments:{}})).structuredContent)}catch(e){console.error(`[connected-devices] refresh failed`,e)}finally{ry=!1,gy()}}}function gy(){if(!$v){Yv.replaceChildren($(`div`,{class:`muted loading`},`Loading connected devices…`));return}let e=$v.counts,t=$(`div`,{class:`toolbar`},$(`div`,{class:`title`},`Connected Devices`),$(`div`,{class:`counts muted`},`${e.total} total · ${e.static} static · ${e.blocked} blocked`),Wv(`↻ Refresh`,()=>void hy(),{class:ry?`is-busy`:``})),n=$v.devices.map(e=>{let t=$(`div`,{class:`row${e.mac===ey?` is-selected`:``}${e.blocked?` is-blocked`:``}`},$(`span`,{class:`cell ip`},e.ip||`—`),$(`span`,{class:`cell name`},e.host||e.comment||`(unknown)`),$(`span`,{class:`cell mac mono`},e.mac),$(`span`,{class:`cell iface`},e.iface||``),$(`span`,{class:`cell badges`},e.static?$(`span`,{class:`badge static`},`static`):null,e.blocked?$(`span`,{class:`badge blocked`},`blocked`):null),$(`span`,{class:`cell actions`},e.blocked?Wv(`Allow`,()=>void my(`allow_device`,e.mac),{class:`ok`}):Wv(`Block`,()=>void my(`block_device`,e.mac),{class:`danger`}),e.static?null:Wv(`Pin IP`,()=>void my(`make_device_static`,e.mac),{class:``})));return t.addEventListener(`click`,t=>{t.target.closest(`.actions`)||(ey=e.mac,e.ip?uy(e.ip):ly(),gy())}),t});Yv.replaceChildren(t,$(`div`,{class:`table`},$(`div`,{class:`row header`},$(`span`,{class:`cell ip`},`IP`),$(`span`,{class:`cell name`},`Name`),$(`span`,{class:`cell mac`},`MAC`),$(`span`,{class:`cell iface`},`Iface`),$(`span`,{class:`cell badges`},``),$(`span`,{class:`cell actions`},``)),...n),$(`div`,{id:`detail`,class:`detail`})),fy()}oy.ontoolresult=e=>{console.warn(`[connected-devices] ontoolresult`,e),py(e.structuredContent)},oy.ontoolinput=()=>{$v||gy()},Kv(oy),oy.onteardown=async()=>(ly(),ay&&clearInterval(ay),{}),gy(),Jv(oy,`connected-devices`,Yv).then(e=>{e&&(ay=setInterval(()=>void hy(),15e3))});
120
120
  </script>
121
121
  <style>
122
122
  :root{--bg:#0b0d10;--surface:#14181d;--surface-2:#1b2027;--border:#2a313a;--text:#e8eaed;--text-dim:#9aa0a6;--accent:#7c9cff;--rx:#4ade80;--tx:#f59e0b;--danger:#f2685a;--ok:#4ade80}@media (prefers-color-scheme:light){:root{--bg:#fff;--surface:#f6f8fa;--surface-2:#eef1f4;--border:#d8dee4;--text:#1c2024;--text-dim:#5b6470;--accent:#3b5bdb}}*{box-sizing:border-box}body{background:var(--bg);color:var(--text);margin:0;font:13px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}.mono{font-family:ui-monospace,SF Mono,Menlo,monospace}.muted{color:var(--text-dim)}.loading{padding:24px}.toolbar{border-bottom:1px solid var(--border);align-items:center;gap:12px;padding:12px 14px;display:flex}.toolbar .title{font-size:15px;font-weight:600}.toolbar .counts{font-size:12px}.btn{font:inherit;color:var(--text);background:var(--surface-2);border:1px solid var(--border);cursor:pointer;border-radius:8px;margin-left:auto;padding:5px 10px}.toolbar .btn{margin-left:auto}.btn:hover{border-color:var(--accent)}.btn.is-busy{opacity:.5;pointer-events:none}.table{padding:6px 8px 14px}.row{cursor:pointer;border-radius:8px;grid-template-columns:110px 1.4fr 150px 90px 110px 150px;align-items:center;gap:8px;padding:7px 8px;display:grid}.row.header{cursor:default;color:var(--text-dim);text-transform:uppercase;letter-spacing:.04em;font-size:11px}.row:not(.header):hover{background:var(--surface)}.row.is-selected{background:color-mix(in srgb, var(--accent) 16%, var(--surface))}.row.is-blocked .name,.row.is-blocked .ip{color:var(--text-dim);text-decoration:line-through}.cell{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.cell.mac{color:var(--text-dim);font-family:ui-monospace,monospace;font-size:11.5px}.badge{border-radius:100px;margin-right:4px;padding:1px 7px;font-size:10.5px;display:inline-block}.badge.static{background:color-mix(in srgb, var(--accent) 22%, transparent);color:var(--accent)}.badge.blocked{background:color-mix(in srgb, var(--danger) 22%, transparent);color:var(--danger)}.cell.actions{justify-content:flex-end;gap:6px;display:flex}.cell.actions .btn{margin:0;padding:3px 9px;font-size:12px}.btn.danger{border-color:color-mix(in srgb, var(--danger) 45%, var(--border));color:var(--danger)}.btn.ok{border-color:color-mix(in srgb, var(--ok) 45%, var(--border));color:var(--ok)}.detail{border-top:1px solid var(--border);padding:14px}.detail-title{font-size:14px;font-weight:600}.detail-sub{color:var(--text-dim);margin-bottom:10px;font-size:12px}.note{max-width:460px;font-size:12px}.rates{font-variant-numeric:tabular-nums;gap:16px;margin-bottom:6px;display:flex}.rate{font-weight:600}.rate.rx{color:var(--rx)}.rate.tx{color:var(--tx)}.traffic-chart{background:var(--surface);border:1px solid var(--border);border-radius:10px;width:100%;max-width:460px;height:140px;display:block}.traffic-chart .line{fill:none;stroke-width:2px}.traffic-chart .rx.line{stroke:var(--rx)}.traffic-chart .tx.line{stroke:var(--tx)}.traffic-chart .rx.area{fill:color-mix(in srgb, var(--rx) 18%, transparent);stroke:none}.traffic-chart .tx.area{fill:color-mix(in srgb, var(--tx) 14%, transparent);stroke:none}.totals{font-variant-numeric:tabular-nums;margin-top:6px;font-size:12px}
@@ -116,7 +116,7 @@ Boolean requesting whether a visible border and background is provided by the ho
116
116
  - omitted: host decides border`)}),I({method:V(`ui/request-display-mode`),params:I({mode:mv.describe(`The display mode being requested.`)})});var Av=I({mode:mv.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),jv=R([V(`model`),V(`app`)]).describe(`Tool visibility scope - who can access the tool.`);I({resourceUri:j().optional(),visibility:F(jv).optional().describe(`Who can access this tool. Default: ["model", "app"]
117
117
  - "model": Tool visible to and callable by the agent
118
118
  - "app": Tool callable by the app from this server only`),csp:Jf().optional(),permissions:Jf().optional()}),I({mimeTypes:F(j()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),I({method:V(`ui/download-file`),params:I({contents:F(R([r_,i_])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),I({method:V(`ui/message`),params:I({role:V(`user`).describe(`Message role, currently only "user" is supported.`),content:F(a_).describe(`Message content blocks (text, image, etc.).`)})}),I({method:V(`ui/notifications/sandbox-resource-ready`),params:I({html:j().describe(`HTML content to load into the inner iframe.`),sandbox:j().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:yv.optional().describe(`CSP configuration from resource metadata.`),permissions:bv.optional().describe(`Sandbox permissions from resource metadata.`)})});var Mv=I({method:V(`ui/notifications/tool-result`),params:m_.describe(`Standard MCP tool execution result.`)}),Nv=I({toolInfo:I({id:Ph.optional().describe(`JSON-RPC id of the tools/call request.`),tool:d_.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:pv.optional().describe(`Current color theme preference.`),styles:Tv.optional().describe(`Style configuration for theming the app.`),displayMode:mv.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:F(mv).optional().describe(`Display modes the host supports.`),containerDimensions:R([I({height:M().describe(`Fixed container height in pixels.`)}),I({maxHeight:R([M(),Gf()]).optional().describe(`Maximum container height in pixels.`)})]).and(R([I({width:M().describe(`Fixed container width in pixels.`)}),I({maxWidth:R([M(),Gf()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
119
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),Pv=I({method:V(`ui/notifications/host-context-changed`),params:Nv.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(a_).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:Yh.describe(`App identification (name and version).`),appCapabilities:kv.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var Fv=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Yh.describe(`Host application identification and version.`),hostCapabilities:Ov.describe(`Features and capabilities provided by the host.`),hostContext:Nv.describe(`Rich context about the host environment.`)}).passthrough(),Iv={target:`draft-2020-12`};async function Lv(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](Iv);if(n.vendor===`zod`){let{z:n}=await lv(async()=>{let{z:e}=await Promise.resolve().then(()=>(Ch(),xh));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Rv(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function zv(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function Bv(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function Vv(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function Hv(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}var Uv=class e extends uv{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:xv,toolinputpartial:Sv,toolresult:Mv,toolcancelled:Cv,hostcontextchanged:Pv};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||a({jitless:!0}),this.setRequestHandler(ag,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=av(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Rv(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Rv(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Lv(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Lv(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(Ev,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(g_,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(f_,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},m_,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},zg,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},Ng,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?M_:j_;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},vv,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Wh,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},gv,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},_v,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},Av,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new fv(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:dv}},Fv,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}},Wv=`show_system_dashboard`,Gv=document.getElementById(`app`);function $(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))e===`class`?r.className=n:r.setAttribute(e,n);for(let e of n.flat())e===!1||e==null||r.append(e instanceof Node?e:document.createTextNode(String(e)));return r}function Kv(e){if(e==null)return`—`;let t=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],n=0,r=e;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(+(r<10&&n>0))} ${t[n]}`}function qv(e){return e==null?``:e>=90?`is-bad`:e>=70?`is-warn`:`is-good`}var Jv=`http://www.w3.org/2000/svg`;function Yv(e,t){let n=document.createElementNS(Jv,e);for(let[e,r]of Object.entries(t))n.setAttribute(e,String(r));return n}function Xv(e,t,n){let r=2*Math.PI*26,i=t==null?0:Math.max(0,Math.min(100,t))/100,a=Yv(`svg`,{width:64,height:64,viewBox:`0 0 64 64`}),o=Yv(`circle`,{cx:32,cy:32,r:26,fill:`none`,"stroke-width":7});o.setAttribute(`class`,`gauge__track`);let s=Yv(`circle`,{cx:32,cy:32,r:26,fill:`none`,"stroke-width":7,"stroke-dasharray":r,"stroke-dashoffset":r*(1-i)});s.setAttribute(`class`,`gauge__bar ${qv(t)}`);let c=Yv(`text`,{x:32,y:37,"text-anchor":`middle`});return c.setAttribute(`class`,`gauge__pct`),c.textContent=t==null?`—`:`${Math.round(t)}%`,a.replaceChildren(o,s,c),$(`div`,{class:`card gauge`},a,$(`div`,{class:`gauge__meta`},$(`p`,{class:`card__label`},e),$(`small`,{},n)))}function Zv(e,t){return $(`div`,{class:`card`},$(`p`,{class:`card__label`},e),$(`div`,{class:`card__value`},t))}function Qv(e,t){let n=Object.entries(t);if(n.length===0)return null;let r=$(`div`,{class:`kv__body`},...n.flatMap(([e,t])=>[$(`div`,{class:`kv__k`},e),$(`div`,{class:`kv__v`},t||`—`)]));return $(`details`,{class:`kv`},$(`summary`,{},`${e} (${n.length})`),r)}var $v=null,ey=!1;function ty(){if(!$v){Gv.replaceChildren($(`div`,{class:`skeleton`},`Waiting for device data…`));return}let e=$v,t=e.derived,n=e.resource.version??`?`,r=e.routerboard.model??e.resource[`board-name`]??`?`,i=[Xv(`CPU load`,t.cpuLoadPct,`${e.resource[`cpu-count`]??`?`} cores`),Xv(`Memory`,t.memUsedPct,`${Kv(t.memUsedBytes)} / ${Kv(t.memTotalBytes)}`),t.hddUsedPct!=null&&Xv(`Disk`,t.hddUsedPct,`${Kv(t.hddUsedBytes)} / ${Kv(t.hddTotalBytes)}`)].filter(Boolean),a=[Zv(`Uptime`,e.resource.uptime??`—`),t.temperatureC!=null&&Zv(`Temperature`,`${t.temperatureC} °C`),t.voltageV!=null&&Zv(`Voltage`,`${t.voltageV} V`),Zv(`Architecture`,e.resource[`architecture-name`]??`—`)].filter(Boolean),o=$(`button`,{class:`btn`},ey?`Refreshing…`:`↻ Refresh`);ey&&o.setAttribute(`disabled`,`true`),o.addEventListener(`click`,iy);let s=$(`span`,{class:`pill`},`device `,$(`b`,{},e.device)),c=$(`header`,{class:`hd`},$(`span`,{class:`hd__dot`}),$(`div`,{},$(`h1`,{class:`hd__title`},e.identity),$(`p`,{class:`hd__sub`},`${r} · RouterOS ${n}`)),$(`span`,{class:`hd__spacer`}),s),l=$(`footer`,{class:`foot`},o,$(`span`,{},`updated ${new Date(e.generatedAt).toLocaleTimeString()}`)),u=[c,$(`section`,{class:`grid`},...i),$(`section`,{class:`grid`},...a),Qv(`System resource`,e.resource),Qv(`RouterBOARD`,e.routerboard),l].filter(e=>e!=null);Gv.replaceChildren(...u)}var ny=new Uv({name:`mikrotik-dashboard`,version:`1.0.0`});function ry(e){e&&typeof e==`object`&&`device`in e&&($v=e,ty())}async function iy(){if(!ey){ey=!0,ty();try{ry((await ny.callServerTool({name:Wv,arguments:{}})).structuredContent)}catch(e){console.error(`[dashboard] refresh failed`,e)}finally{ey=!1,ty()}}}ny.ontoolresult=e=>{console.debug(`[dashboard] ontoolresult fired`,e),ry(e.structuredContent)},ny.ontoolinput=()=>{$v||ty()},ny.onhostcontextchanged=e=>{if(e.theme&&Bv(e.theme),e.styles?.variables&&Vv(e.styles.variables),e.styles?.css?.fonts&&Hv(e.styles.css.fonts),e.safeAreaInsets){let{top:t,right:n,bottom:r,left:i}=e.safeAreaInsets;document.body.style.padding=`${t+16}px ${n+16}px ${r+16}px ${i+16}px`}},ny.onteardown=async()=>({}),Bv(zv()),ty(),ny.connect().then(()=>{console.debug(`[dashboard] connect OK`,{hostCaps:ny.getHostCapabilities(),hostCtx:ny.getHostContext()})}).catch(e=>console.error(`[dashboard] connect failed`,e));
119
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),Pv=I({method:V(`ui/notifications/host-context-changed`),params:Nv.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(a_).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:Yh.describe(`App identification (name and version).`),appCapabilities:kv.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var Fv=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Yh.describe(`Host application identification and version.`),hostCapabilities:Ov.describe(`Features and capabilities provided by the host.`),hostContext:Nv.describe(`Rich context about the host environment.`)}).passthrough(),Iv={target:`draft-2020-12`};async function Lv(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](Iv);if(n.vendor===`zod`){let{z:n}=await lv(async()=>{let{z:e}=await Promise.resolve().then(()=>(Ch(),xh));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Rv(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function zv(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function Bv(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function Vv(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function Hv(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}var Uv=class e extends uv{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:xv,toolinputpartial:Sv,toolresult:Mv,toolcancelled:Cv,hostcontextchanged:Pv};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||a({jitless:!0}),this.setRequestHandler(ag,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=av(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Rv(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Rv(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Lv(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Lv(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(Ev,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(g_,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(f_,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},m_,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},zg,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},Ng,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?M_:j_;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},vv,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Wh,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},gv,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},_v,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},Av,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new fv(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:dv}},Fv,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function Wv(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))e===`class`?r.className=n:r.setAttribute(e,n);for(let e of n.flat())e===!1||e==null||r.append(e instanceof Node?e:document.createTextNode(String(e)));return r}var Gv=1e4;async function Kv(e,t,n){try{return await e.connect(void 0,{timeout:Gv}),console.warn(`[${t}] connected`,{host:e.getHostVersion(),caps:e.getHostCapabilities()}),!0}catch(e){console.error(`[${t}] connect failed`,e);let r=e instanceof Error&&/timed?\s*out/i.test(e.message)?`The MCP App host did not respond — make sure your client supports MCP Apps (ext-apps).`:`Connection failed: ${e instanceof Error?e.message:String(e)}`;return n.replaceChildren(Wv(`div`,{class:`skeleton`},r)),!1}}var qv=`show_system_dashboard`,Jv=document.getElementById(`app`);function $(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))e===`class`?r.className=n:r.setAttribute(e,n);for(let e of n.flat())e===!1||e==null||r.append(e instanceof Node?e:document.createTextNode(String(e)));return r}function Yv(e){if(e==null)return`—`;let t=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],n=0,r=e;for(;r>=1024&&n<t.length-1;)r/=1024,n++;return`${r.toFixed(+(r<10&&n>0))} ${t[n]}`}function Xv(e){return e==null?``:e>=90?`is-bad`:e>=70?`is-warn`:`is-good`}var Zv=`http://www.w3.org/2000/svg`;function Qv(e,t){let n=document.createElementNS(Zv,e);for(let[e,r]of Object.entries(t))n.setAttribute(e,String(r));return n}function $v(e,t,n){let r=2*Math.PI*26,i=t==null?0:Math.max(0,Math.min(100,t))/100,a=Qv(`svg`,{width:64,height:64,viewBox:`0 0 64 64`}),o=Qv(`circle`,{cx:32,cy:32,r:26,fill:`none`,"stroke-width":7});o.setAttribute(`class`,`gauge__track`);let s=Qv(`circle`,{cx:32,cy:32,r:26,fill:`none`,"stroke-width":7,"stroke-dasharray":r,"stroke-dashoffset":r*(1-i)});s.setAttribute(`class`,`gauge__bar ${Xv(t)}`);let c=Qv(`text`,{x:32,y:37,"text-anchor":`middle`});return c.setAttribute(`class`,`gauge__pct`),c.textContent=t==null?`—`:`${Math.round(t)}%`,a.replaceChildren(o,s,c),$(`div`,{class:`card gauge`},a,$(`div`,{class:`gauge__meta`},$(`p`,{class:`card__label`},e),$(`small`,{},n)))}function ey(e,t){return $(`div`,{class:`card`},$(`p`,{class:`card__label`},e),$(`div`,{class:`card__value`},t))}function ty(e,t){let n=Object.entries(t);if(n.length===0)return null;let r=$(`div`,{class:`kv__body`},...n.flatMap(([e,t])=>[$(`div`,{class:`kv__k`},e),$(`div`,{class:`kv__v`},t||`—`)]));return $(`details`,{class:`kv`},$(`summary`,{},`${e} (${n.length})`),r)}var ny=null,ry=!1;function iy(){if(!ny){Jv.replaceChildren($(`div`,{class:`skeleton`},`Waiting for device data…`));return}let e=ny,t=e.derived,n=e.resource.version??`?`,r=e.routerboard.model??e.resource[`board-name`]??`?`,i=[$v(`CPU load`,t.cpuLoadPct,`${e.resource[`cpu-count`]??`?`} cores`),$v(`Memory`,t.memUsedPct,`${Yv(t.memUsedBytes)} / ${Yv(t.memTotalBytes)}`),t.hddUsedPct!=null&&$v(`Disk`,t.hddUsedPct,`${Yv(t.hddUsedBytes)} / ${Yv(t.hddTotalBytes)}`)].filter(Boolean),a=[ey(`Uptime`,e.resource.uptime??`—`),t.temperatureC!=null&&ey(`Temperature`,`${t.temperatureC} °C`),t.voltageV!=null&&ey(`Voltage`,`${t.voltageV} V`),ey(`Architecture`,e.resource[`architecture-name`]??`—`)].filter(Boolean),o=$(`button`,{class:`btn`},ry?`Refreshing…`:`↻ Refresh`);ry&&o.setAttribute(`disabled`,`true`),o.addEventListener(`click`,sy);let s=$(`span`,{class:`pill`},`device `,$(`b`,{},e.device)),c=$(`header`,{class:`hd`},$(`span`,{class:`hd__dot`}),$(`div`,{},$(`h1`,{class:`hd__title`},e.identity),$(`p`,{class:`hd__sub`},`${r} · RouterOS ${n}`)),$(`span`,{class:`hd__spacer`}),s),l=$(`footer`,{class:`foot`},o,$(`span`,{},`updated ${new Date(e.generatedAt).toLocaleTimeString()}`)),u=[c,$(`section`,{class:`grid`},...i),$(`section`,{class:`grid`},...a),ty(`System resource`,e.resource),ty(`RouterBOARD`,e.routerboard),l].filter(e=>e!=null);Jv.replaceChildren(...u)}var ay=new Uv({name:`mikrotik-dashboard`,version:`1.0.0`});function oy(e){e&&typeof e==`object`&&`device`in e&&(ny=e,iy())}async function sy(){if(!ry){ry=!0,iy();try{oy((await ay.callServerTool({name:qv,arguments:{}})).structuredContent)}catch(e){console.error(`[dashboard] refresh failed`,e)}finally{ry=!1,iy()}}}ay.ontoolresult=e=>{console.warn(`[dashboard] ontoolresult`,e),oy(e.structuredContent)},ay.ontoolinput=()=>{ny||iy()},ay.onhostcontextchanged=e=>{if(e.theme&&Bv(e.theme),e.styles?.variables&&Vv(e.styles.variables),e.styles?.css?.fonts&&Hv(e.styles.css.fonts),e.safeAreaInsets){let{top:t,right:n,bottom:r,left:i}=e.safeAreaInsets;document.body.style.padding=`${t+16}px ${n+16}px ${r+16}px ${i+16}px`}},ay.onteardown=async()=>({}),Bv(zv()),iy(),Kv(ay,`dashboard`,Jv);
120
120
  </script>
121
121
  <style>
122
122
  :root{--mt-bg:var(--color-background-primary,#0b0d10);--mt-surface:var(--color-background-secondary,#14171c);--mt-surface-2:var(--color-background-tertiary,#1b1f26);--mt-border:var(--color-border-primary,#262b33);--mt-text:var(--color-text-primary,#e8eaed);--mt-text-dim:var(--color-text-secondary,#9aa3af);--mt-text-faint:var(--color-text-tertiary,#6b7280);--mt-accent:var(--color-accent-primary,#6ea8fe);--mt-good:#34d399;--mt-warn:#fbbf24;--mt-bad:#f87171;--mt-radius:var(--border-radius-md,14px);--mt-radius-sm:var(--border-radius-sm,9px);--mt-mono:var(--font-mono,ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace);--mt-sans:var(--font-sans,system-ui, -apple-system, "Segoe UI", sans-serif);--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light dark}@media (prefers-color-scheme:dark){:root{--lightningcss-light: ;--lightningcss-dark:initial}}*{box-sizing:border-box}body{background:var(--mt-bg);color:var(--mt-text);font-family:var(--mt-sans);-webkit-font-smoothing:antialiased;margin:0;padding:16px;font-size:13px;line-height:1.5}.app{gap:14px;max-width:860px;margin:0 auto;display:grid}.hd{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.hd__dot{background:var(--mt-good);width:9px;height:9px;box-shadow:0 0 0 4px color-mix(in srgb, var(--mt-good) 22%, transparent);border-radius:50%}.hd__title{letter-spacing:-.01em;margin:0;font-size:17px;font-weight:650}.hd__sub{color:var(--mt-text-dim);font-family:var(--mt-mono);margin:0;font-size:12px}.hd__spacer{flex:1}.pill{border:1px solid var(--mt-border);background:var(--mt-surface);color:var(--mt-text-dim);font-family:var(--mt-mono);border-radius:999px;align-items:center;gap:6px;padding:3px 9px;font-size:11px;display:inline-flex}.pill b{color:var(--mt-text);font-weight:600}.grid{grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;display:grid}.card{background:linear-gradient(180deg, var(--mt-surface), var(--mt-surface-2));border:1px solid var(--mt-border);border-radius:var(--mt-radius);padding:14px}.card__label{color:var(--mt-text-dim);text-transform:uppercase;letter-spacing:.06em;margin:0 0 8px;font-size:11px}.card__value{font-family:var(--mt-mono);letter-spacing:-.01em;font-size:20px;font-weight:600}.card__value small{color:var(--mt-text-dim);font-size:12px;font-weight:400}.gauge{align-items:center;gap:14px;display:flex}.gauge svg{flex:none}.gauge__track{stroke:var(--mt-surface-2)}.gauge__bar{stroke:var(--mt-accent);stroke-linecap:round;transform-origin:50%;transition:stroke-dashoffset .6s cubic-bezier(.2,.8,.2,1);transform:rotate(-90deg)}.gauge__pct{font-family:var(--mt-mono);fill:var(--mt-text);font-size:16px;font-weight:650}.gauge__meta{min-width:0}.gauge__meta .card__label{margin-bottom:4px}.gauge__meta small{color:var(--mt-text-faint);font-family:var(--mt-mono);font-size:11px}.is-good{stroke:var(--mt-good)}.is-warn{stroke:var(--mt-warn)}.is-bad{stroke:var(--mt-bad)}details.kv{background:var(--mt-surface);border:1px solid var(--mt-border);border-radius:var(--mt-radius);overflow:hidden}details.kv>summary{cursor:pointer;color:var(--mt-text-dim);-webkit-user-select:none;user-select:none;padding:12px 14px;font-weight:600;list-style:none}details.kv>summary::-webkit-details-marker{display:none}details.kv>summary:after{content:"▸";float:right;color:var(--mt-text-faint);transition:transform .2s}details.kv[open]>summary:after{transform:rotate(90deg)}.kv__body{border-top:1px solid var(--mt-border);grid-template-columns:minmax(120px,.4fr) 1fr;display:grid}.kv__body>div{border-bottom:1px solid color-mix(in srgb, var(--mt-border) 55%, transparent);overflow-wrap:anywhere;min-width:0;padding:7px 14px;font-size:12px}.kv__k{color:var(--mt-text-dim);font-family:var(--mt-mono)}.kv__v{font-family:var(--mt-mono);color:var(--mt-text)}.foot{color:var(--mt-text-faint);font-size:11px;font-family:var(--mt-mono);align-items:center;gap:10px;display:flex}.btn{appearance:none;border:1px solid var(--mt-border);background:var(--mt-surface);color:var(--mt-text);font:inherit;border-radius:var(--mt-radius-sm);cursor:pointer;padding:5px 11px;font-size:12px;transition:border-color .15s,background .15s}.btn:hover{border-color:var(--mt-accent);background:var(--mt-surface-2)}.btn:disabled{opacity:.5;cursor:default}.skeleton{color:var(--mt-text-faint);text-align:center;padding:40px 0}