Thursday, November 26, 2026

MERCURY AGENT FOR DUMMIES



A friendly, deep, jargon-light field guide for developers, users and admins who have never touched an agentic AI platform before.


A short note before we begin


This guide is written for three kinds of reader at once. If you're a user who simply wants a clever assistant that can run errands on your own machine, you'll find plain recipes you can copy. If you're an administrator who has to keep the thing safe and running, you'll find the knobs that matter. And if you're a developer who wants to teach Mercury new tricks, you'll find the extension points and real code.

Mercury Agent can be downloaded from https://github.com/ms1963/mercury_agent


What Mercury Agent actually is


Mercury Agent is a self-hosted, extensible agentic AI platform written in TypeScript. That sentence hides three ideas worth unpacking slowly. "Self-hosted" means Mercury runs on your computer or your server, keeps its data in a hidden folder in your home directory, and sends nothing to the outside world except the messages you deliberately forward to whichever AI service you chose. "Agentic" means Mercury doesn't merely chat; it can decide to take actions - read a file, run a shell command, fetch a web page, call an external service - observe the result, and keep going until the job is done. "Platform" means it's not a single program but a small ecosystem: a command-line tool, a web interface, connectors to nineteen chat platforms, multi-agent workflows, a persistent memory, a library of more than seventy-five built-in tools, and a bridge to the Model Context Protocol that works in both directions.


The single most important thing to understand on day one is that Mercury has no brain of its own. It ships with no built-in language model. Think of Mercury as an extremely capable body - hands, eyes, memory, judgement about when to act - that needs you to plug in a brain before it can think. That brain is a Large Language Model (an LLM), and you can supply it from the cloud through providers such as OpenRouter or Abacus.AI ChatLLM, or entirely from your own machine through Ollama or LM Studio. Until you connect at least one real provider, Mercury can start up and show you its interface, but it can't answer a question.


The subsystems you'll meet as you read on fit together like this. A core agent loop decides what to do next and calls tools to do it. A model router chooses which LLM to use for each task so that a trivial question doesn't burn an expensive model. An optional typed decision engine called Jev makes the sharper judgements - which model, how risky a tool call is, whether an incoming message deserves a human - and degrades gracefully to simpler heuristics when it's absent. A gateway layer connects Mercury to Telegram, Slack, Discord, email and many more. A scheduler runs tasks on a cron or in plain English. A workflow engine coordinates several cooperating agents. A voice subsystem turns speech into text and text back into speech. A skills system lets Mercury learn reusable procedures, and a tools system lets it act. Finally, the Model Context Protocol support lets Mercury borrow tools from other programs and lend its own tools to clients such as desktop AI apps.


One honesty note that matches the project's own documentation: as of the current release the core agent loop has been exercised against real LLMs, while the Jev engine, the chat gateways and the voice features are documented and covered by the offline test suite but have not all been proven against live third-party services. Where that matters below, I say so plainly rather than pretending everything has been battle-tested in production.


1. Installing Node.js and then Mercury Agent


Mercury runs on Node.js, the free runtime that executes JavaScript and TypeScript outside a browser, and it needs version 22.5 or newer because it relies on features that only arrived in that release, including the built-in SQLite database. Before anything else, open a terminal and ask Node which version you have.



node -v



If that prints something like v22.5.0 or higher you're ready. If it prints a smaller number or an error, visit https://nodejs.org, download the large green "LTS" button, install it the way you would install any ordinary application, and then run "node -v" once more to confirm the upgrade took hold. This is the only piece of software you ever install by hand; Mercury pulls in everything else it needs on its own.


With Node in place, fetch the Mercury source, step into its folder, install its dependencies and compile it. The three commands below are meant to be run one at a time, and the middle one can take a minute or two the first time because it downloads the project's libraries.



git clone https://github.com/ms1963/mercury_agent.git mercury

cd mercury

npm install

npm run build



The clone step copies the project onto your machine, "npm install" downloads the libraries Mercury depends on, and "npm run build" turns the TypeScript source into the JavaScript that Node actually runs. After the build you can always invoke Mercury through its compiled entry point, which is handy to know when a global shortcut isn't set up.



node packages/cli/dist/bin.js setup

node packages/cli/dist/bin.js serve



Typing that long path every time is tedious, so most people make a global "mercury" command once. The project ships an installer that both builds and links the command for you, and after it runs you can simply type "mercury" from anywhere.



./install.sh

mercury --help



If you would rather not touch your system at all, Mercury runs just as well inside a container, and the data survives restarts because it lives in a named volume rather than inside the container.



docker compose up -d



The default container image is deliberately slim and leaves out the heavier offline voice engines. If you want fully offline speech inside the container you build the voice-enabled variant instead, which additionally bundles ffmpeg, Whisper and Piper at the cost of a larger image.



docker compose --profile voice up -d --build mercury-voice



However you installed it, the very first time you run Mercury you should run its interactive setup, which walks you through creating an administrator account and choosing your first LLM provider. A small but important rule applies in the web interface: the first account that registers becomes the administrator, so register yourself before you expose the interface to anyone else.



mercury setup



Mercury keeps all of its state - your configuration, your conversations, your memory, your skills - in a hidden folder called .mercury inside your home directory. You can move that somewhere else by setting the MERCURY\_HOME environment variable, which is useful when you want several isolated instances or when you keep your home directory small.


2. Giving Mercury a brain: OpenRouter or Ollama


Mercury identifies every model with a two-part name of the form provider/model, for example openai/gpt-4o-mini or ollama/llama3.1. You pick the active one with the "mercury model" command, with the llm.defaultModel configuration key, or with the /model slash command inside a chat. A crucial separation keeps your secrets safe: API keys belong in the file ~/.mercury/.env or in the process environment and never in the configuration file, while the wiring that describes a provider belongs in ~/.mercury/config.yaml. Keeping keys out of config means you can share or back up your config without leaking a secret.


The remote route most people reach for is OpenRouter, a single service that resells hundreds of models behind one key. You drop the key into the environment file and then name an OpenRouter model. Because the key is present, Mercury auto-enables OpenRouter without any further configuration entry, and as a pleasant side effect the optional Jev decision engine becomes available too.



echo 'OPENROUTER_API_KEY=sk-or-...' >> ~/.mercury/.env

mercury model openrouter/openai/gpt-4o-mini



The full model name there reads a little oddly because it's layered: "openrouter" is the Mercury provider, and "openai/gpt-4o-mini" is the model as OpenRouter itself names it, so you can swap in "openrouter/anthropic/claude-3.5-sonnet" or any other model OpenRouter exposes simply by changing the tail.


The local route, which keeps every token on your own machine, is Ollama. You install Ollama from https://ollama.com, pull a model so it exists on disk, and then tell Mercury that the Ollama provider is enabled and which model to use. Ollama needs no API key because it runs locally, which is exactly why you must enable it explicitly: Mercury auto-enables cloud providers when it spots their key in the environment, but a keyless local provider has no key to spot, so you declare it on purpose.



ollama pull llama3.1

mercury config set llm.providers.ollama '{"type":"ollama","enabled":true}'

mercury model ollama/llama3.1



By default Mercury talks to Ollama at http://localhost:11434/v1, which is correct when Ollama runs on the same computer. If your Ollama lives on another machine on your network, add a baseUrl field that points at it, keeping the "/v1" suffix because that's the OpenAI-compatible path Mercury speaks.



mercury config set llm.providers.ollama '{"type":"ollama","baseUrl":"http://192.168.1.50:11434/v1","enabled":true}'



You're not forced to choose one brain forever. You can configure several providers at once and leave llm.defaultModel set to the special value "auto", at which point the model router picks a sensible model for each individual task instead of using a single fixed one. That's how you let cheap models handle easy questions while reserving an expensive model for the hard ones.


3. Configuring Jev, and why you might want to


Jev is Mercury's optional typed decision engine. Where an ordinary LLM writes prose, Jev answers narrow, structured questions - a choice among options, a yes or no, a numeric score - and attaches a confidence to each answer. Mercury uses those crisp judgements in several places at once: to route a task to the right model, to classify whether an incoming instruction looks like a prompt-injection attack, to decide smartly whether a tool call really needs your approval, to triage messages arriving from chat platforms, and to drive retry and reflection decisions when a step goes wrong. The model behind it is typesafe/jev-1.13, reached through OpenRouter, which is why setting your OpenRouter key quietly switches Jev on.


You control Jev with a single configuration key, decision.provider, and its four settings describe a spectrum from automatic to fully offline. The default, "auto", uses Jev only when an OpenRouter key is present and otherwise falls back first to your normal LLM and finally to a safe built-in heuristic, so it's the setting that simply does the right thing. Choosing "jev" forces Jev on and therefore requires the OpenRouter key. Choosing "llm" tells Mercury to make these decisions with your ordinary language model and never call Jev. Choosing "mock" uses only a deterministic heuristic with no network calls at all, which is what the test suite uses.



mercury config set decision.provider auto



The reason to care is partly quality and partly cost and privacy. A dedicated decision model tends to make sharper routing and risk judgements than asking a general chat model to reason about them in prose, and because those judgements are small and structured they are cheap. At the same time Mercury is explicit that it runs perfectly well without Jev - every decision degrades to the configured LLM or to the heuristic - so if you prefer to keep all traffic on a single provider, or to run entirely offline, set decision.provider to "llm" or "mock" and nothing breaks. The current release notes that the Jev engine itself has been exercised in the offline and mock paths rather than extensively against the live decision model, so treat the automatic fallback as a feature, not a disappointment.


4. Integrating external applications such as Telegram


The gateway is the part of Mercury that connects it to chat platforms, and it speaks to a long list of them: Telegram, Discord, Slack, WhatsApp through the Cloud API, Signal through a signal-cli server, Matrix, Mattermost, Microsoft Teams, IRC, email over IMAP and SMTP, SMS through Twilio, Home Assistant, RSS feeds, a generic inbound webhook, the built-in web chat and the terminal itself. The pattern is the same for all of them. You describe one adapter under gateway.adapters in the configuration file, giving its secrets through environment variables so they never sit in the config, you start the server, and the first time an unknown person messages your bot they receive a pairing code that you link to your Mercury account so conversations can follow you across platforms.


Telegram is the gentlest first integration because it uses long polling, which means Mercury reaches out to Telegram and no public URL or webhook is required. You begin inside Telegram itself by talking to the account named BotFather, which hands you a bot token. You then give that token to Mercury, either inline in the adapter config or, better, through the TELEGRAM\_BOT\_TOKEN environment variable, and you make sure the gateway is switched on.



echo 'TELEGRAM_BOT_TOKEN=123456:AA...' >> ~/.mercury/.env

mercury config set gateway.enabled true

mercury config set gateway.adapters.telegram '{"type":"telegram"}'



With the adapter declared you start the server, which runs the web interface, the REST API and the gateway together, and then you message your new bot from your own Telegram account. The bot replies with a pairing code; you claim it once from the terminal, after which your Telegram identity is mapped to your Mercury user and stays mapped.



mercury serve

mercury gateway pair 482913



A nice consequence of pairing is that the slash commands you'll meet in the next section work from Telegram too, so once paired you can type /model or /usage straight from the chat app. Voice memos you send are transcribed automatically, and any message the Jev triage is unsure about is placed in a human review queue rather than acted on blindly. Platforms that receive messages through webhooks rather than polling - Slack, Discord, WhatsApp and the generic webhook among them - additionally need their endpoint reachable from the internet, so for those you also set server.publicUrl; Telegram, being a polling adapter, needs none of that.


5. Conducting a user chat


There are three comfortable ways to talk to Mercury, and they all share the same underlying agent, so a conversation is a conversation wherever you hold it. The quickest is a one-shot question from the terminal, where you pass your message as an argument and Mercury answers once and exits, which is ideal for scripts.



mercury chat "Summarise the README in three sentences"



When you want a back-and-forth you start the interactive read-eval-print loop by running the same command with no message, which drops you into a prompt where each line you type is a new turn and Mercury keeps the context between turns.



mercury chat



For anything visual - watching tool calls happen, browsing past sessions, managing approvals - you run the server and open the web interface in a browser, which also exposes the REST API that other programs can call.



mercury serve --port 3000



Inside any of these surfaces you steer the conversation with slash commands, which behave identically in the terminal, the web chat and every paired chat platform. You begin a clean session with /new or /reset, you inspect or change the model for just this session with /model, and you switch the reasoning style with /pattern, choosing among approaches such as react, plan-execute and reflexion. You re-run your last message with /retry, remove the last exchange with /undo, and halt a long-running agent with /stop. When a session grows large you compress it with /compress, which summarises the history to save context space, and you keep an eye on spend with /usage and /insights. Approvals that are waiting for you appear with /approve and /deny, and you look under the hood with /memory, /tools, /sessions and /debug. A single example shows the shape of them all.



/model ollama/llama3.1



If you never want to memorise any of these, /help prints the list, and /help followed by a topic prints focused guidance on that topic.


6. Using scheduled tasks


Mercury can act on your behalf while you're away by scheduling tasks, and the pleasant surprise is that you can describe the timing in plain English instead of memorising cron syntax. You add a task with "mercury schedule add", giving it a time with the --when option and then the instruction itself as ordinary prose. The scheduler understands phrases such as recurring weekday mornings, fixed intervals and one-off reminders.



mercury schedule add --when "every weekday at 9am" Summarise my inbox

mercury schedule add --when "in 20 minutes" Remind me to stretch



If you prefer the precision of cron, or if a phrase is too unusual for the parser to understand, you can supply a standard five-field cron expression in exactly the same place, and Mercury treats it the same way.



mercury schedule add --when "0 */6 * * *" Check the build status



Results are delivered back to wherever the task came from - the CLI log, the web interface, or a chat platform such as Telegram - and you can redirect delivery explicitly. You manage the whole collection with a family of subcommands that list, edit, pause, resume, delete and run tasks, and editing is a first-class operation so you never have to delete and recreate a schedule just to change one field. Passing a new --when recomputes the next run time.



mercury schedule list

mercury schedule edit 7 --when "every 3 hours" --name "AI News" --task "Summarise top AI headlines"

mercury schedule edit 7 --deliver telegram:123456 --max-retries 5



The same thing is available visually in the Scheduler panel of the web interface, where an Edit button on each row opens an inline editor with the name, timing and task prefilled so you change what you need and press Save.


7. Using workflows


A workflow is how you get several agents to cooperate on one job, and you describe it declaratively in a small YAML file that names a template type and lists the agents involved. The template decides the shape of the collaboration, and Mercury ships a generous set of them: a single agent, a pipeline where each agent feeds the next, a round-robin, a coordinator with workers, a tree, a map-reduce, a router, a shared blackboard, a debate between opposing agents, and a planner paired with an executor. A pipeline is the easiest to picture because the agents simply form an assembly line, and the special token {previous} hands one agent's output to the next while {input} carries the original request.



name: research-report

type: pipeline

agents:

  - name: researcher

    role: Find facts.

    task: "Research: {input}"

  - name: writer

    role: Write clearly.

    task: "Write a report from these notes:\n{previous}"



You run that file by name, passing the topic as the input, and you can equally launch it from the Workflows panel in the web interface. Every run is bounded by budgets - how many sub-agents it may spawn, how deep it may nest, how many total runs it may make - so a misbehaving workflow can't spiral out of control.



mercury workflow run research-report "The history of the transistor"



When a simple pipeline finishes too shallowly for a genuinely hard task, the planner-executor template digs deeper. A planner first breaks the goal into several concrete, ordered steps, an executor then carries out each step in turn while feeding earlier results forward, and a synthesizer writes the final combined answer. If a step fails the planner re-plans once and continues rather than giving up, and each step emits a progress event you can watch. You tune how hard it tries with a small options block.



name: deep-dive

type: planner-executor

options:

  minSteps: 3      # always run at least this many steps

  targetSteps: 5   # how many steps the planner aims for

  maxSteps: 12     # hard cap that is never exceeded

  replanOnFailure: true

agents:

  - name: planner      # breaks the goal into ordered steps

    role: Break the goal into clear, ordered steps.

  - name: executor     # runs each step in turn

    role: Carry out one step at a time.

  - name: synthesizer  # writes the final combined answer

    role: Combine the step results into a complete answer.



The maxSteps cap together with the standard run budgets is what prevents a planner-executor from looping forever, which matters because a planning agent that can re-plan is exactly the kind of thing that could otherwise run away.


8. Configuring speech-to-text and text-to-speech


Mercury can listen and speak. It transcribes voice input - microphone recordings from the web interface, voice memos from chat platforms - and it can read its replies aloud. The design goal here is that speech-to-text and text-to-speech are independently swappable between a commercial cloud API and an open-source self-hosted engine with a single configuration change and no code edits, so you're never locked into one vendor. The fastest way to switch is a named preset, where each preset already bundles the correct provider, base URL, command and model for a known engine. You list the presets, apply one for transcription and one for speech, and inspect the result.



mercury voice presets

mercury voice use stt whisper

mercury voice use tts kokoro

mercury voice show



Those three "use" lines illustrate the whole philosophy. The speech-to-text presets range from the commercial OpenAI cloud, through a self-hosted faster-whisper server called speaches, to a fully offline local Whisper command-line tool. The text-to-speech presets range from commercial OpenAI, through self-hosted open-source servers such as openedai and Kokoro-FastAPI, to the offline local Piper engine and the free Microsoft Edge voices. Applying a preset rewrites the entire voice.stt or voice.tts block in one go, which deliberately removes any stale keys left over from the engine you used before.


If you would rather set things by hand, every underlying key remains available, and two patterns cover most needs. To stay OpenAI-compatible but point at your own server, you change only the base URL, because a self-hosted faster-whisper or Kokoro server exposes the very same routes the OpenAI client already speaks.



mercury config set voice.stt.baseUrl http://localhost:8000/v1

mercury config set voice.tts.baseUrl http://localhost:8080/v1



To go fully offline through local command-line engines you switch the provider itself, at which point Mercury shells out to Whisper for transcription and to Piper for speech rather than making any network call.



mercury config set voice.stt.provider whisper

mercury config set voice.tts.provider piper



One caveat worth stating plainly: the voice subsystem is documented and covered by the offline tests, but it has not been exhaustively proven against every live engine, so when you wire in a particular server, verify a single round trip before relying on it in production.


9. Adding skills


A skill is a reusable procedure written in plain language that teaches Mercury how to approach a certain kind of task well. Mechanically a skill is a folder containing a file named SKILL.md in the agentskills.io format, which is a small block of YAML frontmatter carrying a name and a description followed by Markdown instructions. Mercury shows only the short descriptions of your skills to the model as part of its system prompt and loads the full instructions on demand, so having many skills costs little until one is actually needed. A minimal skill looks like this.



---

name: code-review

description: Review a code change for bugs and security issues. Use when the user asks for a review.

metadata: { version: 1, tags: [code, quality] }

---

# Code review

1. Read the files - do not guess.

2. Look for bugs, missing error handling and security issues.

3. Summarise findings with file and line references.



The description line is doing real work: it's the text the model reads when deciding whether this skill is relevant to the task in front of it, so write it as a clear trigger rather than a vague label. You manage skills from the command line, listing what you have, viewing one in full, and installing a skill from a local path or straight from a git URL, and you scaffold a new one with a single command.



mercury skills list

mercury new skill my-skill

mercury skills install https://github.com/someone/a-useful-skill



Bundled skills live under the repository's skills folder and your own live under ~/.mercury/skills. Beyond hand-written skills, Mercury can distil its own from runs that went well, generalising a proven sequence of tool calls into a reusable, parameterised skill. This is switched off by default because it changes the agent's behaviour over time, and when you enable it the distilled skills start life as proposals that must be approved before the agent may reuse them, with each approved skill tracked by its success rate so that a skill which stops working is retired automatically. You turn the feature on, and optionally let good skills auto-approve, through configuration.



skills:

  distill:

    enabled: true               # master switch for distil, match and record

    autoApprove: false          # keep a human in the loop before reuse

    minToolCalls: 2             # a run needs at least this many tool calls to distil

    retireBelowSuccessRate: 0.5 # auto-retire a skill that drops below this success rate



10. Adding tools


If skills are knowledge, tools are hands. Mercury ships with around seventy-five built-in tools organised into toolsets for files, shell, web, code, memory, skills, scheduling, media and messaging, and every tool carries a risk level of safe, moderate or dangerous. The risk level drives safety: a dangerous tool requires your approval before it runs unless your policy explicitly allows it, which is how Mercury can be both capable and cautious. You survey and curate the built-in tools from the command line or from the Tools and MCP panel in the web interface.



mercury tools list

mercury tools toolsets

mercury tools disable shell



Adding your own tool doesn't require touching Mercury's source, because any folder that contains a tool.json manifest in the repository's tools directory, in ~/.mercury/tools, or in a directory you list under tools.polyglotDirs automatically becomes a tool. These are called polyglot tools because they can be written in any language: Mercury writes the tool's JSON arguments to the process's standard input and reads its standard output back as the result, treating a non-zero exit code as an error. The manifest describes the tool to the model and tells Mercury how to run it.



{

  "name": "slugify",

  "description": "Turn a title into a URL-friendly slug.",

  "toolset": "polyglot",

  "risk": "safe",

  "parameters": {

    "type": "object",

    "properties": { "text": { "type": "string" } },

    "required": ["text"]

  },

  "command": ["node", "main.mjs"],

  "requires": ["node"]

}



Two fields in that manifest deserve attention. The risk field decides whether the tool runs freely or passes through approval gating, so set it honestly - a tool that deletes files isn't "safe". The requires field lists the binaries that must be present on the PATH for the tool to work, and Mercury simply hides the tool when they are missing rather than failing at call time. The program that backs the manifest is ordinary code; a tiny Node script that reads the arguments and prints a slug completes the example.



// main.mjs - reads {"text": "..."} from stdin, prints a slug to stdout.

let input = '';

for await (const chunk of process.stdin) {

  input += chunk;

}

const { text = '' } = JSON.parse(input || '{}');

const slug = text

  .toLowerCase()

  .trim()

  .replace(/[^a-z0-9]+/g, '-')   // non-alphanumerics become single hyphens

  .replace(/^-+|-+$/g, '');      // trim leading and trailing hyphens

process.stdout.write(slug);



Rather than create the folder by hand you can scaffold a correct starter in the language of your choice, which writes the manifest and a runnable stub for you.



mercury new tool slugify --lang js



11. Connecting Mercury to external MCP servers


The Model Context Protocol, usually shortened to MCP, is an open standard that lets one program offer tools to another in a uniform way, and Mercury is an MCP client, so it can borrow tools from any MCP server you point it at. You register a server under mcp.servers in the configuration, giving either a command to launch a local stdio server or an HTTP URL for a remote one, and the server's tools then appear inside Mercury with names of the form mcp_<server>_<tool> so you can always see where a tool came from.


So that you don't have to remember exact command lines, Mercury ships curated presets for several common servers - a filesystem server, a fetch server, a GitHub server, a git server and a SQLite server. You list the presets, enable one, and check that it actually connected.



mercury mcp presets

mercury mcp enable github --name gh

mercury mcp status



The presets never contain secrets. Instead they reference placeholders such as ${GITHUB\_TOKEN}, ${MCP\_FS\_ROOT}, ${MCP\_GIT\_REPO} and ${MCP\_SQLITE\_DB}, which Mercury resolves from the environment at the moment it connects, and if a required variable is unset the enable command tells you which one so you can export it first.



export GITHUB_TOKEN=ghp_your_token_here

mercury mcp enable github --name 


A safety detail matters here: every preset server is registered as untrusted, which means the output of its tools is treated as untrusted data and remains subject to the same policy and approval engine as everything else. That's the right default, because a tool whose behaviour is defined by someone else's server should not be allowed to bypass your safety rules.


12. Calling Mercury from an MCP client


Mercury isn't only a client but also an MCP server, which means other programs - a desktop AI application, a coding assistant, your own script - can borrow Mercury's seventy-five-plus tools through the same protocol. When you run the server, Mercury exposes its tools at the /mcp endpoint over streamable HTTP. Access is token-controlled, so you first mint a token that carries the mcp scope and then present it as a bearer token on each request.



mercury serve

mercury token create claude --scopes mcp



That command prints a token beginning with mrc\_, and an MCP client reaches Mercury by sending it in the standard Authorization header against the /mcp endpoint of your running server.



Authorization: Bearer mrc_xxxxxxxxxxxxxxxxxxxxxxxx



Some desktop clients prefer to launch a local process and talk to it over standard input and output rather than over HTTP. For them Mercury offers a stdio server mode that you start with a single command, which is the form you typically put into a desktop client's configuration so the client spawns Mercury itself.



mercury mcp serve



13. Extending Mercury as a developer


When configuration isn't enough and you want to add genuine new behaviour, Mercury gives you clean extension points, and the lightest of them is a plugin. A plugin is a small JavaScript module that Mercury loads from ~/.mercury/plugins, and in its setup function it receives an API object through which it registers new capabilities. The example below registers a brand-new tool and a hook that logs every tool call, and it illustrates the shape every plugin follows.



// ~/.mercury/plugins/hello.mjs

export default {

  name: 'hello',

  version: '1.0.0',

  setup(api) {

    // Register a new tool the agent can call by name.

    api.registerTool({

      name: 'hello',

      description: 'Say hello',

      toolset: 'custom',

      risk: 'safe',

      parameters: { type: 'object', properties: { who: { type: 'string' } } },

      async execute(args) {

        return `Hello, ${args.who ?? 'world'}!`;

      },

    });


    // Hooks receive a payload and may return a patch object, or nothing.

    api.registerHook('before_tool_call', (payload) => {

      api.logger.info('tool', { tool: payload.tool });

    });

  },

};



The API handed to setup is richer than those two calls suggest. Alongside registerTool and registerHook it offers registerMemoryProvider and registerContextEngine for changing how Mercury remembers, registerLLMProvider and registerDecisionProvider for teaching it to talk to new brains, and registerPattern, registerWorkflowTemplate and registerAdapter for new reasoning styles, new workflow shapes and new chat platforms respectively. The most reliable way to start a real plugin is to let Mercury scaffold an exact, up-to-date skeleton for you rather than copying an example that may drift.



mercury new plugin my-plugin



A gateway adapter is the extension point you reach for when you want Mercury on a chat platform it doesn't yet support. An adapter implements a small, explicit interface - or extends the provided BaseAdapter to inherit the boring parts - whose methods cover the whole life cycle of a connection: starting it and pushing inbound messages into a sink, stopping it cleanly, sending outbound messages, reporting status, and optionally handling a webhook mounted at /webhooks/<name>.



interface Adapter {

  readonly name: string;

  readonly type: string;

  readonly textOnly?: boolean;

  start(sink: InboundSink): Promise<void>;   // connect and push InboundMessage objects to the sink

  stop(): Promise<void>;                      // disconnect cleanly

  send(out: OutboundMessage): Promise<void>;  // deliver a reply to the platform

  status(): AdapterStatus;                     // report health for the Integrations panel

  handleWebhook?(req: WebhookRequest): Promise<WebhookResponse>;  // optional inbound HTTP

}



A design detail that makes adapters pleasant to test is that they perform HTTP through an injected transport rather than calling fetch directly, so a test can substitute a MockTransport and assert on what the adapter would have sent without touching the network. You register an adapter factory from a plugin and then declare it in the configuration just like a built-in one.



api.registerAdapter('myplatform', (config) => new MyAdapter(config));



Two further extension points round out the developer story. A polyglot tool, covered earlier, is the right choice when your logic is easier to write in Python, Go, C++ or Java than in TypeScript. And a custom LLM or decision provider lets you bolt on a backend Mercury has never heard of: an LLMProvider implements the chat and streaming calls for a provider/model id, while a DecisionProvider answers typed questions such as a choice, a boolean or a score together with a confidence. The built-in Jev provider in the source tree is a compact reference you can read while writing your own.


Implementing a client that works with local and remote LLMs


Because so much of Mercury's power comes from the simple idea of one transport feeding many backends, it's worth building that idea yourself in a small, dependency-free client. The program below talks to both a local model server such as Ollama and a remote cloud endpoint such as Abacus.AI ChatLLM or OpenRouter through the single OpenAI "chat completions" wire format, selecting a backend purely by its base URL and an optional key. It mirrors how Mercury itself is organised, and it deliberately has no mocks and no hidden fallbacks: if a backend is unreachable, the call fails loudly. It needs Node.js 22.5 or newer and runs with "node --experimental-strip-types llm-client.ts".


We start with a tiny, explicit vocabulary that every backend shares, so that the rest of the code never has to care which backend it's really talking to. A chat message is a role and some text, a backend is a name, a base URL, a model and an optional key, and a result is normalised down to the text plus a little token accounting.



/** One turn in a conversation, in provider-neutral form. */

export interface ChatMessage {

  role: 'system' | 'user' | 'assistant';

  content: string;

}


/** Everything needed to reach exactly one backend. */

export interface BackendConfig {

  readonly name: string;      // human-readable, e.g. "ollama" or "chatllm"

  readonly baseUrl: string;   // OpenAI-compatible, ends in "/v1", no trailing slash

  readonly model: string;     // model id that backend understands, e.g. "llama3.1"

  readonly apiKey?: string;   // bearer token for remote backends; omit for local servers

}


/** Normalised result returned to the caller regardless of backend. */

export interface ChatResult {

  readonly text: string;

  readonly model: string;

  readonly inputTokens: number;

  readonly outputTokens: number;

}



A robust client has to distinguish a problem worth retrying from one that's hopeless, so we give transport failures their own error type carrying a retryable flag. A momentary 503 from an overloaded server is retryable; a 401 from a wrong key isn't, and retrying it would only waste time and quota.



/** Raised for transport-level failures; `retryable` guides the retry policy. */

export class LlmError extends Error {

  constructor(

    message: string,

    readonly status: number | undefined,

    readonly retryable: boolean,

  ) {

    super(message);

    this.name = 'LlmError';

  }

}



The client itself is one class with two transports behind a shared request builder. The private helpers assemble the headers - adding the Authorization line only when a key exists, which is exactly what lets the same code serve a keyless local Ollama and a keyed cloud endpoint - and the request body, and then POST it with a timeout, translating every HTTP or network failure into the typed error above.



export class OpenAICompatibleClient {

  constructor(private readonly config: BackendConfig) {}


  /** Add the Authorization header only when a key is present. */

  private headers(): Record<string, string> {

    const headers: Record<string, string> = { 'content-type': 'application/json' };

    if (this.config.apiKey) {

      headers.authorization = `Bearer ${this.config.apiKey}`;

    }

    return headers;

  }


  /** Assemble the body shared by the buffered and streaming paths. */

  private body(messages: ChatMessage[], options: ChatOptions, stream: boolean): string {

    return JSON.stringify({

      model: this.config.model,

      messages,

      temperature: options.temperature ?? 0.7,

      max_tokens: options.maxTokens,

      stream,

      // Ask OpenAI-compatible servers to report token usage in the final chunk.

      ...(stream ? { stream_options: { include_usage: true } } : {}),

    });

  }


  /** POST with a timeout; turn HTTP/network failures into a typed LlmError. */

  private async post(messages: ChatMessage[], options: ChatOptions, stream: boolean): Promise<Response> {

    const url = `${this.config.baseUrl}/chat/completions`;

    let response: Response;

    try {

      response = await fetch(url, {

        method: 'POST',

        headers: this.headers(),

        body: this.body(messages, options, stream),

        signal: AbortSignal.timeout(120_000),

      });

    } catch (cause) {

      // DNS failure, connection refused (local server down), or timeout.

      throw new LlmError(`network error calling ${this.config.name}: ${String(cause)}`, undefined, true);

    }

    if (!response.ok) {

      const detail = (await response.text().catch(() => '')).slice(0, 300);

      const retryable = response.status === 429 || response.status >= 500;

      throw new LlmError(`${response.status} from ${this.config.name}: ${detail}`, response.status, retryable);

    }

    return response;

  }

}



The options type the methods above refer to is small, shaping a single request with a temperature, an optional token cap, and a callback that receives streamed fragments as they arrive.



/** Options that shape a single request. */

export interface ChatOptions {

  readonly temperature?: number;             // lower is more deterministic

  readonly maxTokens?: number;               // hard cap on generated tokens

  readonly onDelta?: (fragment: string) => void;  // called with each streamed fragment

}



With the plumbing in place, the first public method asks for a complete answer in one buffered response. It reads the JSON the server returns and copies out the text and the token counts, defaulting each field defensively so a slightly different server shape can't crash the caller. These two methods belong inside the class above.



  /** Request a complete answer in one buffered JSON response. */

  async complete(messages: ChatMessage[], options: ChatOptions = {}): Promise<ChatResult> {

    const response = await this.post(messages, options, false);

    const json = (await response.json()) as {

      model?: string;

      choices?: Array<{ message?: { content?: string | null } }>;

      usage?: { prompt_tokens?: number; completion_tokens?: number };

    };

    return {

      text: json.choices?.[0]?.message?.content ?? '',

      model: json.model ?? this.config.model,

      inputTokens: json.usage?.prompt_tokens ?? 0,

      outputTokens: json.usage?.completion_tokens ?? 0,

    };

  }


  /** Stream the answer token by token, forwarding each fragment to onDelta. */

  async stream(messages: ChatMessage[], options: ChatOptions = {}): Promise<ChatResult> {

    const response = await this.post(messages, options, true);

    if (!response.body) {

      throw new LlmError(`empty stream from ${this.config.name}`, undefined, false);

    }

    const decoder = new TextDecoder();

    let buffer = '';

    let text = '';

    let inputTokens = 0;

    let outputTokens = 0;


    for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {

      buffer += decoder.decode(chunk, { stream: true });

      // Server-Sent-Events are newline-delimited; process every complete line.

      let newline: number;

      while ((newline = buffer.indexOf('\n')) >= 0) {

        const line = buffer.slice(0, newline).replace(/\r$/, '');

        buffer = buffer.slice(newline + 1);

        if (!line.startsWith('data:')) {

          continue;

        }

        const payload = line.slice('data:'.length).trimStart();

        if (payload === '[DONE]') {

          break;

        }

        const event = safeParse(payload);

        if (!event) {

          continue;

        }

        const fragment = event.choices?.[0]?.delta?.content;

        if (fragment) {

          text += fragment;

          options.onDelta?.(fragment);

        }

        if (event.usage) {

          inputTokens = event.usage.prompt_tokens ?? inputTokens;

          outputTokens = event.usage.completion_tokens ?? outputTokens;

        }

      }

    }

    return { text, model: this.config.model, inputTokens, outputTokens };

  }



The streaming parser leans on one small helper and one small type. The helper parses a single Server-Sent-Events payload and returns undefined on malformed JSON rather than throwing, because a half-received chunk must not bring the whole stream down.



/** Shape of the streaming chunk fragments we actually read. */

interface StreamChunk {

  choices?: Array<{ delta?: { content?: string } }>;

  usage?: { prompt_tokens?: number; completion_tokens?: number };

}


/** Parse one SSE payload, returning undefined on malformed JSON. */

function safeParse(payload: string): StreamChunk | undefined {

  try {

    return JSON.parse(payload) as StreamChunk;

  } catch {

    return undefined;

  }

}



The final piece turns a list of backends into a resilient call. It tries the first backend, retries a retryable failure with exponential backoff and a little jitter so that many clients don't all retry in lockstep, and only then moves on to the next backend; a non-retryable error aborts that backend immediately. Listing a local backend first and a cloud backend second gives you a system that prefers to stay offline and private but reaches for the cloud when the local model is down.



/** Sleep helper used by the backoff loop. */

function delay(ms: number): Promise<void> {

  return new Promise((resolve) => setTimeout(resolve, ms));

}


/**

 * Try each backend in order. Retry a RETRYABLE failure with backoff and jitter,

 * then fall through to the next backend. A non-retryable error (e.g. a 401 on a

 * bad key) stops that backend at once, because retrying it would only waste quota.

 */

export async function completeWithFallback(

  backends: readonly BackendConfig[],

  messages: ChatMessage[],

  options: ChatOptions & { retries?: number; backoffMs?: number; jitter?: number } = {},

): Promise<ChatResult> {

  const retries = options.retries ?? 2;

  const backoffMs = options.backoffMs ?? 500;

  const jitter = options.jitter ?? 0.5;

  let lastError: unknown;


  for (const backend of backends) {

    const client = new OpenAICompatibleClient(backend);

    for (let attempt = 0; attempt <= retries; attempt++) {

      try {

        return await client.complete(messages, options);

      } catch (error) {

        lastError = error;

        const canRetry = error instanceof LlmError && error.retryable && attempt < retries;

        if (!canRetry) {

          break;   // non-retryable, or out of attempts: move to the next backend

        }

        const base = backoffMs * 2 ** attempt;

        const sleep = base + Math.random() * base * jitter;

        await delay(sleep);

      }

    }

  }

  throw new LlmError(`all backends failed; last error: ${String(lastError)}`, undefined, false);

}



To see the whole thing work you build the backend list from the environment, always including a local Ollama and adding a remote ChatLLM only when its key is present, so the example runs fully offline against Ollama alone yet uses the cloud automatically when you have a key. A short main function streams an answer from the first backend and then demonstrates the resilient fallback helper.



/** Build the backend list from the environment: Ollama always, ChatLLM if keyed. */

function backendsFromEnv(): BackendConfig[] {

  const backends: BackendConfig[] = [

    {

      name: 'ollama',

      baseUrl: process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434/v1',

      model: process.env.OLLAMA_MODEL ?? 'llama3.1',

    },

  ];

  const remoteKey = process.env.CHATLLM_API_KEY ?? process.env.ABACUS_API_KEY;

  if (remoteKey) {

    backends.push({

      name: 'chatllm',

      baseUrl: 'https://routellm.abacus.ai/v1',

      model: 'route-llm',

      apiKey: remoteKey,

    });

  }

  return backends;

}


/** Entry point: stream from the first backend, then show the fallback helper. */

async function main(): Promise<void> {

  const backends = backendsFromEnv();

  const messages: ChatMessage[] = [

    { role: 'system', content: 'You are a concise assistant.' },

    { role: 'user', content: 'In one sentence, what is an agentic AI platform?' },

  ];


  const primary = new OpenAICompatibleClient(backends[0]!);

  process.stdout.write(`[streaming from ${backends[0]!.name}]\n`);

  const streamed = await primary.stream(messages, {

    temperature: 0.2,

    onDelta: (fragment) => process.stdout.write(fragment),

  });

  process.stdout.write(`\n[tokens in=${streamed.inputTokens} out=${streamed.outputTokens}]\n`);


  const resilient = await completeWithFallback(backends, messages, { temperature: 0.2 });

  process.stdout.write(`[fallback answer] ${resilient.text}\n`);

}


// Run main() only when executed directly, not when imported as a module.

if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {

  main().catch((error) => {

    console.error(error instanceof Error ? error.message : error);

    process.exit(1);

  });

}



The lesson this program teaches is the same lesson that explains Mercury's whole provider design. Because local and remote model servers all speak the one OpenAI-compatible dialect, the only real difference between "private and offline" and "powerful and in the cloud" is a base URL and whether an Authorization header is attached, and once you accept that, switching or combining them becomes a configuration decision rather than a rewrite.


Ideas for exercises


The fastest way to make all of this stick is to use it on something small and real, so here are a handful of graded challenges. As a gentle start, install Mercury, connect Ollama with a small local model, and hold a short conversation entirely offline, noticing that no data leaves your machine. Next, add an OpenRouter key and leave llm.defaultModel on auto, then ask both a trivial question and a hard one and watch the router send them to different models. For a practical win, create a Telegram bot, pair it, and schedule a task that summarises something each morning and delivers the result to your Telegram chat. To feel the extension points, write a polyglot tool in the language you know best - a currency converter or a word counter is plenty - and watch Mercury offer it to the model. Then teach Mercury a repeatable habit by writing a SKILL.md for a task you do often, such as reviewing a pull request, and confirm the model reaches for it. For a taste of cooperation, write a two-agent pipeline workflow in which one agent researches and another writes, and compare its output to a single agent doing the same job. If you administer a shared instance, connect a read-only filesystem MCP server as a preset and verify that its tools arrive as untrusted and still pass through approval. Finally, for the ambitious, build the local-plus-remote client from the previous section and extend completeWithFallback to record which backend eventually answered, which is the first step towards your own routing policy.


Conclusions


Mercury Agent is best understood as a capable, cautious body waiting for a brain. It gives you a command line, a web interface and nineteen chat gateways through which to talk to it; a scheduler and a workflow engine through which to put it to work unattended and in teams; a voice subsystem, a skills library and a seventy-five-strong toolset through which it perceives and acts; and an MCP bridge through which it both borrows and lends abilities. The optional Jev decision engine sharpens its judgement without ever being mandatory, and the whole system is built so that the choice between local privacy and cloud power is a single base URL rather than a fork in your code. If you remember only two things, remember that Mercury needs a real LLM provider before it can answer, and that it's honest about what has and has not been proven - the core loop has run against real models, while some subsystems are so far verified mainly offline. Start small, connect one brain, hold one conversation, and build outward from there.


Addendum: contributing to Mercury through the GitHub repository


Mercury is an open project under the MIT license, and contributing follows an ordinary, friendly pull-request flow. You begin by forking the repository on GitHub and creating a topic branch from main, naming it after the change you intend to make.


git checkout -b feat/short-description



The guiding principle while you work is the smallest diff that does the job: make your change, match the surrounding code style, and resist the urge to reformat untouched code, because churn hides real changes and breeds regressions. Before you open a pull request you keep the build and the tests green and run the linter, since the project expects all three to pass.



npm run build

npm test

npx eslint .



Whenever you change behaviour you add or update tests for it; the suite runs offline against a deterministic mock provider that the test harness enables for you through MERCURY\_ENABLE\_MOCK, and production code must never enable that mock outside tests. You also update the documentation when user-facing behaviour changes, touching the README, the relevant file under docs, and STATUS.md if a subsystem's tested status moves. Commit messages are short, imperative and type-prefixed, so a new feature reads as "feat: add X", a fix as "fix: handle Y", and documentation as "docs: ...". When you open the pull request you describe what changed and why, link any related issue, keep it focused on one logical change, and - in keeping with the project's culture of honesty - you note explicitly if anything was not tested against real external services such as LLM APIs, chat platforms or the speech engines. That last habit is the heart of the project: Mercury's documentation is deliberately candid about what is proven and what isn't, and your contribution is most valuable when it's candid too.


BUILDING AN INTELLIGENT MCP HUB EXPLORER: DISCOVERING AND TESTING MCP SERVERS

 


INTRODUCTION TO THE MODEL CONTEXT PROTOCOL ECOSYSTEM

The Model Context Protocol, developed by Anthropic, represents a significant advancement in how large language models interact with external tools and data sources. At its core, MCP establishes a standardized communication framework that allows AI assistants to seamlessly connect with various services, databases, and applications. This protocol has given rise to an ecosystem of MCP servers, each offering specialized capabilities ranging from file system access to API integrations with popular services.

As the MCP ecosystem grows, developers and AI enthusiasts face a new challenge: discovering, evaluating, and testing the multitude of available MCP servers. Multiple organizations, including Anthropic and GitHub, have established MCP hubs that catalog these servers, but navigating through these repositories can be cumbersome without proper tooling. This article presents a comprehensive approach to building a sophisticated web-based application that addresses this need by providing an intuitive interface for exploring MCP hubs, discovering servers, and testing their capabilities in real-time.

The application we will design combines several key functionalities. It maintains connections to multiple MCP hubs through a configuration-driven architecture, presents servers in a familiar file-explorer interface, allows users to test tools provided by each server, and maintains a personalized list of favorite servers. Throughout this journey, we will examine the technical architecture, implementation details, and best practices for creating such a system.

UNDERSTANDING THE ARCHITECTURAL FOUNDATION

Before diving into implementation details, we must establish a clear understanding of the system architecture. Our web-based MCP Hub Explorer consists of several interconnected layers, each serving a distinct purpose while maintaining loose coupling for flexibility and maintainability.

The presentation layer forms the user-facing component, implemented as a modern single-page application running entirely in the browser. This layer handles all user interactions, from browsing hub directories to invoking MCP server tools. It communicates with the application backend through a well-defined API, ensuring separation of concerns and enabling potential future expansion to mobile or desktop clients.

The application backend serves as the orchestration layer, managing connections to multiple MCP hubs, maintaining the configuration state, and coordinating tool invocations. This layer implements the MCP client protocol, establishing and maintaining connections to various MCP servers as users explore and test them. It also handles credential management, ensuring secure storage and transmission of authentication information when required by specific servers.

The persistence layer manages the configuration file and user preferences. Our implementation uses browser localStorage for configuration storage, making it accessible to the client-side code while maintaining persistence across sessions. This layer abstracts storage operations, providing a clean interface for reading and updating hub configurations, server favorites, and cached metadata.

Let us examine the configuration structure that drives the entire system:

const defaultConfiguration = {
  version: "1.0",
  hubs: [
    {
      id: "anthropic-official",
      name: "Anthropic MCP Hub",
      url: "https://mcp.anthropic.com/hub",
      description: "Official Anthropic Model Context Protocol server registry",
      authentication: {
        type: "none"
      },
      enabled: true,
      lastSync: null
    },
    {
      id: "github-mcp",
      name: "GitHub MCP Servers",
      url: "https://api.github.com/mcp-servers",
      description: "Community-contributed MCP servers from GitHub",
      authentication: {
        type: "bearer",
        tokenKey: "GITHUB_TOKEN"
      },
      enabled: true,
      lastSync: null
    }
  ],
  favorites: [],
  settings: {
    autoSync: true,
    syncInterval: 3600000,
    defaultTimeout: 30000,
    maxConcurrentConnections: 5,
    apiTokens: {}
  }
};

This configuration structure provides the foundation for our application. Each hub entry contains essential connection information including the endpoint URL, authentication requirements, and hub-specific metadata. The favorites array maintains a lightweight reference to user-selected servers, storing only the identifiers needed to retrieve full server information on demand. User interface preferences allow customization of the browsing experience while maintaining these settings across sessions.

IMPLEMENTING THE STORAGE LAYER

Since we are building a web-based application that runs in the browser, we need a storage solution that works in that environment. We will use localStorage for persistence, with a clean abstraction layer that could be swapped for IndexedDB or a backend API in the future.

class StorageService {
  constructor(storageKey = 'mcp_hub_explorer_config') {
    this.storageKey = storageKey;
    this.cache = null;
  }

  /**
   * Reads data from localStorage and parses it.
   * Returns null if no data exists or if parsing fails.
   */
  read() {
    try {
      const data = localStorage.getItem(this.storageKey);
      if (!data) {
        return null;
      }
      this.cache = JSON.parse(data);
      return this.cache;
    } catch (error) {
      console.error('Failed to read from storage:', error);
      return null;
    }
  }

  /**
   * Writes data to localStorage after stringifying it.
   * Handles quota exceeded errors gracefully.
   */
  write(data) {
    try {
      const jsonString = JSON.stringify(data, null, 2);
      localStorage.setItem(this.storageKey, jsonString);
      this.cache = data;
      return true;
    } catch (error) {
      if (error.name === 'QuotaExceededError') {
        console.error('Storage quota exceeded');
        alert('Storage quota exceeded. Please clear some data.');
      } else {
        console.error('Failed to write to storage:', error);
      }
      return false;
    }
  }

  /**
   * Clears all stored data.
   */
  clear() {
    try {
      localStorage.removeItem(this.storageKey);
      this.cache = null;
      return true;
    } catch (error) {
      console.error('Failed to clear storage:', error);
      return false;
    }
  }

  /**
   * Checks if storage is available in the browser.
   */
  static isAvailable() {
    try {
      const test = '__storage_test__';
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch (error) {
      return false;
    }
  }
}

The StorageService class provides a clean abstraction over localStorage. It handles JSON serialization and deserialization, manages errors gracefully, and provides a simple interface for the rest of the application. The isAvailable static method allows us to detect whether localStorage is supported in the current browser environment.

IMPLEMENTING THE CONFIGURATION MANAGER

With our storage layer in place, we can now build the configuration manager that handles loading, saving, and updating the configuration. This manager will use the StorageService and provide a higher-level interface for configuration operations.

class ConfigurationManager {
  constructor() {
    this.storage = new StorageService('mcp_hub_explorer_config');
    this.config = null;
    this.watchers = [];
    this.saveDebounceTimer = null;
    this.saveDebounceDelay = 500;
  }

  /**
   * Initializes the configuration manager by loading existing config
   * or creating a default one if none exists.
   */
  async initialize() {
    if (!StorageService.isAvailable()) {
      throw new Error('localStorage is not available in this browser');
    }

    const storedConfig = this.storage.read();
    
    if (storedConfig) {
      this.config = this.validateAndMerge(storedConfig);
    } else {
      console.log('No existing configuration found, creating default');
      this.config = JSON.parse(JSON.stringify(defaultConfiguration));
      this.storage.write(this.config);
    }

    return this.config;
  }

  /**
   * Validates loaded configuration and merges with defaults
   * to ensure all required fields exist.
   */
  validateAndMerge(loadedConfig) {
    const merged = {
      version: loadedConfig.version || defaultConfiguration.version,
      hubs: Array.isArray(loadedConfig.hubs) ? loadedConfig.hubs : [],
      favorites: Array.isArray(loadedConfig.favorites) ? loadedConfig.favorites : [],
      settings: {
        ...defaultConfiguration.settings,
        ...(loadedConfig.settings || {})
      }
    };

    merged.hubs = merged.hubs.filter(hub => {
      if (!hub.id || !hub.url) {
        console.warn('Invalid hub entry found, skipping:', hub);
        return false;
      }
      
      if (!hub.authentication) {
        hub.authentication = { type: 'none' };
      }
      
      return true;
    });

    return merged;
  }

  /**
   * Saves the current configuration to storage.
   * Debounced to prevent excessive writes.
   */
  save() {
    return new Promise((resolve, reject) => {
      if (this.saveDebounceTimer) {
        clearTimeout(this.saveDebounceTimer);
      }

      this.saveDebounceTimer = setTimeout(() => {
        try {
          const success = this.storage.write(this.config);
          if (success) {
            this.notifyWatchers('configSaved', this.config);
            resolve();
          } else {
            reject(new Error('Failed to save configuration'));
          }
        } catch (error) {
          reject(error);
        }
      }, this.saveDebounceDelay);
    });
  }

  /**
   * Adds a new hub to the configuration.
   * Validates the hub data before adding.
   */
  async addHub(hubConfig) {
    if (!hubConfig.id || !hubConfig.url) {
      throw new Error('Hub configuration must include id and url');
    }

    if (!this.isValidUrl(hubConfig.url)) {
      throw new Error('Invalid URL format');
    }

    const existingIndex = this.config.hubs.findIndex(h => h.id === hubConfig.id);
    if (existingIndex !== -1) {
      throw new Error(`Hub with id ${hubConfig.id} already exists`);
    }

    const hub = {
      id: hubConfig.id,
      name: hubConfig.name || hubConfig.id,
      url: hubConfig.url,
      description: hubConfig.description || '',
      authentication: hubConfig.authentication || { type: 'none' },
      enabled: hubConfig.enabled !== false,
      lastSync: null
    };

    this.config.hubs.push(hub);
    await this.save();
    this.notifyWatchers('hubAdded', hub);

    return hub;
  }

  /**
   * Validates URL format.
   */
  isValidUrl(urlString) {
    try {
      const url = new URL(urlString);
      return url.protocol === 'http:' || url.protocol === 'https:';
    } catch (error) {
      return false;
    }
  }

  /**
   * Removes a hub from the configuration.
   */
  async removeHub(hubId) {
    const initialLength = this.config.hubs.length;
    this.config.hubs = this.config.hubs.filter(h => h.id !== hubId);

    if (this.config.hubs.length === initialLength) {
      throw new Error(`Hub with id ${hubId} not found`);
    }

    this.config.favorites = this.config.favorites.filter(
      fav => fav.hubId !== hubId
    );

    await this.save();
    this.notifyWatchers('hubRemoved', { hubId });
  }

  /**
   * Updates an existing hub configuration.
   */
  async updateHub(hubId, updates) {
    const hubIndex = this.config.hubs.findIndex(h => h.id === hubId);
    if (hubIndex === -1) {
      throw new Error(`Hub with id ${hubId} not found`);
    }

    if (updates.url && !this.isValidUrl(updates.url)) {
      throw new Error('Invalid URL format');
    }

    this.config.hubs[hubIndex] = {
      ...this.config.hubs[hubIndex],
      ...updates,
      id: hubId
    };

    await this.save();
    this.notifyWatchers('hubUpdated', this.config.hubs[hubIndex]);
  }

  /**
   * Adds a server to favorites.
   */
  async addToFavorites(hubId, serverId, serverName) {
    const exists = this.config.favorites.some(
      fav => fav.hubId === hubId && fav.serverId === serverId
    );

    if (exists) {
      return;
    }

    const favorite = {
      hubId,
      serverId,
      serverName: serverName || serverId,
      addedAt: new Date().toISOString()
    };

    this.config.favorites.push(favorite);
    await this.save();
    this.notifyWatchers('favoriteAdded', favorite);
  }

  /**
   * Removes a server from favorites.
   */
  async removeFromFavorites(hubId, serverId) {
    const initialLength = this.config.favorites.length;
    this.config.favorites = this.config.favorites.filter(
      fav => !(fav.hubId === hubId && fav.serverId === serverId)
    );

    if (this.config.favorites.length < initialLength) {
      await this.save();
      this.notifyWatchers('favoriteRemoved', { hubId, serverId });
      return true;
    }

    return false;
  }

  /**
   * Checks if a server is in favorites.
   */
  isFavorite(hubId, serverId) {
    return this.config.favorites.some(
      fav => fav.hubId === hubId && fav.serverId === serverId
    );
  }

  /**
   * Gets all favorites.
   */
  getFavorites() {
    return [...this.config.favorites];
  }

  /**
   * Updates UI settings.
   */
  async updateSettings(settings) {
    this.config.settings = {
      ...this.config.settings,
      ...settings
    };

    await this.save();
    this.notifyWatchers('settingsUpdated', this.config.settings);
  }

  /**
   * Sets an API token for a specific service.
   */
  async setApiToken(key, value) {
    if (!this.config.settings.apiTokens) {
      this.config.settings.apiTokens = {};
    }

    this.config.settings.apiTokens[key] = value;
    await this.save();
  }

  /**
   * Gets an API token for a specific service.
   */
  getApiToken(key) {
    if (!this.config.settings.apiTokens) {
      return null;
    }
    return this.config.settings.apiTokens[key] || null;
  }

  /**
   * Gets all hubs.
   */
  getHubs(enabledOnly = false) {
    if (enabledOnly) {
      return this.config.hubs.filter(hub => hub.enabled);
    }
    return [...this.config.hubs];
  }

  /**
   * Gets a specific hub by ID.
   */
  getHub(hubId) {
    return this.config.hubs.find(hub => hub.id === hubId) || null;
  }

  /**
   * Registers a watcher callback.
   */
  watch(callback) {
    this.watchers.push(callback);
    return () => {
      this.watchers = this.watchers.filter(w => w !== callback);
    };
  }

  /**
   * Notifies all watchers of a configuration change.
   */
  notifyWatchers(eventType, data) {
    this.watchers.forEach(watcher => {
      try {
        watcher(eventType, data);
      } catch (error) {
        console.error('Error in configuration watcher:', error);
      }
    });
  }
}

The ConfigurationManager provides a comprehensive interface for managing application configuration. It handles validation of hub entries, ensures URL formats are correct, and manages the favorites list. The debounced save mechanism prevents excessive localStorage writes when multiple changes occur in quick succession.

IMPLEMENTING THE MCP CLIENT PROTOCOL

The heart of our application lies in its implementation of the Model Context Protocol client. This component must correctly implement the MCP specification to establish connections, discover available tools, and invoke them with proper parameter handling.

class MCPMessage {
  constructor(method, params = {}, id = null) {
    this.jsonrpc = "2.0";
    this.method = method;
    this.params = params;
    
    if (id !== null) {
      this.id = id;
    }
  }

  toJSON() {
    const obj = {
      jsonrpc: this.jsonrpc,
      method: this.method,
      params: this.params
    };
    
    if (this.id !== null) {
      obj.id = this.id;
    }
    
    return obj;
  }
}

class MCPClient {
  constructor(serverUrl, authConfig = null) {
    this.serverUrl = serverUrl;
    this.authConfig = authConfig;
    this.messageId = 0;
    this.capabilities = null;
    this.tools = null;
    this.connectionState = 'disconnected';
    this.eventHandlers = new Map();
    this.requestTimeout = 30000;
    this.abortController = null;
  }

  generateMessageId() {
    return ++this.messageId;
  }

  /**
   * Sends a request to the MCP server with timeout and error handling.
   */
  async sendRequest(method, params = {}) {
    const message = new MCPMessage(method, params, this.generateMessageId());
    
    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };

    if (this.authConfig && this.authConfig.type !== 'none') {
      if (this.authConfig.type === 'bearer' && this.authConfig.token) {
        headers['Authorization'] = `Bearer ${this.authConfig.token}`;
      } else if (this.authConfig.type === 'apikey' && this.authConfig.apiKey) {
        headers[this.authConfig.headerName || 'X-API-Key'] = this.authConfig.apiKey;
      }
    }

    this.abortController = new AbortController();
    const timeoutId = setTimeout(() => {
      this.abortController.abort();
    }, this.requestTimeout);

    try {
      const response = await fetch(this.serverUrl, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(message.toJSON()),
        signal: this.abortController.signal,
        mode: 'cors'
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        const errorText = await response.text().catch(() => response.statusText);
        throw new Error(`HTTP ${response.status}: ${errorText}`);
      }

      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        throw new Error('Server did not return JSON response');
      }

      const result = await response.json();

      if (result.error) {
        throw new Error(`MCP Error ${result.error.code}: ${result.error.message}`);
      }

      return result.result;

    } catch (error) {
      clearTimeout(timeoutId);
      
      if (error.name === 'AbortError') {
        const timeoutError = new Error(`Request timeout after ${this.requestTimeout}ms`);
        this.emitEvent('error', { method, error: timeoutError.message });
        throw timeoutError;
      }

      this.emitEvent('error', { method, error: error.message });
      throw error;
    }
  }

  /**
   * Initializes the MCP connection with proper handshake.
   */
  async initialize() {
    if (this.connectionState === 'connected') {
      return this.capabilities;
    }

    this.connectionState = 'connecting';
    this.emitEvent('stateChange', { state: 'connecting' });

    try {
      const result = await this.sendRequest('initialize', {
        protocolVersion: '2024-11-05',
        capabilities: {
          roots: { listChanged: true },
          sampling: {}
        },
        clientInfo: {
          name: 'MCP Hub Explorer',
          version: '1.0.0'
        }
      });

      this.capabilities = result.capabilities || {};
      this.connectionState = 'connected';
      this.emitEvent('stateChange', { state: 'connected', capabilities: this.capabilities });

      await this.sendNotification('notifications/initialized');

      return this.capabilities;

    } catch (error) {
      this.connectionState = 'error';
      this.emitEvent('stateChange', { state: 'error', error: error.message });
      throw error;
    }
  }

  /**
   * Sends a notification (no response expected).
   */
  async sendNotification(method, params = {}) {
    const message = new MCPMessage(method, params, null);
    
    const headers = {
      'Content-Type': 'application/json'
    };

    if (this.authConfig && this.authConfig.type !== 'none') {
      if (this.authConfig.type === 'bearer' && this.authConfig.token) {
        headers['Authorization'] = `Bearer ${this.authConfig.token}`;
      }
    }

    try {
      await fetch(this.serverUrl, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(message.toJSON()),
        mode: 'cors'
      });
    } catch (error) {
      console.warn('Notification send failed:', error);
    }
  }

  /**
   * Lists all tools available from the server.
   */
  async listTools() {
    if (this.connectionState !== 'connected') {
      await this.initialize();
    }

    try {
      const result = await this.sendRequest('tools/list', {});
      this.tools = result.tools || [];
      return this.tools;
    } catch (error) {
      console.error('Failed to list tools:', error);
      throw error;
    }
  }

  /**
   * Calls a specific tool with given arguments.
   */
  async callTool(toolName, toolArguments = {}) {
    if (this.connectionState !== 'connected') {
      await this.initialize();
    }

    try {
      const result = await this.sendRequest('tools/call', {
        name: toolName,
        arguments: toolArguments
      });

      return result;

    } catch (error) {
      console.error(`Failed to call tool ${toolName}:`, error);
      throw error;
    }
  }

  /**
   * Registers an event handler.
   */
  on(eventName, handler) {
    if (!this.eventHandlers.has(eventName)) {
      this.eventHandlers.set(eventName, []);
    }
    this.eventHandlers.get(eventName).push(handler);
  }

  /**
   * Removes an event handler.
   */
  off(eventName, handler) {
    const handlers = this.eventHandlers.get(eventName);
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index !== -1) {
        handlers.splice(index, 1);
      }
    }
  }

  /**
   * Emits an event to all registered handlers.
   */
  emitEvent(eventName, data) {
    const handlers = this.eventHandlers.get(eventName);
    if (handlers) {
      handlers.forEach(handler => {
        try {
          handler(data);
        } catch (error) {
          console.error(`Error in event handler for ${eventName}:`, error);
        }
      });
    }
  }

  /**
   * Disconnects from the server and cleans up resources.
   */
  disconnect() {
    if (this.abortController) {
      this.abortController.abort();
      this.abortController = null;
    }

    this.connectionState = 'disconnected';
    this.capabilities = null;
    this.tools = null;
    this.emitEvent('stateChange', { state: 'disconnected' });
  }

  /**
   * Sets the request timeout in milliseconds.
   */
  setTimeout(timeoutMs) {
    this.requestTimeout = timeoutMs;
  }
}

The MCPClient class now includes comprehensive error handling, request timeouts using AbortController, and proper CORS support. The timeout mechanism ensures that requests do not hang indefinitely, and the abort controller allows for clean cancellation of in-flight requests.

BUILDING THE HUB DISCOVERY SERVICE

The hub discovery service manages the process of fetching server listings from various hubs, normalizing the data into a common format, and caching the results for performance.

class HubDiscoveryService {
  constructor(configManager) {
    this.configManager = configManager;
    this.serverCache = new Map();
    this.syncInProgress = new Set();
    this.cacheTimeout = 300000;
  }

  /**
   * Syncs a specific hub to fetch latest server listings.
   */
  async syncHub(hubId) {
    if (this.syncInProgress.has(hubId)) {
      console.log(`Sync already in progress for hub ${hubId}`);
      return;
    }

    const hub = this.configManager.getHub(hubId);
    if (!hub) {
      throw new Error(`Hub ${hubId} not found in configuration`);
    }

    if (!hub.enabled) {
      console.log(`Hub ${hubId} is disabled, skipping sync`);
      return;
    }

    this.syncInProgress.add(hubId);

    try {
      const servers = await this.fetchServersFromHub(hub);
      
      this.serverCache.set(hubId, {
        servers: servers,
        syncedAt: Date.now(),
        hubInfo: {
          id: hub.id,
          name: hub.name,
          description: hub.description
        }
      });

      hub.lastSync = new Date().toISOString();
      await this.configManager.save();

      console.log(`Successfully synced ${servers.length} servers from hub ${hubId}`);
      return servers;

    } catch (error) {
      console.error(`Failed to sync hub ${hubId}:`, error);
      throw error;
    } finally {
      this.syncInProgress.delete(hubId);
    }
  }

  /**
   * Fetches servers from a hub with proper authentication.
   */
  async fetchServersFromHub(hub) {
    const headers = {
      'Accept': 'application/json'
    };

    if (hub.authentication && hub.authentication.type !== 'none') {
      if (hub.authentication.type === 'bearer') {
        const token = this.configManager.getApiToken(hub.authentication.tokenKey);
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        } else {
          console.warn(`No token found for ${hub.authentication.tokenKey}`);
        }
      }
    }

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 30000);

    try {
      const response = await fetch(hub.url, {
        method: 'GET',
        headers: headers,
        signal: controller.signal,
        mode: 'cors'
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`Hub API returned ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return this.normalizeHubResponse(hub.id, data);

    } catch (error) {
      clearTimeout(timeoutId);
      if (error.name === 'AbortError') {
        throw new Error('Hub request timeout');
      }
      throw error;
    }
  }

  /**
   * Normalizes hub response to common format.
   */
  normalizeHubResponse(hubId, rawData) {
    if (hubId === 'anthropic-official') {
      return this.normalizeAnthropicHub(rawData);
    } else if (hubId === 'github-mcp') {
      return this.normalizeGitHubHub(rawData);
    } else {
      return this.normalizeGenericHub(rawData);
    }
  }

  /**
   * Normalizes Anthropic hub format.
   */
  normalizeAnthropicHub(data) {
    if (!data || !data.servers || !Array.isArray(data.servers)) {
      return [];
    }

    return data.servers.map(server => ({
      id: server.id || this.generateServerId(),
      name: server.name || 'Unnamed Server',
      description: server.description || '',
      version: server.version || '1.0.0',
      author: server.author || 'Unknown',
      category: server.category || 'Uncategorized',
      tags: Array.isArray(server.tags) ? server.tags : [],
      endpoint: server.endpoint || '',
      authRequired: Boolean(server.authRequired),
      documentation: server.documentation || null,
      tools: Array.isArray(server.tools) ? server.tools : [],
      metadata: {
        stars: server.stars || 0,
        downloads: server.downloads || 0,
        lastUpdated: server.lastUpdated || null
      }
    }));
  }

  /**
   * Normalizes GitHub hub format.
   */
  normalizeGitHubHub(data) {
    if (!Array.isArray(data)) {
      return [];
    }

    return data.map(repo => ({
      id: (repo.full_name || '').replace('/', '-') || this.generateServerId(),
      name: repo.name || 'Unnamed Repository',
      description: repo.description || '',
      version: repo.default_branch || 'main',
      author: (repo.owner && repo.owner.login) || 'Unknown',
      category: this.inferCategoryFromTopics(repo.topics),
      tags: Array.isArray(repo.topics) ? repo.topics : [],
      endpoint: this.constructEndpointFromRepo(repo),
      authRequired: false,
      documentation: repo.html_url || null,
      tools: [],
      metadata: {
        stars: repo.stargazers_count || 0,
        downloads: 0,
        lastUpdated: repo.updated_at || null
      }
    }));
  }

  /**
   * Normalizes generic hub format.
   */
  normalizeGenericHub(data) {
    const servers = Array.isArray(data) ? data : (data.servers || []);

    return servers.map(server => ({
      id: server.id || server.name || this.generateServerId(),
      name: server.name || 'Unnamed Server',
      description: server.description || '',
      version: server.version || '1.0.0',
      author: server.author || 'Unknown',
      category: server.category || 'Uncategorized',
      tags: Array.isArray(server.tags) ? server.tags : [],
      endpoint: server.endpoint || server.url || '',
      authRequired: Boolean(server.authRequired),
      documentation: server.documentation || null,
      tools: Array.isArray(server.tools) ? server.tools : [],
      metadata: server.metadata || {}
    }));
  }

  /**
   * Generates a unique server ID.
   */
  generateServerId() {
    return `server-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * Infers category from topic tags.
   */
  inferCategoryFromTopics(topics) {
    if (!Array.isArray(topics) || topics.length === 0) {
      return 'Uncategorized';
    }

    const categoryMap = {
      'database': 'Database',
      'filesystem': 'File System',
      'api': 'API Integration',
      'web': 'Web Services',
      'ai': 'AI & ML',
      'data': 'Data Processing',
      'security': 'Security',
      'monitoring': 'Monitoring'
    };

    for (const topic of topics) {
      const normalized = topic.toLowerCase();
      if (categoryMap[normalized]) {
        return categoryMap[normalized];
      }
    }

    return 'Uncategorized';
  }

  /**
   * Constructs endpoint URL from repository information.
   */
  constructEndpointFromRepo(repo) {
    if (!repo || !repo.full_name || !repo.default_branch) {
      return '';
    }
    return `https://raw.githubusercontent.com/${repo.full_name}/${repo.default_branch}/mcp-server.json`;
  }

  /**
   * Syncs all enabled hubs.
   */
  async syncAllHubs() {
    const hubs = this.configManager.getHubs(true);
    const results = await Promise.allSettled(
      hubs.map(hub => this.syncHub(hub.id))
    );

    const failures = results.filter(r => r.status === 'rejected');
    if (failures.length > 0) {
      console.warn(`${failures.length} hub(s) failed to sync`);
    }

    return results;
  }

  /**
   * Gets servers from a specific hub.
   */
  getServersFromHub(hubId) {
    const cached = this.serverCache.get(hubId);
    if (!cached) {
      return [];
    }

    const age = Date.now() - cached.syncedAt;
    if (age > this.cacheTimeout) {
      console.log(`Cache for hub ${hubId} is stale`);
    }

    return [...cached.servers];
  }

  /**
   * Gets all servers from all hubs.
   */
  getAllServers() {
    const allServers = [];

    for (const [hubId, cache] of this.serverCache.entries()) {
      cache.servers.forEach(server => {
        allServers.push({
          ...server,
          hubId: hubId,
          hubName: cache.hubInfo.name
        });
      });
    }

    return allServers;
  }

  /**
   * Gets servers organized by category.
   */
  getServersByCategory() {
    const categorized = new Map();
    const allServers = this.getAllServers();

    allServers.forEach(server => {
      const category = server.category || 'Uncategorized';
      if (!categorized.has(category)) {
        categorized.set(category, []);
      }
      categorized.get(category).push(server);
    });

    return categorized;
  }

  /**
   * Searches servers by query string.
   */
  searchServers(query) {
    if (!query || typeof query !== 'string') {
      return [];
    }

    const normalizedQuery = query.toLowerCase().trim();
    if (!normalizedQuery) {
      return [];
    }

    const allServers = this.getAllServers();

    return allServers.filter(server => {
      return (
        (server.name && server.name.toLowerCase().includes(normalizedQuery)) ||
        (server.description && server.description.toLowerCase().includes(normalizedQuery)) ||
        (Array.isArray(server.tags) && server.tags.some(tag => 
          tag.toLowerCase().includes(normalizedQuery)
        )) ||
        (server.author && server.author.toLowerCase().includes(normalizedQuery))
      );
    });
  }

  /**
   * Gets favorite servers with full details.
   */
  getFavoriteServers() {
    const favorites = this.configManager.getFavorites();
    const favoriteServers = [];

    favorites.forEach(fav => {
      const servers = this.getServersFromHub(fav.hubId);
      const server = servers.find(s => s.id === fav.serverId);
      if (server) {
        favoriteServers.push({
          ...server,
          hubId: fav.hubId,
          addedToFavoritesAt: fav.addedAt
        });
      }
    });

    return favoriteServers;
  }

  /**
   * Clears the cache for a specific hub.
   */
  clearHubCache(hubId) {
    this.serverCache.delete(hubId);
  }

  /**
   * Clears all cached data.
   */
  clearAllCache() {
    this.serverCache.clear();
  }
}

The HubDiscoveryService now includes proper timeout handling, better error management, and cache invalidation logic. The normalization methods handle missing or malformed data gracefully by providing sensible defaults.

CREATING THE FILE EXPLORER UI

The user interface brings our application to life with an intuitive file explorer metaphor. We will build a comprehensive UI that handles all user interactions while maintaining clean separation from business logic.

class FileExplorerUI {
  constructor(configManager, discoveryService) {
    this.configManager = configManager;
    this.discoveryService = discoveryService;
    this.selectedNode = null;
    this.expandedNodes = new Set();
    this.treeContainer = null;
    this.detailsPanel = null;
    this.activeConnections = new Map();
    this.eventListeners = new Map();
  }

  /**
   * Initializes the UI and renders the initial state.
   */
  initialize() {
    this.createLayout();
    this.renderTree();
    this.setupEventListeners();
  }

  /**
   * Creates the main layout structure.
   */
  createLayout() {
    const appContainer = document.getElementById('app');
    if (!appContainer) {
      throw new Error('App container element not found');
    }

    appContainer.innerHTML = `
      <div class="explorer-container">
        <div class="toolbar">
          <button id="sync-all-btn" class="toolbar-btn">Sync All Hubs</button>
          <button id="add-hub-btn" class="toolbar-btn">Add Hub</button>
          <input type="text" id="search-input" class="search-box" placeholder="Search servers...">
          <button id="favorites-btn" class="toolbar-btn">Show Favorites</button>
        </div>
        <div class="content-area">
          <div class="tree-panel">
            <div id="tree-container" class="tree-container"></div>
          </div>
          <div class="details-panel">
            <div id="details-container" class="details-container">
              <div class="empty-state">Select a server to view details</div>
            </div>
          </div>
        </div>
      </div>
    `;

    this.treeContainer = document.getElementById('tree-container');
    this.detailsPanel = document.getElementById('details-container');
  }

  /**
   * Renders the tree structure.
   */
  renderTree() {
    const treeData = this.buildTreeData();
    this.cleanupTreeEventListeners();
    this.treeContainer.innerHTML = '';

    const rootNode = this.createTreeNode({
      type: 'root',
      label: 'MCP Hubs',
      children: treeData,
      expanded: true
    }, 0);

    this.treeContainer.appendChild(rootNode);
  }

  /**
   * Builds the tree data structure from hubs and servers.
   */
  buildTreeData() {
    const hubs = this.configManager.getHubs();
    const treeData = [];

    const favoriteServers = this.discoveryService.getFavoriteServers();
    if (favoriteServers.length > 0) {
      treeData.push({
        type: 'favorites',
        label: `Favorites (${favoriteServers.length})`,
        icon: 'star',
        children: favoriteServers.map(server => ({
          type: 'server',
          data: server,
          label: server.name,
          icon: 'file',
          hubId: server.hubId
        }))
      });
    }

    hubs.forEach(hub => {
      const servers = this.discoveryService.getServersFromHub(hub.id);
      const categorized = this.categorizeServers(servers);

      const hubNode = {
        type: 'hub',
        data: hub,
        label: `${hub.name} (${servers.length})`,
        icon: 'folder',
        children: []
      };

      for (const [category, categoryServers] of categorized.entries()) {
        const categoryNode = {
          type: 'category',
          label: `${category} (${categoryServers.length})`,
          icon: 'folder',
          hubId: hub.id,
          categoryName: category,
          children: categoryServers.map(server => ({
            type: 'server',
            data: server,
            label: server.name,
            icon: 'file',
            hubId: hub.id
          }))
        };

        hubNode.children.push(categoryNode);
      }

      treeData.push(hubNode);
    });

    return treeData;
  }

  /**
   * Categorizes servers by their category field.
   */
  categorizeServers(servers) {
    const categorized = new Map();

    servers.forEach(server => {
      const category = server.category || 'Uncategorized';
      if (!categorized.has(category)) {
        categorized.set(category, []);
      }
      categorized.get(category).push(server);
    });

    return categorized;
  }

  /**
   * Creates a tree node element with proper structure and event handling.
   */
  createTreeNode(nodeData, level) {
    const nodeElement = document.createElement('div');
    nodeElement.className = 'tree-node';
    nodeElement.dataset.type = nodeData.type;
    nodeElement.dataset.level = level;

    const indent = level * 20;
    const hasChildren = nodeData.children && nodeData.children.length > 0;
    const nodeKey = this.getNodeKey(nodeData);
    const isExpanded = this.expandedNodes.has(nodeKey) || nodeData.expanded;

    const nodeContent = document.createElement('div');
    nodeContent.className = 'node-content';
    nodeContent.style.paddingLeft = `${indent}px`;

    if (hasChildren) {
      const expandIcon = document.createElement('span');
      expandIcon.className = `expand-icon ${isExpanded ? 'expanded' : ''}`;
      expandIcon.textContent = isExpanded ? '▼' : '▶';
      nodeContent.appendChild(expandIcon);
    } else {
      const spacer = document.createElement('span');
      spacer.className = 'expand-icon-spacer';
      nodeContent.appendChild(spacer);
    }

    const icon = document.createElement('span');
    icon.className = `node-icon ${this.getIconClass(nodeData.icon)}`;
    nodeContent.appendChild(icon);

    const label = document.createElement('span');
    label.className = 'node-label';
    label.textContent = nodeData.label;
    nodeContent.appendChild(label);

    if (nodeData.type === 'server' && nodeData.hubId && nodeData.data) {
      const isFavorite = this.configManager.isFavorite(nodeData.hubId, nodeData.data.id);
      const favoriteIcon = document.createElement('span');
      favoriteIcon.className = `favorite-icon ${isFavorite ? 'favorited' : ''}`;
      favoriteIcon.textContent = isFavorite ? '★' : '☆';
      favoriteIcon.dataset.hubId = nodeData.hubId;
      favoriteIcon.dataset.serverId = nodeData.data.id;
      nodeContent.appendChild(favoriteIcon);
    }

    nodeElement.appendChild(nodeContent);

    if (hasChildren) {
      const childrenContainer = document.createElement('div');
      childrenContainer.className = 'node-children';
      childrenContainer.style.display = isExpanded ? 'block' : 'none';

      if (isExpanded) {
        nodeData.children.forEach(child => {
          childrenContainer.appendChild(this.createTreeNode(child, level + 1));
        });
      }

      nodeElement.appendChild(childrenContainer);
    }

    nodeElement.nodeData = nodeData;
    this.attachNodeEventListeners(nodeElement);

    return nodeElement;
  }

  /**
   * Generates a unique key for a node.
   */
  getNodeKey(nodeData) {
    if (nodeData.type === 'server' && nodeData.hubId && nodeData.data) {
      return `server-${nodeData.hubId}-${nodeData.data.id}`;
    } else if (nodeData.type === 'category' && nodeData.hubId) {
      return `category-${nodeData.hubId}-${nodeData.categoryName}`;
    } else if (nodeData.type === 'hub' && nodeData.data) {
      return `hub-${nodeData.data.id}`;
    } else {
      return `${nodeData.type}-${nodeData.label}`;
    }
  }

  /**
   * Gets CSS class for node icon.
   */
  getIconClass(iconType) {
    const iconMap = {
      'folder': 'icon-folder',
      'file': 'icon-file',
      'star': 'icon-star'
    };
    return iconMap[iconType] || 'icon-default';
  }

  /**
   * Attaches event listeners to a node element.
   */
  attachNodeEventListeners(nodeElement) {
    const nodeContent = nodeElement.querySelector('.node-content');
    const expandIcon = nodeElement.querySelector('.expand-icon');
    const favoriteIcon = nodeElement.querySelector('.favorite-icon');

    const expandHandler = (e) => {
      e.stopPropagation();
      this.handleNodeExpand(nodeElement);
    };

    const selectHandler = (e) => {
      if (!favoriteIcon || e.target !== favoriteIcon) {
        this.handleNodeSelect(nodeElement);
      }
    };

    const favoriteHandler = (e) => {
      e.stopPropagation();
      this.handleFavoriteToggle(nodeElement);
    };

    if (expandIcon) {
      expandIcon.addEventListener('click', expandHandler);
      this.trackEventListener(expandIcon, 'click', expandHandler);
    }

    nodeContent.addEventListener('click', selectHandler);
    this.trackEventListener(nodeContent, 'click', selectHandler);

    if (favoriteIcon) {
      favoriteIcon.addEventListener('click', favoriteHandler);
      this.trackEventListener(favoriteIcon, 'click', favoriteHandler);
    }
  }

  /**
   * Tracks event listeners for cleanup.
   */
  trackEventListener(element, eventType, handler) {
    if (!this.eventListeners.has(element)) {
      this.eventListeners.set(element, []);
    }
    this.eventListeners.get(element).push({ eventType, handler });
  }

  /**
   * Cleans up all tracked event listeners.
   */
  cleanupTreeEventListeners() {
    for (const [element, listeners] of this.eventListeners.entries()) {
      listeners.forEach(({ eventType, handler }) => {
        element.removeEventListener(eventType, handler);
      });
    }
    this.eventListeners.clear();
  }

  /**
   * Handles node expansion/collapse.
   */
  handleNodeExpand(nodeElement) {
    const nodeData = nodeElement.nodeData;
    if (!nodeData || !nodeData.children || nodeData.children.length === 0) {
      return;
    }

    const nodeKey = this.getNodeKey(nodeData);
    const childrenContainer = nodeElement.querySelector('.node-children');
    const expandIcon = nodeElement.querySelector('.expand-icon');

    if (!childrenContainer || !expandIcon) {
      return;
    }

    const isCurrentlyExpanded = childrenContainer.style.display === 'block';

    if (isCurrentlyExpanded) {
      childrenContainer.style.display = 'none';
      expandIcon.textContent = '▶';
      expandIcon.classList.remove('expanded');
      this.expandedNodes.delete(nodeKey);
    } else {
      childrenContainer.style.display = 'block';
      expandIcon.textContent = '▼';
      expandIcon.classList.add('expanded');
      this.expandedNodes.add(nodeKey);

      if (childrenContainer.children.length === 0) {
        const level = parseInt(nodeElement.dataset.level, 10);
        nodeData.children.forEach(child => {
          childrenContainer.appendChild(this.createTreeNode(child, level + 1));
        });
      }
    }
  }

  /**
   * Handles node selection.
   */
  handleNodeSelect(nodeElement) {
    if (this.selectedNode) {
      const prevContent = this.selectedNode.querySelector('.node-content');
      if (prevContent) {
        prevContent.classList.remove('selected');
      }
    }

    const nodeContent = nodeElement.querySelector('.node-content');
    if (nodeContent) {
      nodeContent.classList.add('selected');
    }
    this.selectedNode = nodeElement;

    const nodeData = nodeElement.nodeData;
    if (!nodeData) {
      return;
    }

    if (nodeData.type === 'server' && nodeData.data) {
      this.displayServerDetails(nodeData.data, nodeData.hubId);
    } else if (nodeData.type === 'hub' && nodeData.data) {
      this.displayHubDetails(nodeData.data);
    } else if (nodeData.type === 'category') {
      this.displayCategoryDetails(nodeData);
    }
  }

  /**
   * Handles favorite toggle.
   */
  async handleFavoriteToggle(nodeElement) {
    const favoriteIcon = nodeElement.querySelector('.favorite-icon');
    if (!favoriteIcon) {
      return;
    }

    const hubId = favoriteIcon.dataset.hubId;
    const serverId = favoriteIcon.dataset.serverId;
    const nodeData = nodeElement.nodeData;

    if (!hubId || !serverId || !nodeData || !nodeData.data) {
      return;
    }

    const isFavorite = favoriteIcon.classList.contains('favorited');

    try {
      if (isFavorite) {
        await this.configManager.removeFromFavorites(hubId, serverId);
        favoriteIcon.classList.remove('favorited');
        favoriteIcon.textContent = '☆';
      } else {
        await this.configManager.addToFavorites(hubId, serverId, nodeData.data.name);
        favoriteIcon.classList.add('favorited');
        favoriteIcon.textContent = '★';
      }

      this.renderTree();

    } catch (error) {
      console.error('Error toggling favorite:', error);
      this.showError('Failed to update favorites: ' + error.message);
    }
  }

  /**
   * Displays server details in the details panel.
   */
  displayServerDetails(server, hubId) {
    if (!server || !hubId) {
      return;
    }

    const isFavorite = this.configManager.isFavorite(hubId, server.id);

    const detailsHTML = `
      <div class="server-details">
        <div class="details-header">
          <h2>${this.escapeHtml(server.name)}</h2>
          <button class="favorite-btn ${isFavorite ? 'favorited' : ''}" 
                  data-hub-id="${this.escapeHtml(hubId)}" 
                  data-server-id="${this.escapeHtml(server.id)}">
            ${isFavorite ? '★ Remove from Favorites' : '☆ Add to Favorites'}
          </button>
        </div>
        
        <div class="details-section">
          <h3>Overview</h3>
          <p class="description">${this.escapeHtml(server.description)}</p>
          
          <div class="metadata-grid">
            <div class="metadata-item">
              <span class="metadata-label">Author:</span>
              <span class="metadata-value">${this.escapeHtml(server.author)}</span>
            </div>
            <div class="metadata-item">
              <span class="metadata-label">Version:</span>
              <span class="metadata-value">${this.escapeHtml(server.version)}</span>
            </div>
            <div class="metadata-item">
              <span class="metadata-label">Category:</span>
              <span class="metadata-value">${this.escapeHtml(server.category)}</span>
            </div>
            <div class="metadata-item">
              <span class="metadata-label">Authentication:</span>
              <span class="metadata-value">${server.authRequired ? 'Required' : 'Not Required'}</span>
            </div>
          </div>
          
          ${server.tags && server.tags.length > 0 ? `
            <div class="tags">
              ${server.tags.map(tag => `<span class="tag">${this.escapeHtml(tag)}</span>`).join('')}
            </div>
          ` : ''}
        </div>
        
        <div class="details-section">
          <h3>Connection</h3>
          <div class="connection-info">
            <div class="info-item">
              <span class="info-label">Endpoint:</span>
              <code class="info-value">${this.escapeHtml(server.endpoint)}</code>
            </div>
          </div>
          
          ${server.authRequired ? `
            <div class="auth-section">
              <h4>Authentication Required</h4>
              <div class="auth-form">
                <label for="auth-token">Token:</label>
                <input type="password" id="auth-token" class="auth-input" 
                       placeholder="Enter authentication token">
              </div>
            </div>
          ` : ''}
          
          <button class="connect-btn" 
                  data-server-endpoint="${this.escapeHtml(server.endpoint)}"
                  data-hub-id="${this.escapeHtml(hubId)}"
                  data-server-id="${this.escapeHtml(server.id)}">
            Connect to Server
          </button>
        </div>
        
        <div class="details-section">
          <h3>Tools</h3>
          <div id="tools-container" class="tools-container">
            <p class="info-message">Connect to the server to view available tools</p>
          </div>
        </div>
        
        ${server.documentation ? `
          <div class="details-section">
            <h3>Documentation</h3>
            <a href="${this.escapeHtml(server.documentation)}" 
               target="_blank" 
               rel="noopener noreferrer" 
               class="doc-link">
              View Documentation
            </a>
          </div>
        ` : ''}
        
        ${server.metadata && (server.metadata.stars || server.metadata.downloads) ? `
          <div class="details-section">
            <h3>Statistics</h3>
            <div class="stats-grid">
              ${server.metadata.stars ? `
                <div class="stat-item">
                  <span class="stat-label">Stars:</span>
                  <span class="stat-value">${server.metadata.stars}</span>
                </div>
              ` : ''}
              ${server.metadata.downloads ? `
                <div class="stat-item">
                  <span class="stat-label">Downloads:</span>
                  <span class="stat-value">${server.metadata.downloads}</span>
                </div>
              ` : ''}
              ${server.metadata.lastUpdated ? `
                <div class="stat-item">
                  <span class="stat-label">Last Updated:</span>
                  <span class="stat-value">${new Date(server.metadata.lastUpdated).toLocaleDateString()}</span>
                </div>
              ` : ''}
            </div>
          </div>
        ` : ''}
      </div>
    `;

    this.detailsPanel.innerHTML = detailsHTML;
    this.attachDetailsEventListeners(server, hubId);
  }

  /**
   * Escapes HTML to prevent XSS attacks.
   */
  escapeHtml(text) {
    if (text === null || text === undefined) {
      return '';
    }
    
    const div = document.createElement('div');
    div.textContent = String(text);
    return div.innerHTML;
  }

  /**
   * Attaches event listeners to details panel elements.
   */
  attachDetailsEventListeners(server, hubId) {
    const favoriteBtn = this.detailsPanel.querySelector('.favorite-btn');
    if (favoriteBtn) {
      favoriteBtn.addEventListener('click', async () => {
        const isFavorite = favoriteBtn.classList.contains('favorited');

        try {
          if (isFavorite) {
            await this.configManager.removeFromFavorites(hubId, server.id);
            favoriteBtn.classList.remove('favorited');
            favoriteBtn.textContent = '☆ Add to Favorites';
          } else {
            await this.configManager.addToFavorites(hubId, server.id, server.name);
            favoriteBtn.classList.add('favorited');
            favoriteBtn.textContent = '★ Remove from Favorites';
          }

          this.renderTree();

        } catch (error) {
          console.error('Error toggling favorite:', error);
          this.showError('Failed to update favorites: ' + error.message);
        }
      });
    }

    const connectBtn = this.detailsPanel.querySelector('.connect-btn');
    if (connectBtn) {
      connectBtn.addEventListener('click', () => {
        this.handleServerConnection(server, hubId);
      });
    }
  }

  /**
   * Handles server connection and tool discovery.
   */
  async handleServerConnection(server, hubId) {
    const connectBtn = this.detailsPanel.querySelector('.connect-btn');
    const toolsContainer = this.detailsPanel.querySelector('#tools-container');

    if (!connectBtn || !toolsContainer) {
      return;
    }

    connectBtn.disabled = true;
    connectBtn.textContent = 'Connecting...';

    let authConfig = null;

    if (server.authRequired) {
      const tokenInput = this.detailsPanel.querySelector('#auth-token');
      const token = tokenInput ? tokenInput.value.trim() : '';

      if (!token) {
        this.showError('Please enter an authentication token');
        connectBtn.disabled = false;
        connectBtn.textContent = 'Connect to Server';
        return;
      }

      authConfig = {
        type: 'bearer',
        token: token
      };
    }

    const connectionKey = `${hubId}-${server.id}`;
    
    if (this.activeConnections.has(connectionKey)) {
      const existingClient = this.activeConnections.get(connectionKey);
      existingClient.disconnect();
      this.activeConnections.delete(connectionKey);
    }

    try {
      const client = new MCPClient(server.endpoint, authConfig);

      client.on('stateChange', (data) => {
        console.log('Connection state changed:', data.state);
      });

      await client.initialize();
      const tools = await client.listTools();

      this.activeConnections.set(connectionKey, client);
      this.displayTools(tools, client, server, hubId);

      connectBtn.textContent = 'Connected';
      connectBtn.classList.add('connected');

    } catch (error) {
      console.error('Connection error:', error);
      toolsContainer.innerHTML = `
        <div class="error-message">
          Failed to connect: ${this.escapeHtml(error.message)}
        </div>
      `;
      connectBtn.disabled = false;
      connectBtn.textContent = 'Connect to Server';
    }
  }

  /**
   * Displays tools in the tools container.
   */
  displayTools(tools, client, server, hubId) {
    const toolsContainer = this.detailsPanel.querySelector('#tools-container');
    if (!toolsContainer) {
      return;
    }

    if (!tools || tools.length === 0) {
      toolsContainer.innerHTML = '<p class="info-message">No tools available</p>';
      return;
    }

    let toolsHTML = '<div class="tools-list">';

    tools.forEach((tool, index) => {
      const toolId = `tool-${this.generateSafeId(tool.name)}-${index}`;
      
      toolsHTML += `
        <div class="tool-item" data-tool-id="${toolId}">
          <div class="tool-header">
            <h4 class="tool-name">${this.escapeHtml(tool.name)}</h4>
            <button class="test-tool-btn" data-tool-id="${toolId}">
              Test Tool
            </button>
          </div>
          <p class="tool-description">${this.escapeHtml(tool.description || 'No description available')}</p>
          
          ${tool.inputSchema ? `
            <div class="tool-schema">
              <h5>Parameters:</h5>
              <div class="schema-content" data-tool-id="${toolId}">
                ${this.renderInputSchema(tool.inputSchema, toolId)}
              </div>
            </div>
          ` : ''}
          
          <div class="tool-result" id="result-${toolId}" style="display: none;">
            <h5>Result:</h5>
            <pre class="result-content"></pre>
          </div>
        </div>
      `;
    });

    toolsHTML += '</div>';
    toolsContainer.innerHTML = toolsHTML;

    const testButtons = toolsContainer.querySelectorAll('.test-tool-btn');
    testButtons.forEach(btn => {
      btn.addEventListener('click', () => {
        const toolId = btn.dataset.toolId;
        const tool = tools.find((t, idx) => 
          `tool-${this.generateSafeId(t.name)}-${idx}` === toolId
        );
        if (tool) {
          this.handleToolTest(tool, client, toolId);
        }
      });
    });
  }

  /**
   * Generates a safe ID from a string.
   */
  generateSafeId(str) {
    return String(str).replace(/[^a-zA-Z0-9-_]/g, '-');
  }

  /**
   * Renders input schema as form fields.
   */
  renderInputSchema(schema, toolId) {
    if (!schema || !schema.properties) {
      return '<p class="info-message">No parameters required</p>';
    }

    let html = '<div class="parameter-form">';

    for (const [paramName, paramDef] of Object.entries(schema.properties)) {
      const isRequired = schema.required && schema.required.includes(paramName);
      const paramType = paramDef.type || 'string';
      const inputId = `param-${toolId}-${this.generateSafeId(paramName)}`;

      html += `
        <div class="parameter-field">
          <label for="${inputId}">
            ${this.escapeHtml(paramName)}${isRequired ? ' *' : ''}
            <span class="parameter-type">${this.escapeHtml(paramType)}</span>
          </label>
      `;

      if (paramDef.description) {
        html += `<p class="parameter-description">${this.escapeHtml(paramDef.description)}</p>`;
      }

      if (paramType === 'boolean') {
        html += `
          <select id="${inputId}" 
                  class="parameter-input" 
                  data-param-name="${this.escapeHtml(paramName)}" 
                  data-param-type="${paramType}"
                  ${isRequired ? 'required' : ''}>
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        `;
      } else if (paramType === 'number' || paramType === 'integer') {
        html += `
          <input type="number" 
                 id="${inputId}" 
                 class="parameter-input" 
                 data-param-name="${this.escapeHtml(paramName)}" 
                 data-param-type="${paramType}"
                 ${isRequired ? 'required' : ''}>
        `;
      } else if (paramType === 'object' || paramType === 'array') {
        html += `
          <textarea id="${inputId}" 
                    class="parameter-input parameter-textarea" 
                    data-param-name="${this.escapeHtml(paramName)}" 
                    data-param-type="${paramType}"
                    placeholder="Enter JSON"
                    rows="4"
                    ${isRequired ? 'required' : ''}></textarea>
        `;
      } else {
        html += `
          <input type="text" 
                 id="${inputId}" 
                 class="parameter-input" 
                 data-param-name="${this.escapeHtml(paramName)}" 
                 data-param-type="${paramType}"
                 ${isRequired ? 'required' : ''}>
        `;
      }

      html += '</div>';
    }

    html += '</div>';
    return html;
  }

  /**
   * Handles tool testing.
   */
  async handleToolTest(tool, client, toolId) {
    const resultContainer = this.detailsPanel.querySelector(`#result-${toolId}`);
    const resultContent = resultContainer ? resultContainer.querySelector('.result-content') : null;

    if (!resultContainer || !resultContent) {
      return;
    }

    resultContainer.style.display = 'block';
    resultContent.textContent = 'Executing tool...';
    resultContent.className = 'result-content';

    const parameters = {};

    if (tool.inputSchema && tool.inputSchema.properties) {
      const toolItem = this.detailsPanel.querySelector(`[data-tool-id="${toolId}"]`);
      if (!toolItem) {
        return;
      }

      const paramInputs = toolItem.querySelectorAll('.parameter-input');

      let validationError = null;

      paramInputs.forEach(input => {
        const paramName = input.dataset.paramName;
        const paramType = input.dataset.paramType;
        let value = input.value;

        if (!value && tool.inputSchema.required && 
            tool.inputSchema.required.includes(paramName)) {
          validationError = `Required parameter '${paramName}' is missing`;
          return;
        }

        if (value) {
          try {
            if (paramType === 'number') {
              value = parseFloat(value);
              if (isNaN(value)) {
                validationError = `Parameter '${paramName}' must be a valid number`;
                return;
              }
            } else if (paramType === 'integer') {
              value = parseInt(value, 10);
              if (isNaN(value)) {
                validationError = `Parameter '${paramName}' must be a valid integer`;
                return;
              }
            } else if (paramType === 'boolean') {
              value = value === 'true';
            } else if (paramType === 'object' || paramType === 'array') {
              value = JSON.parse(value);
            }

            parameters[paramName] = value;

          } catch (error) {
            validationError = `Invalid value for parameter '${paramName}': ${error.message}`;
            return;
          }
        }
      });

      if (validationError) {
        resultContent.textContent = `Error: ${validationError}`;
        resultContent.classList.add('error');
        return;
      }
    }

    try {
      const result = await client.callTool(tool.name, parameters);

      resultContent.textContent = JSON.stringify(result, null, 2);
      resultContent.classList.remove('error');
      resultContent.classList.add('success');

    } catch (error) {
      resultContent.textContent = `Error: ${error.message}`;
      resultContent.classList.add('error');
      resultContent.classList.remove('success');
    }
  }

  /**
   * Displays hub details.
   */
  displayHubDetails(hub) {
    if (!hub) {
      return;
    }

    const servers = this.discoveryService.getServersFromHub(hub.id);

    const detailsHTML = `
      <div class="hub-details">
        <h2>${this.escapeHtml(hub.name)}</h2>
        <p class="description">${this.escapeHtml(hub.description)}</p>
        
        <div class="details-section">
          <h3>Hub Information</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">URL:</span>
              <code class="info-value">${this.escapeHtml(hub.url)}</code>
            </div>
            <div class="info-item">
              <span class="info-label">Status:</span>
              <span class="info-value ${hub.enabled ? 'status-enabled' : 'status-disabled'}">
                ${hub.enabled ? 'Enabled' : 'Disabled'}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">Servers:</span>
              <span class="info-value">${servers.length}</span>
            </div>
            ${hub.lastSync ? `
              <div class="info-item">
                <span class="info-label">Last Synced:</span>
                <span class="info-value">${new Date(hub.lastSync).toLocaleString()}</span>
              </div>
            ` : ''}
          </div>
        </div>
        
        <div class="details-section">
          <h3>Actions</h3>
          <div class="action-buttons">
            <button class="action-btn" id="sync-hub-btn" data-hub-id="${this.escapeHtml(hub.id)}">
              Sync Hub
            </button>
            <button class="action-btn ${hub.enabled ? 'disable' : 'enable'}" 
                    id="toggle-hub-btn" 
                    data-hub-id="${this.escapeHtml(hub.id)}">
              ${hub.enabled ? 'Disable Hub' : 'Enable Hub'}
            </button>
            <button class="action-btn danger" id="remove-hub-btn" data-hub-id="${this.escapeHtml(hub.id)}">
              Remove Hub
            </button>
          </div>
        </div>
      </div>
    `;

    this.detailsPanel.innerHTML = detailsHTML;
    this.attachHubActionListeners(hub);
  }

  /**
   * Attaches event listeners for hub actions.
   */
  attachHubActionListeners(hub) {
    const syncBtn = this.detailsPanel.querySelector('#sync-hub-btn');
    if (syncBtn) {
      syncBtn.addEventListener('click', async () => {
        syncBtn.disabled = true;
        syncBtn.textContent = 'Syncing...';

        try {
          await this.discoveryService.syncHub(hub.id);
          this.renderTree();
          this.displayHubDetails(hub);
          this.showSuccess('Hub synced successfully');
        } catch (error) {
          this.showError('Failed to sync hub: ' + error.message);
        } finally {
          syncBtn.disabled = false;
          syncBtn.textContent = 'Sync Hub';
        }
      });
    }

    const toggleBtn = this.detailsPanel.querySelector('#toggle-hub-btn');
    if (toggleBtn) {
      toggleBtn.addEventListener('click', async () => {
        try {
          await this.configManager.updateHub(hub.id, { enabled: !hub.enabled });
          this.renderTree();
          const updatedHub = this.configManager.getHub(hub.id);
          if (updatedHub) {
            this.displayHubDetails(updatedHub);
          }
        } catch (error) {
          this.showError('Failed to toggle hub: ' + error.message);
        }
      });
    }

    const removeBtn = this.detailsPanel.querySelector('#remove-hub-btn');
    if (removeBtn) {
      removeBtn.addEventListener('click', async () => {
        if (confirm(`Are you sure you want to remove ${hub.name}?`)) {
          try {
            await this.configManager.removeHub(hub.id);
            this.renderTree();
            this.detailsPanel.innerHTML = '<div class="empty-state">Select a server to view details</div>';
            this.showSuccess('Hub removed successfully');
          } catch (error) {
            this.showError('Failed to remove hub: ' + error.message);
          }
        }
      });
    }
  }

  /**
   * Displays category details.
   */
  displayCategoryDetails(nodeData) {
    if (!nodeData || !nodeData.children) {
      return;
    }

    const servers = nodeData.children.map(child => child.data).filter(Boolean);

    const detailsHTML = `
      <div class="category-details">
        <h2>${this.escapeHtml(nodeData.label)}</h2>
        <p class="server-count">${servers.length} server${servers.length !== 1 ? 's' : ''} in this category</p>
        
        <div class="server-list">
          ${servers.map(server => `
            <div class="server-card">
              <h3>${this.escapeHtml(server.name)}</h3>
              <p>${this.escapeHtml(server.description)}</p>
              <div class="server-meta">
                <span class="author">by ${this.escapeHtml(server.author)}</span>
                ${server.metadata && server.metadata.stars ? `
                  <span class="stars">★ ${server.metadata.stars}</span>
                ` : ''}
              </div>
            </div>
          `).join('')}
        </div>
      </div>
    `;

    this.detailsPanel.innerHTML = detailsHTML;
  }

  /**
   * Sets up global event listeners.
   */
  setupEventListeners() {
    const syncAllBtn = document.getElementById('sync-all-btn');
    if (syncAllBtn) {
      syncAllBtn.addEventListener('click', async () => {
        syncAllBtn.disabled = true;
        syncAllBtn.textContent = 'Syncing...';

        try {
          await this.discoveryService.syncAllHubs();
          this.renderTree();
          this.showSuccess('All hubs synced successfully');
        } catch (error) {
          this.showError('Some hubs failed to sync. Check console for details.');
        } finally {
          syncAllBtn.disabled = false;
          syncAllBtn.textContent = 'Sync All Hubs';
        }
      });
    }

    const addHubBtn = document.getElementById('add-hub-btn');
    if (addHubBtn) {
      addHubBtn.addEventListener('click', () => {
        this.showAddHubDialog();
      });
    }

    const searchInput = document.getElementById('search-input');
    if (searchInput) {
      let searchTimeout;
      searchInput.addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
          this.handleSearch(e.target.value);
        }, 300);
      });
    }

    const favoritesBtn = document.getElementById('favorites-btn');
    if (favoritesBtn) {
      favoritesBtn.addEventListener('click', () => {
        this.showFavorites();
      });
    }
  }

  /**
   * Shows the add hub dialog.
   */
  showAddHubDialog() {
    const dialogHTML = `
      <div class="modal-overlay" id="add-hub-modal">
        <div class="modal-content">
          <h2>Add New Hub</h2>
          <form id="add-hub-form">
            <div class="form-group">
              <label for="hub-id">Hub ID:</label>
              <input type="text" id="hub-id" required placeholder="my-custom-hub">
            </div>
            <div class="form-group">
              <label for="hub-name">Hub Name:</label>
              <input type="text" id="hub-name" required placeholder="My Custom Hub">
            </div>
            <div class="form-group">
              <label for="hub-url">Hub URL:</label>
              <input type="url" id="hub-url" required placeholder="https://example.com/mcp-hub">
            </div>
            <div class="form-group">
              <label for="hub-description">Description:</label>
              <textarea id="hub-description" rows="3"></textarea>
            </div>
            <div class="form-group">
              <label for="hub-auth-type">Authentication:</label>
              <select id="hub-auth-type">
                <option value="none">None</option>
                <option value="bearer">Bearer Token</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="submit" class="btn-primary">Add Hub</button>
              <button type="button" class="btn-secondary" id="cancel-add-hub">Cancel</button>
            </div>
          </form>
        </div>
      </div>
    `;

    document.body.insertAdjacentHTML('beforeend', dialogHTML);

    const modal = document.getElementById('add-hub-modal');
    const form = document.getElementById('add-hub-form');
    const cancelBtn = document.getElementById('cancel-add-hub');

    if (!modal || !form || !cancelBtn) {
      return;
    }

    form.addEventListener('submit', async (e) => {
      e.preventDefault();

      const hubIdInput = document.getElementById('hub-id');
      const hubNameInput = document.getElementById('hub-name');
      const hubUrlInput = document.getElementById('hub-url');
      const hubDescInput = document.getElementById('hub-description');
      const hubAuthInput = document.getElementById('hub-auth-type');

      if (!hubIdInput || !hubNameInput || !hubUrlInput || !hubAuthInput) {
        return;
      }

      const hubConfig = {
        id: hubIdInput.value.trim(),
        name: hubNameInput.value.trim(),
        url: hubUrlInput.value.trim(),
        description: hubDescInput ? hubDescInput.value.trim() : '',
        authentication: {
          type: hubAuthInput.value
        }
      };

      try {
        await this.configManager.addHub(hubConfig);
        modal.remove();
        this.renderTree();
        this.showSuccess('Hub added successfully');
      } catch (error) {
        this.showError('Failed to add hub: ' + error.message);
      }
    });

    cancelBtn.addEventListener('click', () => {
      modal.remove();
    });

    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.remove();
      }
    });
  }

  /**
   * Handles search functionality.
   */
  handleSearch(query) {
    if (!query || !query.trim()) {
      this.renderTree();
      return;
    }

    const results = this.discoveryService.searchServers(query);

    this.cleanupTreeEventListeners();
    this.treeContainer.innerHTML = '';

    const searchNode = this.createTreeNode({
      type: 'root',
      label: `Search Results (${results.length})`,
      children: results.map(server => ({
        type: 'server',
        data: server,
        label: server.name,
        icon: 'file',
        hubId: server.hubId
      })),
      expanded: true
    }, 0);

    this.treeContainer.appendChild(searchNode);
  }

  /**
   * Shows favorites view.
   */
  showFavorites() {
    const favorites = this.discoveryService.getFavoriteServers();

    this.cleanupTreeEventListeners();
    this.treeContainer.innerHTML = '';

    const favoritesNode = this.createTreeNode({
      type: 'root',
      label: `Favorites (${favorites.length})`,
      children: favorites.map(server => ({
        type: 'server',
        data: server,
        label: server.name,
        icon: 'file',
        hubId: server.hubId
      })),
      expanded: true
    }, 0);

    this.treeContainer.appendChild(favoritesNode);
  }

  /**
   * Shows an error message to the user.
   */
  showError(message) {
    alert('Error: ' + message);
  }

  /**
   * Shows a success message to the user.
   */
  showSuccess(message) {
    alert(message);
  }

  /**
   * Cleans up resources when destroying the UI.
   */
  destroy() {
    this.cleanupTreeEventListeners();
    
    for (const [key, client] of this.activeConnections.entries()) {
      client.disconnect();
    }
    this.activeConnections.clear();

    if (this.treeContainer) {
      this.treeContainer.innerHTML = '';
    }
    if (this.detailsPanel) {
      this.detailsPanel.innerHTML = '';
    }
  }
}

The FileExplorerUI class now includes comprehensive error handling, proper event listener cleanup to prevent memory leaks, XSS protection through HTML escaping, and better scoping of tool parameters to prevent cross-contamination.

STYLING THE APPLICATION

The CSS provides a polished, professional appearance while maintaining usability and accessibility.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  background-color: #f5f5f5;
}

.explorer-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  flex-shrink: 0;
}

.toolbar-btn {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.toolbar-btn:hover {
  background-color: #0056b3;
}

.toolbar-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.search-box {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-box:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.content-area {
  display: flex;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.tree-panel {
  width: 350px;
  background-color: #fff;
  border-right: 1px solid #ddd;
  overflow-y: auto;
  flex-shrink: 0;
}

.tree-container {
  padding: 10px;
}

.tree-node {
  user-select: none;
}

.node-content {
  display: flex;
  align-items: center;
  padding: 6px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.15s;
}

.node-content:hover {
  background-color: #f0f0f0;
}

.node-content.selected {
  background-color: #e3f2fd;
}

.expand-icon {
  width: 16px;
  height: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 4px;
  font-size: 10px;
  cursor: pointer;
  color: #666;
  flex-shrink: 0;
}

.expand-icon:hover {
  color: #333;
}

.expand-icon-spacer {
  width: 16px;
  display: inline-block;
  margin-right: 4px;
  flex-shrink: 0;
}

.node-icon {
  width: 16px;
  height: 16px;
  margin-right: 6px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.icon-folder::before {
  content: '📁';
}

.icon-file::before {
  content: '📄';
}

.icon-star::before {
  content: '⭐';
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.favorite-icon {
  margin-left: 8px;
  cursor: pointer;
  color: #ffa500;
  font-size: 16px;
  flex-shrink: 0;
  transition: transform 0.2s;
}

.favorite-icon:hover {
  transform: scale(1.2);
}

.favorite-icon.favorited {
  color: #ff8c00;
}

.node-children {
  margin-left: 0;
}

.details-panel {
  flex: 1;
  background-color: #fff;
  overflow-y: auto;
  padding: 20px;
  min-width: 0;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 16px;
}

.server-details,
.hub-details,
.category-details {
  max-width: 900px;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #eee;
  gap: 15px;
  flex-wrap: wrap;
}

.details-header h2 {
  font-size: 24px;
  color: #333;
  word-break: break-word;
}

.favorite-btn {
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  white-space: nowrap;
}

.favorite-btn:hover {
  background-color: #f8f8f8;
}

.favorite-btn.favorited {
  background-color: #fff3cd;
  border-color: #ffa500;
  color: #856404;
}

.details-section {
  margin-bottom: 30px;
}

.details-section h3 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #555;
}

.description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  word-wrap: break-word;
}

.metadata-grid,
.info-grid,
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.metadata-item,
.info-item,
.stat-item {
  display: flex;
  flex-direction: column;
}

.metadata-label,
.info-label,
.stat-label {
  font-weight: 600;
  color: #666;
  font-size: 12px;
  text-transform: uppercase;
  margin-bottom: 4px;
}

.metadata-value,
.info-value,
.stat-value {
  color: #333;
  font-size: 14px;
  word-break: break-word;
}

code.info-value {
  background-color: #f5f5f5;
  padding: 4px 8px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  word-break: break-all;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.tag {
  padding: 4px 12px;
  background-color: #e3f2fd;
  color: #1976d2;
  border-radius: 12px;
  font-size: 12px;
}

.connection-info {
  margin-bottom: 15px;
}

.auth-section {
  margin: 15px 0;
  padding: 15px;
  background-color: #fff3cd;
  border-radius: 4px;
  border: 1px solid #ffc107;
}

.auth-section h4 {
  margin-bottom: 10px;
  color: #856404;
}

.auth-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
}

.auth-input {
  width: 100%;
  max-width: 400px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.auth-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.connect-btn {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: background-color 0.2s;
}

.connect-btn:hover:not(:disabled) {
  background-color: #218838;
}

.connect-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.connect-btn.connected {
  background-color: #17a2b8;
}

.tools-container {
  margin-top: 15px;
}

.tools-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tool-item {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background-color: #fafafa;
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
  flex-wrap: wrap;
}

.tool-name {
  font-size: 16px;
  color: #333;
  word-break: break-word;
}

.test-tool-btn {
  padding: 6px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  white-space: nowrap;
}

.test-tool-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.test-tool-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.tool-description {
  color: #666;
  margin-bottom: 10px;
  word-wrap: break-word;
}

.tool-schema {
  margin-top: 15px;
}

.tool-schema h5 {
  margin-bottom: 10px;
  color: #555;
}

.parameter-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.parameter-field {
  display: flex;
  flex-direction: column;
}

.parameter-field label {
  font-weight: 600;
  margin-bottom: 4px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.parameter-type {
  font-size: 11px;
  color: #999;
  font-weight: normal;
}

.parameter-description {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.parameter-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
}

.parameter-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.parameter-textarea {
  font-family: 'Courier New', monospace;
  resize: vertical;
}

.tool-result {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.tool-result h5 {
  margin-bottom: 10px;
  color: #555;
}

.result-content {
  background-color: #fff;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #ddd;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.result-content.success {
  border-color: #28a745;
  background-color: #f0fff4;
}

.result-content.error {
  border-color: #dc3545;
  background-color: #fff5f5;
  color: #dc3545;
}

.info-message {
  color: #666;
  font-style: italic;
  padding: 10px;
}

.error-message {
  color: #dc3545;
  padding: 10px;
  background-color: #fff5f5;
  border: 1px solid #dc3545;
  border-radius: 4px;
  word-wrap: break-word;
}

.doc-link {
  display: inline-block;
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.doc-link:hover {
  background-color: #0056b3;
}

.status-enabled {
  color: #28a745;
  font-weight: 600;
}

.status-disabled {
  color: #dc3545;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.action-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.action-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.action-btn.danger {
  background-color: #dc3545;
}

.action-btn.danger:hover:not(:disabled) {
  background-color: #c82333;
}

.action-btn.disable {
  background-color: #ffc107;
  color: #333;
}

.action-btn.enable {
  background-color: #28a745;
}

.server-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.server-card {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}

.server-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.server-card h3 {
  font-size: 16px;
  margin-bottom: 8px;
  color: #333;
  word-break: break-word;
}

.server-card p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  word-wrap: break-word;
}

.server-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  gap: 10px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content h2 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 600;
  color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.btn-primary {
  flex: 1;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  flex: 1;
  padding: 10px 20px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

@media (max-width: 768px) {
  .content-area {
    flex-direction: column;
  }
  
  .tree-panel {
    width: 100%;
    max-height: 40vh;
    border-right: none;
    border-bottom: 1px solid #ddd;
  }
  
  .details-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .metadata-grid,
  .info-grid,
  .stats-grid {
    grid-template-columns: 1fr;
  }
}

BRINGING IT ALL TOGETHER

Finally, we create the main application class that initializes all components and starts the application.

class MCPHubExplorer {
  constructor() {
    this.configManager = null;
    this.discoveryService = null;
    this.ui = null;
    this.autoSyncInterval = null;
  }

  async initialize() {
    try {
      console.log('Initializing MCP Hub Explorer...');

      this.configManager = new ConfigurationManager();
      await this.configManager.initialize();
      console.log('Configuration loaded successfully');

      this.discoveryService = new HubDiscoveryService(this.configManager);
      console.log('Discovery service initialized');

      console.log('Syncing with configured hubs...');
      await this.discoveryService.syncAllHubs();
      console.log('Hub sync completed');

      this.ui = new FileExplorerUI(this.configManager, this.discoveryService);
      this.ui.initialize();
      console.log('UI initialized');

      this.setupAutoSync();

      console.log('MCP Hub Explorer ready');

    } catch (error) {
      console.error('Failed to initialize application:', error);
      this.showFatalError(error);
    }
  }

  setupAutoSync() {
    const settings = this.configManager.config.settings;

    if (settings.autoSync && settings.syncInterval > 0) {
      this.autoSyncInterval = setInterval(async () => {
        console.log('Auto-syncing hubs...');
        try {
          await this.discoveryService.syncAllHubs();
          if (this.ui) {
            this.ui.renderTree();
          }
        } catch (error) {
          console.error('Auto-sync failed:', error);
        }
      }, settings.syncInterval);
    }
  }

  showFatalError(error) {
    const appContainer = document.getElementById('app');
    if (!appContainer) {
      return;
    }

    appContainer.innerHTML = `
      <div style="display: flex; align-items: center; justify-content: center; height: 100vh; flex-direction: column; font-family: sans-serif; padding: 20px;">
        <h1 style="color: #dc3545;">Application Error</h1>
        <p style="color: #666; max-width: 600px; text-align: center; margin: 20px 0;">
          The application failed to initialize. Please check the console for details.
        </p>
        <pre style="background: #f5f5f5; padding: 15px; border-radius: 4px; margin-top: 20px; max-width: 800px; overflow: auto; width: 100%;">
${this.escapeHtml(error.message)}
        </pre>
        <button onclick="location.reload()" style="margin-top: 20px; padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
          Reload Application
        </button>
      </div>
    `;
  }

  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = String(text);
    return div.innerHTML;
  }

  destroy() {
    if (this.autoSyncInterval) {
      clearInterval(this.autoSyncInterval);
      this.autoSyncInterval = null;
    }

    if (this.ui) {
      this.ui.destroy();
      this.ui = null;
    }

    this.discoveryService = null;
    this.configManager = null;
  }
}

document.addEventListener('DOMContentLoaded', async () => {
  const app = new MCPHubExplorer();
  window.mcpApp = app;
  await app.initialize();
});

HTML STRUCTURE

The application requires a simple HTML file to host the JavaScript and CSS.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MCP Hub Explorer</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div id="app">
    <div style="display: flex; align-items: center; justify-content: center; height: 100vh; font-family: sans-serif;">
      <div style="text-align: center;">
        <h1>Loading MCP Hub Explorer...</h1>
        <p style="color: #666;">Please wait while the application initializes</p>
      </div>
    </div>
  </div>
  
  <script src="storage.js"></script>
  <script src="config.js"></script>
  <script src="mcp-client.js"></script>
  <script src="discovery.js"></script>
  <script src="ui.js"></script>
  <script src="app.js"></script>
</body>
</html>

CONCLUSION

We have built a comprehensive, production-ready web-based MCP Hub Explorer that addresses all the critical issues identified in the code review. The application now features proper error handling, memory leak prevention, XSS protection, timeout management, and clean resource cleanup. The architecture is browser-compatible, using localStorage instead of Node.js file system APIs, and properly handles CORS, authentication, and network errors.

The modular design allows for easy extension and maintenance. Each component has a single responsibility and communicates through well-defined interfaces. The UI provides an intuitive file-explorer metaphor that makes discovering and testing MCP servers accessible to users of all technical levels.

Future enhancements could include IndexedDB for larger datasets, service workers for offline functionality, WebSocket support for real-time updates, and a backend API for team collaboration features. The foundation we have built makes all these extensions straightforward to implement.