#
tokens: 37621/50000 4/101 files (page 4/6)
lines: off (toggle) GitHub
raw markdown copy
This is page 4 of 6. Use http://codebase.md/sammcj/bybit-mcp?page={x} to view the full context.

# Directory Structure

```
├── .env.example
├── .gitignore
├── client
│   ├── .env.example
│   ├── .gitignore
│   ├── package.json
│   ├── pnpm-lock.yaml
│   ├── README.md
│   ├── src
│   │   ├── cli.ts
│   │   ├── client.ts
│   │   ├── config.ts
│   │   ├── env.ts
│   │   ├── index.ts
│   │   └── launch.ts
│   └── tsconfig.json
├── DEV_PLAN.md
├── docs
│   └── HTTP_SERVER.md
├── eslint.config.js
├── jest.config.js
├── LICENSE
├── package-lock.json
├── package.json
├── pnpm-lock.yaml
├── README.md
├── specs
│   ├── bybit
│   │   ├── bybit-api-v5-openapi.yaml
│   │   └── bybit-api-v5-postman-collection.json
│   ├── mcp
│   │   ├── mcp-schema.json
│   │   └── mcp-schema.ts
│   └── README.md
├── src
│   ├── __tests__
│   │   ├── GetMLRSI.test.ts
│   │   ├── integration.test.ts
│   │   ├── test-setup.ts
│   │   └── tools.test.ts
│   ├── constants.ts
│   ├── env.ts
│   ├── httpServer.ts
│   ├── index.ts
│   ├── tools
│   │   ├── BaseTool.ts
│   │   ├── GetInstrumentInfo.ts
│   │   ├── GetKline.ts
│   │   ├── GetMarketInfo.ts
│   │   ├── GetMarketStructure.ts
│   │   ├── GetMLRSI.ts
│   │   ├── GetOrderBlocks.ts
│   │   ├── GetOrderbook.ts
│   │   ├── GetOrderHistory.ts
│   │   ├── GetPositions.ts
│   │   ├── GetTicker.ts
│   │   ├── GetTrades.ts
│   │   └── GetWalletBalance.ts
│   └── utils
│       ├── knnAlgorithm.ts
│       ├── mathUtils.ts
│       ├── toolLoader.ts
│       └── volumeAnalysis.ts
├── tsconfig.json
└── webui
    ├── .dockerignore
    ├── .env.example
    ├── build-docker.sh
    ├── docker-compose.yml
    ├── docker-entrypoint.sh
    ├── docker-healthcheck.sh
    ├── DOCKER.md
    ├── Dockerfile
    ├── index.html
    ├── package.json
    ├── pnpm-lock.yaml
    ├── pnpm-workspace.yaml
    ├── public
    │   ├── favicon.svg
    │   └── inter.woff2
    ├── README.md
    ├── screenshot.png
    ├── src
    │   ├── assets
    │   │   └── fonts
    │   │       └── fonts.css
    │   ├── components
    │   │   ├── AgentDashboard.ts
    │   │   ├── chat
    │   │   │   ├── DataCard.ts
    │   │   │   └── MessageRenderer.ts
    │   │   ├── ChatApp.ts
    │   │   ├── DataVerificationPanel.ts
    │   │   ├── DebugConsole.ts
    │   │   └── ToolsManager.ts
    │   ├── main.ts
    │   ├── services
    │   │   ├── agentConfig.ts
    │   │   ├── agentMemory.ts
    │   │   ├── aiClient.ts
    │   │   ├── citationProcessor.ts
    │   │   ├── citationStore.ts
    │   │   ├── configService.ts
    │   │   ├── logService.ts
    │   │   ├── mcpClient.ts
    │   │   ├── multiStepAgent.ts
    │   │   ├── performanceOptimiser.ts
    │   │   └── systemPrompt.ts
    │   ├── styles
    │   │   ├── agent-dashboard.css
    │   │   ├── base.css
    │   │   ├── citations.css
    │   │   ├── components.css
    │   │   ├── data-cards.css
    │   │   ├── main.css
    │   │   ├── processing.css
    │   │   ├── variables.css
    │   │   └── verification-panel.css
    │   ├── types
    │   │   ├── agent.ts
    │   │   ├── ai.ts
    │   │   ├── citation.ts
    │   │   ├── mcp.ts
    │   │   └── workflow.ts
    │   └── utils
    │       ├── dataDetection.ts
    │       └── formatters.ts
    ├── tsconfig.json
    └── vite.config.ts
```

# Files

--------------------------------------------------------------------------------
/webui/src/styles/components.css:
--------------------------------------------------------------------------------

```css
/* Component styles */

/* Loading */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: var(--bg-primary);
}

.loading-spinner {
  width: 2rem;
  height: 2rem;
  border: 2px solid var(--border-primary);
  border-top: 2px solid var(--color-primary);
  border-radius: var(--radius-full);
  animation: spin 1s linear infinite;
  margin-bottom: var(--spacing-md);
}

/* Main Layout */
.main-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--bg-primary);
}

/* Header */
.header {
  height: var(--header-height);
  background-color: var(--bg-elevated);
  border-bottom: 1px solid var(--border-primary);
  box-shadow: var(--shadow-sm);
  z-index: var(--z-sticky);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 var(--spacing-lg);
  max-width: 100%;
}

.logo {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.logo h1 {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-primary);
}

.version {
  font-size: var(--font-size-xs);
  color: var(--text-tertiary);
  background-color: var(--bg-secondary);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-full);
}

.header-controls {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.theme-toggle,
.settings-btn,
.agent-dashboard-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.5rem;
  height: 2.5rem;
  border-radius: var(--radius-lg);
  background-color: var(--bg-secondary);
  color: var(--text-secondary);
  transition: all var(--transition-fast);
}

.theme-toggle:hover,
.settings-btn:hover,
.agent-dashboard-btn:hover {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.agent-dashboard-btn.active {
  background-color: var(--color-primary);
  color: var(--text-inverse);
}

/* Main Content */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* Sidebar */
.sidebar {
  width: var(--sidebar-width);
  background-color: var(--bg-secondary);
  border-right: 1px solid var(--border-primary);
  padding: var(--spacing-lg);
}

.nav-menu {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.nav-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  border-radius: var(--radius-lg);
  background-color: transparent;
  color: var(--text-secondary);
  text-align: left;
  transition: all var(--transition-fast);
  width: 100%;
}

.nav-item:hover {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.nav-item.active {
  background-color: var(--color-primary);
  color: var(--text-inverse);
}

.nav-icon {
  font-size: var(--font-size-lg);
  width: 1.5rem;
  text-align: center;
}

.nav-label {
  font-weight: var(--font-weight-medium);
}

/* Content Area */
.content-area {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.view {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
  visibility: hidden;
  transition: all var(--transition-normal);
  overflow: auto;
}

.view.active {
  opacity: 1;
  visibility: visible;
}

/* Chat Components */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: var(--spacing-lg);
  scroll-behavior: smooth;
}

.welcome-message {
  text-align: center;
  padding: var(--spacing-2xl);
  max-width: 600px;
  margin: 0 auto;
}

.welcome-message h2 {
  margin-bottom: var(--spacing-md);
  color: var(--text-primary);
}

.welcome-message p {
  color: var(--text-secondary);
  margin-bottom: var(--spacing-xl);
}

.example-queries {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  max-width: 400px;
  margin: 0 auto;
}

.example-query {
  padding: var(--spacing-md);
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-lg);
  color: var(--text-secondary);
  text-align: left;
  transition: all var(--transition-fast);
}

.example-query:hover {
  background-color: var(--bg-tertiary);
  border-color: var(--border-secondary);
  color: var(--text-primary);
}

.chat-message {
  margin-bottom: var(--spacing-lg);
  animation: fadeIn 0.3s ease-out;
}

.message-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
}

.message-avatar {
  width: 2rem;
  height: 2rem;
  border-radius: var(--radius-full);
  background-color: var(--color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-inverse);
  font-weight: var(--font-weight-semibold);
}

.message-avatar.user {
  background-color: var(--color-accent);
}

.message-name {
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
}

.message-time {
  font-size: var(--font-size-xs);
  color: var(--text-tertiary);
}

.message-content {
  background-color: var(--bg-secondary);
  padding: var(--spacing-md);
  border-radius: var(--radius-lg);
  margin-left: 2.5rem;
}

.message-content.user {
  background-color: var(--color-primary);
  color: var(--text-inverse);
  margin-left: 0;
  margin-right: 2.5rem;
}

/* Markdown content styling */
.message-content h1,
.message-content h2,
.message-content h3,
.message-content h4,
.message-content h5,
.message-content h6 {
  margin: var(--spacing-md) 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-weight: var(--font-weight-semibold);
}

.message-content h1 { font-size: var(--font-size-xl); }
.message-content h2 { font-size: var(--font-size-lg); }
.message-content h3 { font-size: var(--font-size-md); }
.message-content h4,
.message-content h5,
.message-content h6 { font-size: var(--font-size-base); }

.message-content p {
  margin: var(--spacing-sm) 0;
  line-height: 1.6;
}

.message-content ul,
.message-content ol {
  margin: var(--spacing-sm) 0;
  padding-left: var(--spacing-lg);
}

.message-content li {
  margin: var(--spacing-xs) 0;
  line-height: 1.5;
}

.message-content blockquote {
  margin: var(--spacing-md) 0;
  padding: var(--spacing-sm) var(--spacing-md);
  border-left: 3px solid var(--color-primary);
  background-color: var(--bg-tertiary);
  border-radius: 0 var(--radius-md) var(--radius-md) 0;
  font-style: italic;
}

.message-content code {
  background-color: var(--bg-tertiary);
  padding: 0.125rem 0.25rem;
  border-radius: var(--radius-sm);
  font-family: var(--font-mono);
  font-size: 0.875em;
  color: var(--text-primary);
}

.message-content pre {
  margin: var(--spacing-md) 0;
  padding: var(--spacing-md);
  background-color: var(--bg-tertiary);
  border-radius: var(--radius-md);
  overflow-x: auto;
  border: 1px solid var(--border-primary);
}

.message-content pre code {
  background-color: transparent;
  padding: 0;
  border-radius: 0;
  font-size: var(--font-size-sm);
}

.message-content table {
  width: 100%;
  margin: var(--spacing-md) 0;
  border-collapse: collapse;
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  overflow: hidden;
}

.message-content th,
.message-content td {
  padding: var(--spacing-sm) var(--spacing-md);
  text-align: left;
  border-bottom: 1px solid var(--border-primary);
}

.message-content th {
  background-color: var(--bg-tertiary);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
}

.message-content tr:last-child td {
  border-bottom: none;
}

.message-content a {
  color: var(--color-primary);
  text-decoration: underline;
  transition: color var(--transition-fast);
}

.message-content a:hover {
  color: var(--color-primary-hover);
}

.message-content hr {
  margin: var(--spacing-lg) 0;
  border: none;
  border-top: 1px solid var(--border-primary);
}

/* User message markdown overrides */
.message-content.user h1,
.message-content.user h2,
.message-content.user h3,
.message-content.user h4,
.message-content.user h5,
.message-content.user h6 {
  color: var(--text-inverse);
}

.message-content.user code {
  background-color: rgba(255, 255, 255, 0.1);
  color: var(--text-inverse);
}

.message-content.user pre {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
}

.message-content.user blockquote {
  background-color: rgba(255, 255, 255, 0.1);
  border-left-color: var(--text-inverse);
}

.message-content.user a {
  color: var(--text-inverse);
}

.message-content.user th {
  background-color: rgba(255, 255, 255, 0.1);
  color: var(--text-inverse);
}

.message-content.user hr {
  border-top-color: rgba(255, 255, 255, 0.3);
}



/* Chat Input */
.chat-input-container {
  padding: var(--spacing-lg);
  background-color: var(--bg-elevated);
  border-top: 1px solid var(--border-primary);
}

.chat-input-wrapper {
  display: flex;
  gap: var(--spacing-sm);
  align-items: flex-end;
  max-width: 800px;
  margin: 0 auto;
}

.chat-input {
  flex: 1;
  min-height: 2.5rem;
  max-height: 8rem;
  padding: var(--spacing-md);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-lg);
  background-color: var(--bg-primary);
  color: var(--text-primary);
  resize: none;
  transition: border-color var(--transition-fast);
}

.chat-input:focus {
  border-color: var(--border-focus);
}

.send-btn {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: var(--radius-lg);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}

.send-btn:hover:not(:disabled) {
  background-color: var(--color-primary-hover);
}

.send-btn:disabled {
  background-color: var(--border-secondary);
  color: var(--text-tertiary);
}

.input-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: var(--spacing-sm);
  font-size: var(--font-size-xs);
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-tertiary);
}

.typing-indicator {
  color: var(--text-tertiary);
  animation: pulse 1.5s ease-in-out infinite;
}

/* Charts */
.charts-container {
  padding: var(--spacing-lg);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-controls {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  align-items: center;
}

.symbol-select,
.interval-select {
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  background-color: var(--bg-primary);
  color: var(--text-primary);
}

.refresh-btn {
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  border-radius: var(--radius-md);
  transition: background-color var(--transition-fast);
}

.refresh-btn:hover {
  background-color: var(--color-primary-hover);
}

.chart-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: var(--spacing-lg);
  flex: 1;
}

.chart-panel {
  background-color: var(--bg-elevated);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
}

.chart-panel h3 {
  margin-bottom: var(--spacing-md);
  color: var(--text-primary);
}

.chart-container {
  height: 300px;
  background-color: var(--chart-background);
  border-radius: var(--radius-md);
  position: relative;
  overflow: hidden;
}

/* Chart loading and error states */
.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: var(--bg-elevated);
  z-index: 10;
}

.chart-loading .loading-spinner {
  width: 1.5rem;
  height: 1.5rem;
  margin-bottom: var(--spacing-sm);
}

.chart-loading p {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.chart-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: var(--bg-elevated);
  z-index: 10;
}

.chart-error p {
  color: var(--color-danger);
  margin-bottom: var(--spacing-md);
  text-align: center;
}

.chart-error button {
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  border-radius: var(--radius-md);
  transition: background-color var(--transition-fast);
}

.chart-error button:hover {
  background-color: var(--color-primary-hover);
}

/* Responsive chart grid */
@media (min-width: 1200px) {
  .chart-grid {
    grid-template-columns: 2fr 1fr;
  }

  .chart-container {
    height: 400px;
  }
}

@media (min-width: 1600px) {
  .chart-container {
    height: 500px;
  }
}

/* Tools */
.tools-container {
  padding: var(--spacing-lg);
  height: 100%;
  overflow-y: auto;
}

/* Dashboard */
.dashboard-container {
  padding: var(--spacing-lg);
  height: 100%;
  overflow-y: auto;
}

.dashboard-container h2 {
  margin-bottom: var(--spacing-lg);
  color: var(--text-primary);
}

#dashboard-content-wrapper {
  height: calc(100% - 3rem);
}

.tools-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
}

.tools-actions {
  display: flex;
  gap: var(--spacing-sm);
}

.tools-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-2xl);
}

.tool-card {
  background-color: var(--bg-elevated);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-md);
}

.tool-header h4 {
  margin: 0;
  color: var(--text-primary);
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
}

.tool-description {
  color: var(--text-secondary);
  margin-bottom: var(--spacing-md);
  font-size: var(--font-size-sm);
  line-height: 1.5;
}

.tool-params h5 {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-size: var(--font-size-md);
  font-weight: var(--font-weight-medium);
}

.param-item {
  margin-bottom: var(--spacing-md);
}

.param-item label {
  display: block;
  margin-bottom: var(--spacing-xs);
  color: var(--text-primary);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
}

.param-input,
.param-select {
  width: 100%;
  padding: var(--spacing-sm);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: var(--font-size-sm);
  transition: all var(--transition-fast);
}

.param-input:focus,
.param-select:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-alpha);
}

.param-select {
  cursor: pointer;
}

.param-description {
  display: block;
  margin-top: var(--spacing-xs);
  color: var(--text-tertiary);
  font-size: var(--font-size-xs);
  line-height: 1.4;
}

.test-tool-btn {
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  border: none;
  border-radius: var(--radius-md);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.test-tool-btn:hover {
  background-color: var(--color-primary-hover);
  transform: translateY(-1px);
}

.test-tool-btn:disabled {
  background-color: var(--bg-tertiary);
  color: var(--text-tertiary);
  cursor: not-allowed;
  transform: none;
}



.execution-history {
  margin-top: var(--spacing-2xl);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--border-primary);
}

.execution-history h3 {
  margin-bottom: var(--spacing-lg);
  color: var(--text-primary);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  background-color: var(--bg-elevated);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  padding: var(--spacing-md);
}

.history-item.success {
  border-left: 4px solid var(--color-success);
}

.history-item.error {
  border-left: 4px solid var(--color-danger);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-sm);
}

.tool-name {
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
}

.timestamp {
  font-size: var(--font-size-xs);
  color: var(--text-tertiary);
}

.history-params,
.history-result {
  margin-bottom: var(--spacing-sm);
  font-size: var(--font-size-sm);
}

.history-result pre {
  background-color: var(--bg-secondary);
  padding: var(--spacing-sm);
  border-radius: var(--radius-sm);
  overflow-x: auto;
  font-size: var(--font-size-xs);
  max-height: 200px;
  overflow-y: auto;
}

.history-empty {
  text-align: center;
  color: var(--text-tertiary);
  font-style: italic;
}

.tools-empty,
.tools-error {
  text-align: center;
  padding: var(--spacing-2xl);
  color: var(--text-secondary);
}

.tools-error {
  color: var(--color-danger);
}

.retry-btn {
  margin-top: var(--spacing-md);
  padding: var(--spacing-sm) var(--spacing-lg);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  border-radius: var(--radius-md);
  transition: background-color var(--transition-fast);
}

.retry-btn:hover {
  background-color: var(--color-primary-hover);
}

/* Tool Results */
.tool-result {
  margin-top: var(--spacing-md);
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  overflow: hidden;
  animation: slideDown 0.3s ease-out;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--bg-tertiary);
  border-bottom: 1px solid var(--border-primary);
}

.result-header h5 {
  margin: 0;
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
}

.result-close {
  width: 1.5rem;
  height: 1.5rem;
  border-radius: var(--radius-sm);
  background-color: transparent;
  color: var(--text-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--font-size-lg);
  transition: all var(--transition-fast);
  cursor: pointer;
}

.result-close:hover {
  background-color: var(--bg-primary);
  color: var(--text-primary);
}

.result-content {
  padding: var(--spacing-md);
}

.result-status {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  margin-bottom: var(--spacing-sm);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
}

.result-status.result-success {
  color: var(--color-success);
}

.result-status.result-error {
  color: var(--color-danger);
}

.result-data {
  background-color: var(--bg-primary);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-sm);
  padding: var(--spacing-sm);
  font-family: var(--font-mono);
  font-size: var(--font-size-xs);
  color: var(--text-primary);
  overflow-x: auto;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
  margin-bottom: var(--spacing-sm);
}

.result-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-sm);
}

.copy-result-btn {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-medium);
  transition: all var(--transition-fast);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.copy-result-btn:hover {
  background-color: var(--color-primary-hover);
  transform: translateY(-1px);
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
    max-height: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0);
    max-height: 500px;
  }
}

/* Analysis */
.analysis-container {
  padding: var(--spacing-lg);
  height: 100%;
  overflow-y: auto;
}

.analysis-controls {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  align-items: center;
  padding: var(--spacing-md);
  background-color: var(--bg-elevated);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-primary);
}

.analysis-panels {
  display: grid;
  grid-template-columns: 1fr;
  gap: var(--spacing-lg);
}

.analysis-panel {
  background-color: var(--bg-elevated);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
}

.analysis-panel h3 {
  margin-bottom: var(--spacing-md);
  color: var(--text-primary);
}

.analysis-chart {
  height: 300px;
  background-color: var(--chart-background);
  border-radius: var(--radius-md);
  position: relative;
  overflow: hidden;
}

.analysis-display {
  min-height: 200px;
}

.market-structure-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.structure-item {
  text-align: center;
  padding: var(--spacing-md);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-md);
}

.structure-item h4 {
  margin: 0 0 var(--spacing-sm) 0;
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.regime {
  font-weight: var(--font-weight-bold);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-sm);
}

.regime.bullish {
  background-color: var(--color-success);
  color: var(--text-inverse);
}

.regime.bearish {
  background-color: var(--color-danger);
  color: var(--text-inverse);
}

.regime.neutral {
  background-color: var(--color-secondary);
  color: var(--text-inverse);
}

.trend {
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
}

.trend.bullish {
  color: var(--color-success);
}

.trend.bearish {
  color: var(--color-danger);
}

.volatility,
.support,
.resistance {
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
  font-family: var(--font-family-mono);
}

.trading-recommendations {
  background-color: var(--bg-secondary);
  padding: var(--spacing-md);
  border-radius: var(--radius-md);
}

.trading-recommendations h4 {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
}

.trading-recommendations ul {
  margin: 0;
  padding-left: var(--spacing-lg);
}

.trading-recommendations li {
  margin-bottom: var(--spacing-xs);
  color: var(--text-secondary);
}

.analysis-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: var(--bg-elevated);
  z-index: 10;
}

.analysis-loading .loading-spinner {
  width: 1.5rem;
  height: 1.5rem;
  margin-bottom: var(--spacing-sm);
}

.analysis-loading p {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.analysis-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: var(--bg-elevated);
  z-index: 10;
}

.analysis-error p {
  color: var(--color-danger);
  margin-bottom: var(--spacing-md);
  text-align: center;
}

.analysis-error button {
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  border-radius: var(--radius-md);
  transition: background-color var(--transition-fast);
}

.analysis-error button:hover {
  background-color: var(--color-primary-hover);
}

/* Responsive analysis grid */
@media (min-width: 1200px) {
  .analysis-panels {
    grid-template-columns: 1fr 1fr;
  }

  .analysis-chart {
    height: 350px;
  }
}

@media (min-width: 1600px) {
  .analysis-panels {
    grid-template-columns: 1fr 1fr 1fr;
  }

  .analysis-chart {
    height: 400px;
  }
}

/* Modal */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--bg-overlay);
  display: none; /* Hidden by default */
  align-items: center;
  justify-content: center;
  z-index: var(--z-modal);
  animation: fadeIn 0.2s ease-out;
}

.modal.active {
  display: flex; /* Show when active */
}

.modal:not(.hidden) {
  display: flex; /* Show when not hidden */
}

.modal.hidden {
  display: none !important; /* Force hide when hidden class is present */
}

.modal-content {
  background-color: var(--bg-elevated);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-xl);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
  animation: slideInRight 0.3s ease-out;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-primary);
}

.modal-header h2 {
  margin: 0;
}

.close-btn {
  width: 2rem;
  height: 2rem;
  border-radius: var(--radius-md);
  background-color: var(--bg-secondary);
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--font-size-lg);
  transition: all var(--transition-fast);
}

.close-btn:hover {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.modal-body {
  padding: var(--spacing-lg);
  max-height: 60vh;
  overflow-y: auto;
}

.modal-footer {
  padding: var(--spacing-lg);
  border-top: 1px solid var(--border-primary);
  display: flex;
  justify-content: flex-end;
}

.save-btn {
  padding: var(--spacing-sm) var(--spacing-lg);
  background-color: var(--color-primary);
  color: var(--text-inverse);
  border-radius: var(--radius-md);
  font-weight: var(--font-weight-medium);
  transition: background-color var(--transition-fast);
}

.save-btn:hover {
  background-color: var(--color-primary-hover);
}

/* Settings */
.settings-section {
  margin-bottom: var(--spacing-xl);
}

.settings-section h3 {
  margin-bottom: var(--spacing-md);
  color: var(--text-primary);
}

.settings-section label {
  display: block;
  margin-bottom: var(--spacing-xs);
  font-weight: var(--font-weight-medium);
  color: var(--text-secondary);
}

.settings-section input {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  background-color: var(--bg-primary);
  color: var(--text-primary);
  margin-bottom: var(--spacing-md);
  transition: border-color var(--transition-fast);
}

.settings-section input:focus {
  border-color: var(--border-focus);
}

.checkbox-label {
  display: flex !important;
  align-items: flex-start;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-md) !important;
  cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
  width: auto !important;
  margin: 0 !important;
  margin-top: 2px;
}

.checkbox-label span {
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
}

.checkbox-label small {
  display: block;
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
  margin-top: var(--spacing-xs);
}

/* Debug Console Styles */
.debug-console {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #1a1a1a;
  color: #e0e0e0;
  border-top: 2px solid #333;
  font-family: 'JetBrains Mono', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  z-index: 1000;
  transition: transform 0.3s ease;
}

.debug-console.hidden {
  transform: translateY(calc(100% - 40px));
}

.debug-console.visible {
  transform: translateY(0);
  height: 40vh;
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #2a2a2a;
  border-bottom: 1px solid #333;
  user-select: none;
}

.debug-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.debug-count {
  color: #888;
  font-size: 11px;
}

.debug-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.debug-filters {
  display: flex;
  gap: 8px;
}

.debug-filters label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  cursor: pointer;
}

.debug-filters input[type="checkbox"] {
  margin: 0;
}

.debug-btn {
  background: #333;
  color: #e0e0e0;
  border: 1px solid #555;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  transition: background 0.2s;
}

.debug-btn:hover {
  background: #444;
}

.debug-toggle {
  background: #0066cc;
  border-color: #0066cc;
}

.debug-toggle:hover {
  background: #0052a3;
}

.debug-content {
  height: calc(100% - 40px);
  overflow: hidden;
}

.debug-logs {
  height: 100%;
  overflow-y: auto;
  padding: 8px;
}

.debug-log-entry {
  margin-bottom: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  border-left: 3px solid #555;
}

.debug-log-entry.debug-log-error {
  background: rgba(220, 53, 69, 0.1);
  border-left-color: #dc3545;
}

.debug-log-entry.debug-log-warn {
  background: rgba(255, 193, 7, 0.1);
  border-left-color: #ffc107;
}

.debug-log-entry.debug-log-info {
  background: rgba(13, 202, 240, 0.1);
  border-left-color: #0dcaf0;
}

.debug-log-entry.debug-log-log {
  background: rgba(108, 117, 125, 0.1);
  border-left-color: #6c757d;
}

.debug-log-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 2px;
}

.debug-time {
  color: #888;
  font-size: 10px;
}

.debug-level {
  color: #fff;
  font-weight: bold;
  font-size: 10px;
  padding: 1px 4px;
  border-radius: 2px;
  background: #555;
}

.debug-log-error .debug-level {
  background: #dc3545;
}

.debug-log-warn .debug-level {
  background: #ffc107;
  color: #000;
}

.debug-log-info .debug-level {
  background: #0dcaf0;
  color: #000;
}

.debug-source {
  color: #888;
  font-size: 10px;
}

.debug-message {
  color: #e0e0e0;
  line-height: 1.4;
  word-break: break-word;
}

.debug-data {
  background: #0a0a0a;
  border: 1px solid #333;
  border-radius: 4px;
  padding: 8px;
  margin-top: 4px;
  font-size: 11px;
  color: #ccc;
  white-space: pre-wrap;
  overflow-x: auto;
}

```

--------------------------------------------------------------------------------
/specs/mcp/mcp-schema.ts:
--------------------------------------------------------------------------------

```typescript
/* JSON-RPC types */
export type JSONRPCMessage =
  | JSONRPCRequest
  | JSONRPCNotification
  | JSONRPCResponse
  | JSONRPCError;

export const LATEST_PROTOCOL_VERSION = "2024-11-05";
export const JSONRPC_VERSION = "2.0";

/**
 * A progress token, used to associate progress notifications with the original request.
 */
export type ProgressToken = string | number;

/**
 * An opaque token used to represent a cursor for pagination.
 */
export type Cursor = string;

export interface Request {
  method: string;
  params?: {
    _meta?: {
      /**
       * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
       */
      progressToken?: ProgressToken;
    };
    [key: string]: unknown;
  };
}

export interface Notification {
  method: string;
  params?: {
    /**
     * This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.
     */
    _meta?: { [key: string]: unknown };
    [key: string]: unknown;
  };
}

export interface Result {
  /**
   * This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.
   */
  _meta?: { [key: string]: unknown };
  [key: string]: unknown;
}

/**
 * A uniquely identifying ID for a request in JSON-RPC.
 */
export type RequestId = string | number;

/**
 * A request that expects a response.
 */
export interface JSONRPCRequest extends Request {
  jsonrpc: typeof JSONRPC_VERSION;
  id: RequestId;
}

/**
 * A notification which does not expect a response.
 */
export interface JSONRPCNotification extends Notification {
  jsonrpc: typeof JSONRPC_VERSION;
}

/**
 * A successful (non-error) response to a request.
 */
export interface JSONRPCResponse {
  jsonrpc: typeof JSONRPC_VERSION;
  id: RequestId;
  result: Result;
}

// Standard JSON-RPC error codes
export const PARSE_ERROR = -32700;
export const INVALID_REQUEST = -32600;
export const METHOD_NOT_FOUND = -32601;
export const INVALID_PARAMS = -32602;
export const INTERNAL_ERROR = -32603;

/**
 * A response to a request that indicates an error occurred.
 */
export interface JSONRPCError {
  jsonrpc: typeof JSONRPC_VERSION;
  id: RequestId;
  error: {
    /**
     * The error type that occurred.
     */
    code: number;
    /**
     * A short description of the error. The message SHOULD be limited to a concise single sentence.
     */
    message: string;
    /**
     * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
     */
    data?: unknown;
  };
}

/* Empty result */
/**
 * A response that indicates success but carries no data.
 */
export type EmptyResult = Result;

/* Cancellation */
/**
 * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
 *
 * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
 *
 * This notification indicates that the result will be unused, so any associated processing SHOULD cease.
 *
 * A client MUST NOT attempt to cancel its `initialize` request.
 */
export interface CancelledNotification extends Notification {
  method: "notifications/cancelled";
  params: {
    /**
     * The ID of the request to cancel.
     *
     * This MUST correspond to the ID of a request previously issued in the same direction.
     */
    requestId: RequestId;

    /**
     * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
     */
    reason?: string;
  };
}

/* Initialization */
/**
 * This request is sent from the client to the server when it first connects, asking it to begin initialization.
 */
export interface InitializeRequest extends Request {
  method: "initialize";
  params: {
    /**
     * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
     */
    protocolVersion: string;
    capabilities: ClientCapabilities;
    clientInfo: Implementation;
  };
}

/**
 * After receiving an initialize request from the client, the server sends this response.
 */
export interface InitializeResult extends Result {
  /**
   * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
   */
  protocolVersion: string;
  capabilities: ServerCapabilities;
  serverInfo: Implementation;
  /**
   * Instructions describing how to use the server and its features.
   *
   * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
   */
  instructions?: string;
}

/**
 * This notification is sent from the client to the server after initialization has finished.
 */
export interface InitializedNotification extends Notification {
  method: "notifications/initialized";
}

/**
 * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
 */
export interface ClientCapabilities {
  /**
   * Experimental, non-standard capabilities that the client supports.
   */
  experimental?: { [key: string]: object };
  /**
   * Present if the client supports listing roots.
   */
  roots?: {
    /**
     * Whether the client supports notifications for changes to the roots list.
     */
    listChanged?: boolean;
  };
  /**
   * Present if the client supports sampling from an LLM.
   */
  sampling?: object;
}

/**
 * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
 */
export interface ServerCapabilities {
  /**
   * Experimental, non-standard capabilities that the server supports.
   */
  experimental?: { [key: string]: object };
  /**
   * Present if the server supports sending log messages to the client.
   */
  logging?: object;
  /**
   * Present if the server offers any prompt templates.
   */
  prompts?: {
    /**
     * Whether this server supports notifications for changes to the prompt list.
     */
    listChanged?: boolean;
  };
  /**
   * Present if the server offers any resources to read.
   */
  resources?: {
    /**
     * Whether this server supports subscribing to resource updates.
     */
    subscribe?: boolean;
    /**
     * Whether this server supports notifications for changes to the resource list.
     */
    listChanged?: boolean;
  };
  /**
   * Present if the server offers any tools to call.
   */
  tools?: {
    /**
     * Whether this server supports notifications for changes to the tool list.
     */
    listChanged?: boolean;
  };
}

/**
 * Describes the name and version of an MCP implementation.
 */
export interface Implementation {
  name: string;
  version: string;
}

/* Ping */
/**
 * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
 */
export interface PingRequest extends Request {
  method: "ping";
}

/* Progress notifications */
/**
 * An out-of-band notification used to inform the receiver of a progress update for a long-running request.
 */
export interface ProgressNotification extends Notification {
  method: "notifications/progress";
  params: {
    /**
     * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
     */
    progressToken: ProgressToken;
    /**
     * The progress thus far. This should increase every time progress is made, even if the total is unknown.
     *
     * @TJS-type number
     */
    progress: number;
    /**
     * Total number of items to process (or total progress required), if known.
     *
     * @TJS-type number
     */
    total?: number;
  };
}

/* Pagination */
export interface PaginatedRequest extends Request {
  params?: {
    /**
     * An opaque token representing the current pagination position.
     * If provided, the server should return results starting after this cursor.
     */
    cursor?: Cursor;
  };
}

export interface PaginatedResult extends Result {
  /**
   * An opaque token representing the pagination position after the last returned result.
   * If present, there may be more results available.
   */
  nextCursor?: Cursor;
}

/* Resources */
/**
 * Sent from the client to request a list of resources the server has.
 */
export interface ListResourcesRequest extends PaginatedRequest {
  method: "resources/list";
}

/**
 * The server's response to a resources/list request from the client.
 */
export interface ListResourcesResult extends PaginatedResult {
  resources: Resource[];
}

/**
 * Sent from the client to request a list of resource templates the server has.
 */
export interface ListResourceTemplatesRequest extends PaginatedRequest {
  method: "resources/templates/list";
}

/**
 * The server's response to a resources/templates/list request from the client.
 */
export interface ListResourceTemplatesResult extends PaginatedResult {
  resourceTemplates: ResourceTemplate[];
}

/**
 * Sent from the client to the server, to read a specific resource URI.
 */
export interface ReadResourceRequest extends Request {
  method: "resources/read";
  params: {
    /**
     * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
     *
     * @format uri
     */
    uri: string;
  };
}

/**
 * The server's response to a resources/read request from the client.
 */
export interface ReadResourceResult extends Result {
  contents: (TextResourceContents | BlobResourceContents)[];
}

/**
 * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.
 */
export interface ResourceListChangedNotification extends Notification {
  method: "notifications/resources/list_changed";
}

/**
 * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.
 */
export interface SubscribeRequest extends Request {
  method: "resources/subscribe";
  params: {
    /**
     * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
     *
     * @format uri
     */
    uri: string;
  };
}

/**
 * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.
 */
export interface UnsubscribeRequest extends Request {
  method: "resources/unsubscribe";
  params: {
    /**
     * The URI of the resource to unsubscribe from.
     *
     * @format uri
     */
    uri: string;
  };
}

/**
 * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.
 */
export interface ResourceUpdatedNotification extends Notification {
  method: "notifications/resources/updated";
  params: {
    /**
     * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
     *
     * @format uri
     */
    uri: string;
  };
}

/**
 * A known resource that the server is capable of reading.
 */
export interface Resource extends Annotated {
  /**
   * The URI of this resource.
   *
   * @format uri
   */
  uri: string;

  /**
   * A human-readable name for this resource.
   *
   * This can be used by clients to populate UI elements.
   */
  name: string;

  /**
   * A description of what this resource represents.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description?: string;

  /**
   * The MIME type of this resource, if known.
   */
  mimeType?: string;
}

/**
 * A template description for resources available on the server.
 */
export interface ResourceTemplate extends Annotated {
  /**
   * A URI template (according to RFC 6570) that can be used to construct resource URIs.
   *
   * @format uri-template
   */
  uriTemplate: string;

  /**
   * A human-readable name for the type of resource this template refers to.
   *
   * This can be used by clients to populate UI elements.
   */
  name: string;

  /**
   * A description of what this template is for.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description?: string;

  /**
   * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
   */
  mimeType?: string;
}

/**
 * The contents of a specific resource or sub-resource.
 */
export interface ResourceContents {
  /**
   * The URI of this resource.
   *
   * @format uri
   */
  uri: string;
  /**
   * The MIME type of this resource, if known.
   */
  mimeType?: string;
}

export interface TextResourceContents extends ResourceContents {
  /**
   * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
   */
  text: string;
}

export interface BlobResourceContents extends ResourceContents {
  /**
   * A base64-encoded string representing the binary data of the item.
   *
   * @format byte
   */
  blob: string;
}

/* Prompts */
/**
 * Sent from the client to request a list of prompts and prompt templates the server has.
 */
export interface ListPromptsRequest extends PaginatedRequest {
  method: "prompts/list";
}

/**
 * The server's response to a prompts/list request from the client.
 */
export interface ListPromptsResult extends PaginatedResult {
  prompts: Prompt[];
}

/**
 * Used by the client to get a prompt provided by the server.
 */
export interface GetPromptRequest extends Request {
  method: "prompts/get";
  params: {
    /**
     * The name of the prompt or prompt template.
     */
    name: string;
    /**
     * Arguments to use for templating the prompt.
     */
    arguments?: { [key: string]: string };
  };
}

/**
 * The server's response to a prompts/get request from the client.
 */
export interface GetPromptResult extends Result {
  /**
   * An optional description for the prompt.
   */
  description?: string;
  messages: PromptMessage[];
}

/**
 * A prompt or prompt template that the server offers.
 */
export interface Prompt {
  /**
   * The name of the prompt or prompt template.
   */
  name: string;
  /**
   * An optional description of what this prompt provides
   */
  description?: string;
  /**
   * A list of arguments to use for templating the prompt.
   */
  arguments?: PromptArgument[];
}

/**
 * Describes an argument that a prompt can accept.
 */
export interface PromptArgument {
  /**
   * The name of the argument.
   */
  name: string;
  /**
   * A human-readable description of the argument.
   */
  description?: string;
  /**
   * Whether this argument must be provided.
   */
  required?: boolean;
}

/**
 * The sender or recipient of messages and data in a conversation.
 */
export type Role = "user" | "assistant";

/**
 * Describes a message returned as part of a prompt.
 *
 * This is similar to `SamplingMessage`, but also supports the embedding of
 * resources from the MCP server.
 */
export interface PromptMessage {
  role: Role;
  content: TextContent | ImageContent | EmbeddedResource;
}

/**
 * The contents of a resource, embedded into a prompt or tool call result.
 *
 * It is up to the client how best to render embedded resources for the benefit
 * of the LLM and/or the user.
 */
export interface EmbeddedResource extends Annotated {
  type: "resource";
  resource: TextResourceContents | BlobResourceContents;
}

/**
 * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.
 */
export interface PromptListChangedNotification extends Notification {
  method: "notifications/prompts/list_changed";
}

/* Tools */
/**
 * Sent from the client to request a list of tools the server has.
 */
export interface ListToolsRequest extends PaginatedRequest {
  method: "tools/list";
}

/**
 * The server's response to a tools/list request from the client.
 */
export interface ListToolsResult extends PaginatedResult {
  tools: Tool[];
}

/**
 * The server's response to a tool call.
 *
 * Any errors that originate from the tool SHOULD be reported inside the result
 * object, with `isError` set to true, _not_ as an MCP protocol-level error
 * response. Otherwise, the LLM would not be able to see that an error occurred
 * and self-correct.
 *
 * However, any errors in _finding_ the tool, an error indicating that the
 * server does not support tool calls, or any other exceptional conditions,
 * should be reported as an MCP error response.
 */
export interface CallToolResult extends Result {
  content: (TextContent | ImageContent | EmbeddedResource)[];

  /**
   * Whether the tool call ended in an error.
   *
   * If not set, this is assumed to be false (the call was successful).
   */
  isError?: boolean;
}

/**
 * Used by the client to invoke a tool provided by the server.
 */
export interface CallToolRequest extends Request {
  method: "tools/call";
  params: {
    name: string;
    arguments?: { [key: string]: unknown };
  };
}

/**
 * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.
 */
export interface ToolListChangedNotification extends Notification {
  method: "notifications/tools/list_changed";
}

/**
 * Definition for a tool the client can call.
 */
export interface Tool {
  /**
   * The name of the tool.
   */
  name: string;
  /**
   * A human-readable description of the tool.
   */
  description?: string;
  /**
   * A JSON Schema object defining the expected parameters for the tool.
   */
  inputSchema: {
    type: "object";
    properties?: { [key: string]: object };
    required?: string[];
  };
}

/* Logging */
/**
 * A request from the client to the server, to enable or adjust logging.
 */
export interface SetLevelRequest extends Request {
  method: "logging/setLevel";
  params: {
    /**
     * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
     */
    level: LoggingLevel;
  };
}

/**
 * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.
 */
export interface LoggingMessageNotification extends Notification {
  method: "notifications/message";
  params: {
    /**
     * The severity of this log message.
     */
    level: LoggingLevel;
    /**
     * An optional name of the logger issuing this message.
     */
    logger?: string;
    /**
     * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
     */
    data: unknown;
  };
}

/**
 * The severity of a log message.
 *
 * These map to syslog message severities, as specified in RFC-5424:
 * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1
 */
export type LoggingLevel =
  | "debug"
  | "info"
  | "notice"
  | "warning"
  | "error"
  | "critical"
  | "alert"
  | "emergency";

/* Sampling */
/**
 * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.
 */
export interface CreateMessageRequest extends Request {
  method: "sampling/createMessage";
  params: {
    messages: SamplingMessage[];
    /**
     * The server's preferences for which model to select. The client MAY ignore these preferences.
     */
    modelPreferences?: ModelPreferences;
    /**
     * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
     */
    systemPrompt?: string;
    /**
     * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.
     */
    includeContext?: "none" | "thisServer" | "allServers";
    /**
     * @TJS-type number
     */
    temperature?: number;
    /**
     * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
     */
    maxTokens: number;
    stopSequences?: string[];
    /**
     * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
     */
    metadata?: object;
  };
}

/**
 * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it.
 */
export interface CreateMessageResult extends Result, SamplingMessage {
  /**
   * The name of the model that generated the message.
   */
  model: string;
  /**
   * The reason why sampling stopped, if known.
   */
  stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string;
}

/**
 * Describes a message issued to or received from an LLM API.
 */
export interface SamplingMessage {
  role: Role;
  content: TextContent | ImageContent;
}

/**
 * Base for objects that include optional annotations for the client. The client can use annotations to inform how objects are used or displayed
 */
export interface Annotated {
  annotations?: {
    /**
     * Describes who the intended customer of this object or data is.
     * 
     * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`).
     */
    audience?: Role[];

    /**
     * Describes how important this data is for operating the server.
     * 
     * A value of 1 means "most important," and indicates that the data is
     * effectively required, while 0 means "least important," and indicates that
     * the data is entirely optional.
     *
     * @TJS-type number
     * @minimum 0
     * @maximum 1
     */
    priority?: number;
  }
}

/**
 * Text provided to or from an LLM.
 */
export interface TextContent extends Annotated {
  type: "text";
  /**
   * The text content of the message.
   */
  text: string;
}

/**
 * An image provided to or from an LLM.
 */
export interface ImageContent extends Annotated {
  type: "image";
  /**
   * The base64-encoded image data.
   *
   * @format byte
   */
  data: string;
  /**
   * The MIME type of the image. Different providers may support different image types.
   */
  mimeType: string;
}

/**
 * The server's preferences for model selection, requested of the client during sampling.
 *
 * Because LLMs can vary along multiple dimensions, choosing the "best" model is
 * rarely straightforward.  Different models excel in different areas—some are
 * faster but less capable, others are more capable but more expensive, and so
 * on. This interface allows servers to express their priorities across multiple
 * dimensions to help clients make an appropriate selection for their use case.
 *
 * These preferences are always advisory. The client MAY ignore them. It is also
 * up to the client to decide how to interpret these preferences and how to
 * balance them against other considerations.
 */
export interface ModelPreferences {
  /**
   * Optional hints to use for model selection.
   *
   * If multiple hints are specified, the client MUST evaluate them in order
   * (such that the first match is taken).
   *
   * The client SHOULD prioritize these hints over the numeric priorities, but
   * MAY still use the priorities to select from ambiguous matches.
   */
  hints?: ModelHint[];

  /**
   * How much to prioritize cost when selecting a model. A value of 0 means cost
   * is not important, while a value of 1 means cost is the most important
   * factor.
   *
   * @TJS-type number
   * @minimum 0
   * @maximum 1
   */
  costPriority?: number;

  /**
   * How much to prioritize sampling speed (latency) when selecting a model. A
   * value of 0 means speed is not important, while a value of 1 means speed is
   * the most important factor.
   *
   * @TJS-type number
   * @minimum 0
   * @maximum 1
   */
  speedPriority?: number;

  /**
   * How much to prioritize intelligence and capabilities when selecting a
   * model. A value of 0 means intelligence is not important, while a value of 1
   * means intelligence is the most important factor.
   *
   * @TJS-type number
   * @minimum 0
   * @maximum 1
   */
  intelligencePriority?: number;
}

/**
 * Hints to use for model selection.
 *
 * Keys not declared here are currently left unspecified by the spec and are up
 * to the client to interpret.
 */
export interface ModelHint {
  /**
   * A hint for a model name.
   *
   * The client SHOULD treat this as a substring of a model name; for example:
   *  - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`
   *  - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.
   *  - `claude` should match any Claude model
   *
   * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example:
   *  - `gemini-1.5-flash` could match `claude-3-haiku-20240307`
   */
  name?: string;
}

/* Autocomplete */
/**
 * A request from the client to the server, to ask for completion options.
 */
export interface CompleteRequest extends Request {
  method: "completion/complete";
  params: {
    ref: PromptReference | ResourceReference;
    /**
     * The argument's information
     */
    argument: {
      /**
       * The name of the argument
       */
      name: string;
      /**
       * The value of the argument to use for completion matching.
       */
      value: string;
    };
  };
}

/**
 * The server's response to a completion/complete request
 */
export interface CompleteResult extends Result {
  completion: {
    /**
     * An array of completion values. Must not exceed 100 items.
     */
    values: string[];
    /**
     * The total number of completion options available. This can exceed the number of values actually sent in the response.
     */
    total?: number;
    /**
     * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
     */
    hasMore?: boolean;
  };
}

/**
 * A reference to a resource or resource template definition.
 */
export interface ResourceReference {
  type: "ref/resource";
  /**
   * The URI or URI template of the resource.
   *
   * @format uri-template
   */
  uri: string;
}

/**
 * Identifies a prompt.
 */
export interface PromptReference {
  type: "ref/prompt";
  /**
   * The name of the prompt or prompt template
   */
  name: string;
}

/* Roots */
/**
 * Sent from the server to request a list of root URIs from the client. Roots allow
 * servers to ask for specific directories or files to operate on. A common example
 * for roots is providing a set of repositories or directories a server should operate
 * on.
 *
 * This request is typically used when the server needs to understand the file system
 * structure or access specific locations that the client has permission to read from.
 */
export interface ListRootsRequest extends Request {
  method: "roots/list";
}

/**
 * The client's response to a roots/list request from the server.
 * This result contains an array of Root objects, each representing a root directory
 * or file that the server can operate on.
 */
export interface ListRootsResult extends Result {
  roots: Root[];
}

/**
 * Represents a root directory or file that the server can operate on.
 */
export interface Root {
  /**
   * The URI identifying the root. This *must* start with file:// for now.
   * This restriction may be relaxed in future versions of the protocol to allow
   * other URI schemes.
   *
   * @format uri
   */
  uri: string;
  /**
   * An optional name for the root. This can be used to provide a human-readable
   * identifier for the root, which may be useful for display purposes or for
   * referencing the root in other parts of the application.
   */
  name?: string;
}

/**
 * A notification from the client to the server, informing it that the list of roots has changed.
 * This notification should be sent whenever the client adds, removes, or modifies any root.
 * The server should then request an updated list of roots using the ListRootsRequest.
 */
export interface RootsListChangedNotification extends Notification {
  method: "notifications/roots/list_changed";
}

/* Client messages */
export type ClientRequest =
  | PingRequest
  | InitializeRequest
  | CompleteRequest
  | SetLevelRequest
  | GetPromptRequest
  | ListPromptsRequest
  | ListResourcesRequest
  | ReadResourceRequest
  | SubscribeRequest
  | UnsubscribeRequest
  | CallToolRequest
  | ListToolsRequest;

export type ClientNotification =
  | CancelledNotification
  | ProgressNotification
  | InitializedNotification
  | RootsListChangedNotification;

export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult;

/* Server messages */
export type ServerRequest =
  | PingRequest
  | CreateMessageRequest
  | ListRootsRequest;

export type ServerNotification =
  | CancelledNotification
  | ProgressNotification
  | LoggingMessageNotification
  | ResourceUpdatedNotification
  | ResourceListChangedNotification
  | ToolListChangedNotification
  | PromptListChangedNotification;

export type ServerResult =
  | EmptyResult
  | InitializeResult
  | CompleteResult
  | GetPromptResult
  | ListPromptsResult
  | ListResourcesResult
  | ReadResourceResult
  | CallToolResult
  | ListToolsResult;

```

--------------------------------------------------------------------------------
/webui/src/components/ChatApp.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Main chat application component
 */

import type { ChatUIMessage, ChatState, ChatMessage } from '@/types/ai';
import { aiClient, generateSystemPrompt } from '@/services/aiClient';
import { multiStepAgent } from '@/services/multiStepAgent';
import { agentConfigService } from '@/services/agentConfig';
import { mcpClient } from '@/services/mcpClient';
import { configService } from '@/services/configService';
import { citationProcessor } from '@/services/citationProcessor';
import { citationStore } from '@/services/citationStore';
import type { WorkflowEvent } from '@/types/workflow';
import { marked } from 'marked';
import { MessageRenderer, type MessageData } from './chat/MessageRenderer';

export class ChatApp {
  private state: ChatState = {
    messages: [],
    isLoading: false,
    isConnected: false,
    currentStreamingId: undefined,
  };

  private chatMessages: HTMLElement;
  private chatInput: HTMLTextAreaElement;
  private sendBtn: HTMLButtonElement;
  private connectionStatus: HTMLElement;
  private typingIndicator: HTMLElement;
  private fullConversationHistory: ChatMessage[] = []; // Track complete conversation including tool calls
  private workflowEventsContainer: HTMLElement | null = null;
  private useAgent: boolean = false; // Toggle between agent and legacy client - temporarily disabled for testing
  private lastCitationAttachTime: number = 0;
  private citationAttachThrottle: number = 300; // Throttle to 300ms
  private messageRenderer: MessageRenderer;
  private retryCount: number = 0;
  private maxRetries: number = 2; // Maximum number of automatic retries
  private processingMessage: HTMLElement | null = null;

  constructor() {
    // Configure marked for safe HTML rendering
    marked.setOptions({
      breaks: true, // Convert line breaks to <br>
      gfm: true, // GitHub Flavored Markdown
    });
    // Get DOM elements
    this.chatMessages = document.getElementById('chat-messages')!;
    this.chatInput = document.getElementById('chat-input') as HTMLTextAreaElement;
    this.sendBtn = document.getElementById('send-btn') as HTMLButtonElement;
    this.connectionStatus = document.getElementById('connection-status')!;
    this.typingIndicator = document.getElementById('typing-indicator')!;
    this.workflowEventsContainer = document.getElementById('workflow-events');

    // Initialize the enhanced message renderer
    this.messageRenderer = new MessageRenderer(this.chatMessages);

    this.initialize();
  }

  private initialize(): void {
    this.setupEventListeners();
    this.updateConnectionStatus();
    this.loadWelcomeMessage();
  }

  private setupEventListeners(): void {
    // Send button click
    this.sendBtn.addEventListener('click', () => {
      this.sendMessage();
    });

    // Enter key to send (Shift+Enter for new line)
    this.chatInput.addEventListener('keydown', (event) => {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        this.sendMessage();
      }
    });

    // Auto-resize textarea
    this.chatInput.addEventListener('input', () => {
      this.autoResizeTextarea();
      this.updateSendButton();
    });

    // Update send button state on input
    this.chatInput.addEventListener('input', () => {
      this.updateSendButton();
    });

    // Listen for configuration changes
    configService.subscribe(() => {
      this.updateConnectionStatus();
    });
  }

  private autoResizeTextarea(): void {
    this.chatInput.style.height = 'auto';
    this.chatInput.style.height = Math.min(this.chatInput.scrollHeight, 128) + 'px';
  }

  private updateSendButton(): void {
    const hasText = this.chatInput.value.trim().length > 0;
    this.sendBtn.disabled = !hasText || this.state.isLoading;
  }

  private async updateConnectionStatus(): Promise<void> {
    try {
      const [aiConnected, mcpConnected, agentConnected] = await Promise.all([
        aiClient.isConnected(),
        mcpClient.isConnected(),
        multiStepAgent.isConnected(),
      ]);

      if (this.useAgent) {
        this.state.isConnected = agentConnected;

        if (agentConnected) {
          this.connectionStatus.innerHTML = '🤖 Agent Ready';
          this.connectionStatus.className = 'connection-status text-success';
        } else {
          this.connectionStatus.innerHTML = '🔴 Agent Offline';
          this.connectionStatus.className = 'connection-status text-danger';
        }
      } else {
        // Legacy mode
        this.state.isConnected = aiConnected && mcpConnected;

        if (this.state.isConnected) {
          this.connectionStatus.innerHTML = '🟢 Connected';
          this.connectionStatus.className = 'connection-status text-success';
        } else if (aiConnected && !mcpConnected) {
          this.connectionStatus.innerHTML = '🟡 AI Only';
          this.connectionStatus.className = 'connection-status text-warning';
        } else if (!aiConnected && mcpConnected) {
          this.connectionStatus.innerHTML = '🟡 MCP Only';
          this.connectionStatus.className = 'connection-status text-warning';
        } else {
          this.connectionStatus.innerHTML = '🔴 Disconnected';
          this.connectionStatus.className = 'connection-status text-danger';
        }
      }
    } catch (error) {
      console.error('Failed to check connection status:', error);
      this.connectionStatus.innerHTML = '🔴 Error';
      this.connectionStatus.className = 'connection-status text-danger';
    }
  }

  private loadWelcomeMessage(): void {
    // Clear any existing messages
    this.state.messages = [];

    // The welcome message is already in the HTML, so we don't need to add it programmatically
    // Just ensure the chat messages container is ready for new messages
  }

  /**
   * Show processing indicator
   */
  private showProcessingIndicator(isRetry: boolean = false): void {
    this.hideProcessingIndicator(); // Remove any existing indicator

    this.processingMessage = document.createElement('div');
    this.processingMessage.className = 'processing-message';
    this.processingMessage.innerHTML = `
      <div class="message-header">
        <div class="message-avatar">AI</div>
        <span class="message-name">Assistant</span>
        <span class="message-time">${new Date().toLocaleTimeString()}</span>
      </div>
      <div class="message-content processing">
        <div class="processing-indicator">
          <div class="processing-dots">
            <span>•</span>
            <span>•</span>
            <span>•</span>
          </div>
          <span class="processing-text">
            ${isRetry ? `🔄 Retrying... (attempt ${this.retryCount + 1}/${this.maxRetries + 1})` : '🤔 Processing your request...'}
          </span>
        </div>
      </div>
    `;

    this.chatMessages.appendChild(this.processingMessage);
    this.scrollToBottom();
  }

  /**
   * Hide processing indicator
   */
  private hideProcessingIndicator(): void {
    if (this.processingMessage) {
      this.processingMessage.remove();
      this.processingMessage = null;
    }
  }

  /**
   * Check if AI response is empty or invalid
   */
  private isEmptyResponse(content: string): boolean {
    if (!content) return true;

    const trimmed = content.trim();
    if (!trimmed) return true;

    // Remove the overly strict length check - valid responses can be short
    // Only check for truly empty or nonsensical patterns
    const emptyPatterns = [
      /^\.+$/,        // Only dots
      /^-+$/,         // Only dashes
      /^\*+$/,        // Only asterisks
      /^_+$/,         // Only underscores
      /^\?+$/,        // Only question marks
      /^!+$/          // Only exclamation marks
    ];

    return emptyPatterns.some(pattern => pattern.test(trimmed));
  }

  public async sendMessage(content?: string): Promise<void> {
    const messageContent = content || this.chatInput.value.trim();

    if (!messageContent || this.state.isLoading) {
      return;
    }

    // Reset retry count for new messages
    if (!content) {
      this.retryCount = 0;
    }

    // Clear input if using the input field
    if (!content) {
      this.chatInput.value = '';
      this.autoResizeTextarea();
      this.updateSendButton();
    }

    // Create user message (only for new messages, not retries)
    if (this.retryCount === 0) {
      const userMessage: ChatUIMessage = {
        id: this.generateMessageId(),
        role: 'user',
        content: messageContent,
        timestamp: Date.now(),
      };
      this.addMessage(userMessage);
    }

    // Set loading state
    this.state.isLoading = true;
    this.updateSendButton();
    this.showTypingIndicator();
    this.showProcessingIndicator(this.retryCount > 0);

    try {
      console.log('💬 Starting chat request...');

      if (this.useAgent) {
        // Use multi-step agent with streaming
        await this.handleAgentChat(messageContent);
      } else {
        // Use legacy AI client
        await this.handleLegacyChat(messageContent);
      }

      // Reset retry count on success
      this.retryCount = 0;

    } catch (error) {
      console.error('❌ Failed to send message:', error);
      console.error('❌ Error details:', {
        name: error instanceof Error ? error.name : 'Unknown',
        message: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
        details: (error as any)?.details
      });

      // Check if we should retry
      if (this.retryCount < this.maxRetries) {
        this.retryCount++;
        console.log(`🔄 Retrying... attempt ${this.retryCount}/${this.maxRetries}`);

        // Hide current processing indicator and show retry indicator
        this.hideProcessingIndicator();

        // Wait a moment before retrying
        setTimeout(() => {
          this.sendMessage(messageContent);
        }, 1000);
        return;
      }

      // Max retries reached, show error
      const errorMessage: ChatUIMessage = {
        id: this.generateMessageId(),
        role: 'assistant',
        content: `Sorry, I encountered an error after ${this.maxRetries + 1} attempts: ${error instanceof Error ? error.message : 'Unknown error'}`,
        timestamp: Date.now(),
        error: error instanceof Error ? error.message : 'Unknown error',
      };

      this.addMessage(errorMessage);
      this.retryCount = 0; // Reset for next message
    } finally {
      this.state.isLoading = false;
      this.state.currentStreamingId = undefined;
      this.updateSendButton();
      this.hideTypingIndicator();
      this.hideProcessingIndicator();
    }
  }

  /**
   * Handle chat using multi-step agent with streaming and workflow events
   */
  private async handleAgentChat(messageContent: string): Promise<void> {
    console.log('🤖 Using multi-step agent...');

    // Create assistant message for streaming
    const assistantMessage: ChatUIMessage = {
      id: this.generateMessageId(),
      role: 'assistant',
      content: '',
      timestamp: Date.now(),
      isStreaming: true,
    };
    this.addMessage(assistantMessage);

    // Get the message element for updating
    const messageElement = this.chatMessages.querySelector(`[data-message-id="${assistantMessage.id}"]`);
    const contentElement = messageElement?.querySelector('[data-content]') as HTMLElement;

    if (!contentElement) {
      throw new Error('Could not find message content element');
    }

    try {
      // Stream chat with the agent
      await multiStepAgent.streamChat(
        messageContent,
        (chunk: string) => {
          // Update the streaming message content
          assistantMessage.content += chunk;
          contentElement.innerHTML = this.formatMessageContent(assistantMessage.content || '') + '<span class="cursor">|</span>';

          // Only attach citation listeners if the content contains citation patterns
          // This avoids excessive listener attachment during streaming
          if (assistantMessage.content && assistantMessage.content.includes('[REF') && messageElement) {
            this.addCitationEventListenersThrottled(messageElement as HTMLElement);
          }

          this.scrollToBottom();
        },
        (event: WorkflowEvent) => {
          // Handle workflow events
          this.handleWorkflowEvent(event);
        }
      );

      // Check if response is empty
      if (this.isEmptyResponse(assistantMessage.content || '')) {
        throw new Error('Received empty response from agent');
      }

      // Remove streaming cursor and finalize
      assistantMessage.isStreaming = false;
      contentElement.innerHTML = this.formatMessageContent(assistantMessage.content || '');

      // Final citation event listener attachment - always do this at the end
      if (messageElement) {
        this.addCitationEventListeners(messageElement as HTMLElement);
      }

    } catch (error) {
      // Update message with error
      assistantMessage.content = `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`;
      assistantMessage.error = error instanceof Error ? error.message : 'Unknown error';
      assistantMessage.isStreaming = false;

      contentElement.innerHTML = this.formatMessageContent(assistantMessage.content);
      throw error;
    }
  }

  /**
   * Handle chat using legacy AI client (fallback)
   */
  private async handleLegacyChat(messageContent: string): Promise<void> {
    console.log('🔄 Using legacy AI client...');

    // Use the full conversation history if available, otherwise prepare from UI messages
    let aiMessages: ChatMessage[];

    if (this.fullConversationHistory.length > 0) {
      // Use the complete conversation history (includes tool calls and responses)
      aiMessages = [...this.fullConversationHistory];
      // Add the new user message
      aiMessages.push({
        role: 'user',
        content: messageContent,
      });
    } else {
      // First message - prepare from UI messages
      const messages = this.state.messages.map(msg => ({
        role: msg.role,
        content: msg.content,
      }));

      // Add dynamic system prompt with current timestamp
      const systemPrompt = generateSystemPrompt();
      aiMessages = [
        { role: 'system' as const, content: systemPrompt },
        ...messages,
      ];
    }

    console.log('📝 Prepared messages:', aiMessages);

    // Use tool calling
    console.log('🔄 Calling aiClient.chatWithTools...');
    const conversationMessages = await aiClient.chatWithTools(aiMessages);
    console.log('✅ Got conversation messages:', conversationMessages.length);

    // Update the full conversation history with the complete conversation
    this.fullConversationHistory = conversationMessages;
    console.log('📝 Updated full conversation history:', this.fullConversationHistory.length, 'messages');

    // Find new assistant messages to add to the UI
    const assistantMessages = conversationMessages.filter(msg => msg.role === 'assistant');
    const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];

    if (lastAssistantMessage && lastAssistantMessage.content) {
      // Check if response is empty
      if (this.isEmptyResponse(lastAssistantMessage.content)) {
        throw new Error('Received empty response from AI');
      }

      // Add the final assistant response to the UI
      const assistantMessage: ChatUIMessage = {
        id: this.generateMessageId(),
        role: 'assistant',
        content: lastAssistantMessage.content,
        timestamp: Date.now(),
        tool_calls: lastAssistantMessage.tool_calls,
      };
      this.addMessage(assistantMessage);
    } else {
      // No content in the final response
      console.warn('⚠️ No content in final assistant message:', lastAssistantMessage);
      throw new Error('Received empty response from AI');
    }
  }

  /**
   * Handle workflow events from the agent
   */
  private handleWorkflowEvent(event: WorkflowEvent): void {
    if (!agentConfigService.getConfig().showWorkflowSteps) {
      return;
    }

    console.log('🔄 Workflow event:', event);

    // Display workflow events in the UI if container exists
    if (this.workflowEventsContainer) {
      const eventElement = document.createElement('div');
      eventElement.className = 'workflow-event';
      eventElement.innerHTML = `
        <div class="event-type">${event.type}</div>
        <div class="event-time">${new Date(event.timestamp).toLocaleTimeString()}</div>
        <div class="event-data">${JSON.stringify(event.data, null, 2)}</div>
      `;
      this.workflowEventsContainer.appendChild(eventElement);
      this.workflowEventsContainer.scrollTop = this.workflowEventsContainer.scrollHeight;
    }
  }

  private addMessage(message: ChatUIMessage): void {
    this.state.messages.push(message);
    this.renderMessage(message);
    this.scrollToBottom();
  }

  private renderMessage(message: ChatUIMessage): void {
    console.log('[ChatApp] renderMessage called with message:', JSON.parse(JSON.stringify(message))); // DEV_PLAN debug

    // Remove welcome message if this is the first real message
    if (this.state.messages.length === 1) {
      const welcomeMessage = this.chatMessages.querySelector('.welcome-message');
      if (welcomeMessage) {
        welcomeMessage.remove();
      }
    }

    // Check if this message has tool calls or citations and should use enhanced rendering
    const hasToolCalls = message.tool_calls && message.tool_calls.length > 0;
    const hasCitations = message.content && /\[REF\d+\]/.test(message.content);
    const shouldUseEnhancedRenderer = (hasToolCalls || hasCitations) && !message.isStreaming;

    console.log('[ChatApp] Rendering decision:', {
      hasToolCalls,
      hasCitations,
      isStreaming: message.isStreaming,
      shouldUseEnhancedRenderer
    }); // DEV_PLAN debug

    if (shouldUseEnhancedRenderer) {
      console.log('[ChatApp] Using enhanced renderer'); // DEV_PLAN debug
      // Use enhanced MessageRenderer for messages with tool results
      this.renderEnhancedMessage(message);
    } else {
      console.log('[ChatApp] Using simple renderer'); // DEV_PLAN debug
      // Use existing rendering for streaming messages and simple text
      this.renderSimpleMessage(message);
    }
  }

  /**
   * Render message using the enhanced MessageRenderer (for tool results)
   */
  private renderEnhancedMessage(message: ChatUIMessage): void {
    console.log('[ChatApp] renderEnhancedMessage called'); // DEV_PLAN debug
    // Extract tool result from citation data if available
    const toolResult = this.extractToolResultFromCitations(message);
    console.log('[ChatApp] Extracted tool result:', toolResult); // DEV_PLAN debug

    // Convert ChatUIMessage to MessageData format
    const messageData: MessageData = {
      content: message.content || '',
      role: message.role,
      timestamp: message.timestamp,
      toolCall: toolResult ? {
        name: toolResult.toolName,
        result: toolResult.data
      } : undefined
    };
    console.log('[ChatApp] Prepared MessageData for MessageRenderer:', JSON.parse(JSON.stringify(messageData))); // DEV_PLAN debug

    // Create a container for this message
    const messageContainer = document.createElement('div');
    messageContainer.className = 'enhanced-message-container';
    messageContainer.dataset.messageId = message.id;

    // Use MessageRenderer to render the enhanced message
    console.log('[ChatApp] Calling messageRenderer.renderMessage...'); // DEV_PLAN debug
    const renderedMessage = this.messageRenderer.renderMessage(messageData);
    messageContainer.appendChild(renderedMessage);

    this.chatMessages.appendChild(messageContainer);

    // Add citation event listeners if this is an assistant message
    if (message.role === 'assistant') {
      setTimeout(() => {
        this.addCitationEventListeners(messageContainer);
      }, 0);
    }
  }

  /**
   * Render message using the existing simple approach (for streaming and simple messages)
   */
  private renderSimpleMessage(message: ChatUIMessage): void {
    const messageElement = document.createElement('div');
    messageElement.className = 'chat-message';
    messageElement.dataset.messageId = message.id;

    const avatar = message.role === 'user' ? 'U' : 'AI';
    const avatarClass = message.role === 'user' ? 'user' : '';
    const contentClass = message.role === 'user' ? 'user' : '';
    const name = message.role === 'user' ? 'You' : 'Assistant';
    const time = new Date(message.timestamp).toLocaleTimeString();

    messageElement.innerHTML = `
      <div class="message-header">
        <div class="message-avatar ${avatarClass}">${avatar}</div>
        <span class="message-name">${name}</span>
        <span class="message-time">${time}</span>
      </div>
      <div class="message-content ${contentClass}" data-content>
        ${this.formatMessageContent(message.content || '')}
        ${message.isStreaming ? '<span class="cursor">|</span>' : ''}
      </div>
    `;

    this.chatMessages.appendChild(messageElement);

    // Add citation event listeners if this is an assistant message
    if (message.role === 'assistant') {
      setTimeout(() => {
        this.addCitationEventListeners(messageElement);
      }, 0);
    }
  }

  /**
   * Extract tool result from citation data
   */
  private extractToolResultFromCitations(message: ChatUIMessage): { toolName: string; data: any } | null {
    console.log('[ChatApp] extractToolResultFromCitations called with message content:', message.content); // DEV_PLAN 1.22 debug
    const content = message.content || '';

    // Look for citation references in the message content
    const citationMatches = content.match(/\[REF\d+\]/g);
    console.log('[ChatApp] Found citation matches:', citationMatches); // DEV_PLAN 1.22 debug
    if (!citationMatches) {
      return null;
    }

    // Get the first citation reference
    const firstCitation = citationMatches[0];
    console.log('[ChatApp] Processing first citation:', firstCitation); // DEV_PLAN 1.22 debug

    // Remove brackets from citation reference for store lookup
    const referenceId = firstCitation.replace(/[\[\]]/g, ''); // Remove [ and ]
    console.log('[ChatApp] Looking up citation with ID:', referenceId); // DEV_PLAN 1.22 debug

    // Access the citation store to get the stored data
    try {
      const citationData = citationStore.getCitation(referenceId);
      console.log('[ChatApp] Retrieved citation data from store (type:', typeof citationData, '):', citationData); // DEV_PLAN 1.22 debug
      if (citationData && citationData.rawData) {
        const result = {
          toolName: citationData.toolName || 'unknown',
          data: citationData.rawData
        };
        console.log('[ChatApp] Returning tool result:', JSON.parse(JSON.stringify(result))); // DEV_PLAN 1.22 debug
        return result;
      } else {
        console.log('[ChatApp] No rawData found in citation data. Available keys:', citationData ? Object.keys(citationData) : 'null'); // DEV_PLAN 1.22 debug
      }
    } catch (error) {
      console.warn('[ChatApp] Failed to extract citation data:', error); // DEV_PLAN 1.22 debug
      console.warn('[ChatApp] Citation data that caused error:', citationStore.getCitation(firstCitation)); // DEV_PLAN 1.22 debug
    }

    return null;
  }

  private formatMessageContent(content: string): string {
    // Process citations first
    const processedMessage = citationProcessor.processMessage(content);

    try {
      // Use marked to render markdown to HTML (synchronous)
      const htmlContent = marked.parse(processedMessage.processedContent, { async: false }) as string;

      // Basic sanitization - remove potentially dangerous elements
      return this.sanitizeHtml(htmlContent);
    } catch (error) {
      console.warn('Failed to parse markdown, falling back to basic formatting:', error);

      // Fallback to basic formatting if marked fails
      return processedMessage.processedContent
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code>$1</code>')
        .replace(/\n/g, '<br>');
    }
  }

  /**
   * Basic HTML sanitization to remove potentially dangerous elements
   */
  private sanitizeHtml(html: string): string {
    // Remove script tags and event handlers
    return html
      .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
      .replace(/on\w+="[^"]*"/gi, '')
      .replace(/on\w+='[^']*'/gi, '')
      .replace(/javascript:/gi, '');
  }

  /**
   * Throttled version of addCitationEventListeners to reduce spam during streaming
   */
  private addCitationEventListenersThrottled(messageElement: HTMLElement): void {
    const now = Date.now();
    if (now - this.lastCitationAttachTime < this.citationAttachThrottle) {
      return; // Skip if called too recently
    }
    this.lastCitationAttachTime = now;
    this.addCitationEventListeners(messageElement);
  }

  /**
   * Add event listeners for citation interactions
   */
  private addCitationEventListeners(messageElement: HTMLElement): void {
    const citationRefs = messageElement.querySelectorAll('.citation-ref');

    // Reduce logging spam - only log once when citations are found
    if (citationRefs.length > 0) {
      console.log(`🎯 Attaching listeners to ${citationRefs.length} citation references`);
    }

    citationRefs.forEach((citationRef) => {
      const element = citationRef as HTMLElement;
      const referenceId = element.dataset.referenceId;

      if (!referenceId) {
        return;
      }

      // Remove default browser tooltip to avoid double tooltips
      element.removeAttribute('title');

      // Add click handler
      element.addEventListener('click', () => {
        console.log(`🖱️ Citation clicked: ${referenceId}`);
        this.handleCitationClick(referenceId);
      });

      // Add hover handlers for tooltip
      let tooltipTimeout: NodeJS.Timeout;
      let tooltip: HTMLElement | null = null;

      element.addEventListener('mouseenter', () => {
        tooltipTimeout = setTimeout(() => {
          tooltip = this.showCitationTooltip(element, referenceId);
        }, 500); // Show tooltip after 500ms hover
      });

      element.addEventListener('mouseleave', () => {
        clearTimeout(tooltipTimeout);
        if (tooltip) {
          tooltip.remove();
          tooltip = null;
        }
      });

      // Add keyboard support
      element.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          this.handleCitationClick(referenceId);
        }
      });
    });
  }

  /**
   * Handle citation click to show full data
   */
  private handleCitationClick(referenceId: string): void {
    console.log(`🔍 Handling citation click for: ${referenceId}`);
    const tooltipData = citationProcessor.getCitationTooltipData(referenceId);

    console.log(`📊 Citation tooltip data:`, tooltipData);

    if (!tooltipData) {
      console.warn(`❌ No citation data found for ${referenceId}`);
      return;
    }

    // Create and show modal with full citation data
    this.showCitationModal(tooltipData);
  }

  /**
   * Show citation tooltip on hover
   */
  private showCitationTooltip(element: HTMLElement, referenceId: string): HTMLElement | null {
    const tooltipData = citationProcessor.getCitationTooltipData(referenceId);

    if (!tooltipData) {
      return null;
    }

    const tooltip = document.createElement('div');
    tooltip.className = 'citation-tooltip-container';
    tooltip.innerHTML = citationProcessor.createTooltipContent(tooltipData);

    // Add to DOM first to get dimensions
    document.body.appendChild(tooltip);

    // Position tooltip relative to the citation element
    const rect = element.getBoundingClientRect();
    const tooltipRect = tooltip.getBoundingClientRect();

    // Calculate position (prefer below, but above if no space)
    let top = rect.bottom + window.scrollY + 8;
    let left = rect.left + window.scrollX;

    // Adjust if tooltip would go off screen
    if (left + tooltipRect.width > window.innerWidth) {
      left = window.innerWidth - tooltipRect.width - 10;
    }

    if (top + tooltipRect.height > window.innerHeight + window.scrollY) {
      top = rect.top + window.scrollY - tooltipRect.height - 8;
    }

    tooltip.style.position = 'absolute';
    tooltip.style.top = `${top}px`;
    tooltip.style.left = `${left}px`;
    tooltip.style.zIndex = '1000';

    return tooltip;
  }

  /**
   * Show citation modal with full data
   */
  private showCitationModal(tooltipData: any): void {
    // Create modal overlay
    const overlay = document.createElement('div');
    overlay.className = 'citation-modal-overlay';

    const modal = document.createElement('div');
    modal.className = 'citation-modal';

    modal.innerHTML = `
      <div class="citation-modal-header">
        <h3>Citation Data: ${tooltipData.referenceId}</h3>
        <button class="citation-modal-close" aria-label="Close">&times;</button>
      </div>
      <div class="citation-modal-content">
        <div class="citation-info">
          <p><strong>Tool:</strong> ${tooltipData.toolName}</p>
          <p><strong>Timestamp:</strong> ${citationProcessor.formatTimestamp(tooltipData.timestamp)}</p>
          ${tooltipData.endpoint ? `<p><strong>Endpoint:</strong> ${tooltipData.endpoint}</p>` : ''}
        </div>
        <div class="citation-raw-data">
          <h4>Raw Data:</h4>
          <pre><code>${JSON.stringify(tooltipData, null, 2)}</code></pre>
        </div>
      </div>
    `;

    overlay.appendChild(modal);
    document.body.appendChild(overlay);

    // Add event listeners
    const closeBtn = modal.querySelector('.citation-modal-close');
    const closeModal = () => overlay.remove();

    closeBtn?.addEventListener('click', closeModal);
    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) closeModal();
    });

    // Close on Escape key
    const handleKeydown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        closeModal();
        document.removeEventListener('keydown', handleKeydown);
      }
    };
    document.addEventListener('keydown', handleKeydown);
  }

  private showTypingIndicator(): void {
    this.typingIndicator.classList.remove('hidden');
  }

  private hideTypingIndicator(): void {
    this.typingIndicator.classList.add('hidden');
  }

  private scrollToBottom(): void {
    this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
  }

  private generateMessageId(): string {
    return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  // Public methods for external use
  public getMessages(): ChatUIMessage[] {
    return [...this.state.messages];
  }

  public clearMessages(): void {
    this.state.messages = [];
    this.fullConversationHistory = [];
    this.retryCount = 0;
    this.chatMessages.innerHTML = '';
    this.loadWelcomeMessage();
  }

  public isLoading(): boolean {
    return this.state.isLoading;
  }

  public toggleAgentMode(useAgent: boolean): void {
    this.useAgent = useAgent;
    this.updateConnectionStatus();
    console.log(`🔄 Switched to ${useAgent ? 'agent' : 'legacy'} mode`);
  }

  public isUsingAgent(): boolean {
    return this.useAgent;
  }

  public isAgentModeEnabled(): boolean {
    return this.useAgent;
  }

  public getAgentState() {
    return multiStepAgent.getState();
  }
}

```

--------------------------------------------------------------------------------
/specs/mcp/mcp-schema.json:
--------------------------------------------------------------------------------

```json
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "definitions": {
        "Annotated": {
            "description": "Base for objects that include optional annotations for the client. The client can use annotations to inform how objects are used or displayed",
            "properties": {
                "annotations": {
                    "properties": {
                        "audience": {
                            "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).",
                            "items": {
                                "$ref": "#/definitions/Role"
                            },
                            "type": "array"
                        },
                        "priority": {
                            "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.",
                            "maximum": 1,
                            "minimum": 0,
                            "type": "number"
                        }
                    },
                    "type": "object"
                }
            },
            "type": "object"
        },
        "BlobResourceContents": {
            "properties": {
                "blob": {
                    "description": "A base64-encoded string representing the binary data of the item.",
                    "format": "byte",
                    "type": "string"
                },
                "mimeType": {
                    "description": "The MIME type of this resource, if known.",
                    "type": "string"
                },
                "uri": {
                    "description": "The URI of this resource.",
                    "format": "uri",
                    "type": "string"
                }
            },
            "required": [
                "blob",
                "uri"
            ],
            "type": "object"
        },
        "CallToolRequest": {
            "description": "Used by the client to invoke a tool provided by the server.",
            "properties": {
                "method": {
                    "const": "tools/call",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "arguments": {
                            "additionalProperties": {},
                            "type": "object"
                        },
                        "name": {
                            "type": "string"
                        }
                    },
                    "required": [
                        "name"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "CallToolResult": {
            "description": "The server's response to a tool call.\n\nAny errors that originate from the tool SHOULD be reported inside the result\nobject, with `isError` set to true, _not_ as an MCP protocol-level error\nresponse. Otherwise, the LLM would not be able to see that an error occurred\nand self-correct.\n\nHowever, any errors in _finding_ the tool, an error indicating that the\nserver does not support tool calls, or any other exceptional conditions,\nshould be reported as an MCP error response.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "content": {
                    "items": {
                        "anyOf": [
                            {
                                "$ref": "#/definitions/TextContent"
                            },
                            {
                                "$ref": "#/definitions/ImageContent"
                            },
                            {
                                "$ref": "#/definitions/EmbeddedResource"
                            }
                        ]
                    },
                    "type": "array"
                },
                "isError": {
                    "description": "Whether the tool call ended in an error.\n\nIf not set, this is assumed to be false (the call was successful).",
                    "type": "boolean"
                }
            },
            "required": [
                "content"
            ],
            "type": "object"
        },
        "CancelledNotification": {
            "description": "This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n\nThe request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.\n\nA client MUST NOT attempt to cancel its `initialize` request.",
            "properties": {
                "method": {
                    "const": "notifications/cancelled",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "reason": {
                            "description": "An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.",
                            "type": "string"
                        },
                        "requestId": {
                            "$ref": "#/definitions/RequestId",
                            "description": "The ID of the request to cancel.\n\nThis MUST correspond to the ID of a request previously issued in the same direction."
                        }
                    },
                    "required": [
                        "requestId"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "ClientCapabilities": {
            "description": "Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.",
            "properties": {
                "experimental": {
                    "additionalProperties": {
                        "additionalProperties": true,
                        "properties": {},
                        "type": "object"
                    },
                    "description": "Experimental, non-standard capabilities that the client supports.",
                    "type": "object"
                },
                "roots": {
                    "description": "Present if the client supports listing roots.",
                    "properties": {
                        "listChanged": {
                            "description": "Whether the client supports notifications for changes to the roots list.",
                            "type": "boolean"
                        }
                    },
                    "type": "object"
                },
                "sampling": {
                    "additionalProperties": true,
                    "description": "Present if the client supports sampling from an LLM.",
                    "properties": {},
                    "type": "object"
                }
            },
            "type": "object"
        },
        "ClientNotification": {
            "anyOf": [
                {
                    "$ref": "#/definitions/CancelledNotification"
                },
                {
                    "$ref": "#/definitions/InitializedNotification"
                },
                {
                    "$ref": "#/definitions/ProgressNotification"
                },
                {
                    "$ref": "#/definitions/RootsListChangedNotification"
                }
            ]
        },
        "ClientRequest": {
            "anyOf": [
                {
                    "$ref": "#/definitions/InitializeRequest"
                },
                {
                    "$ref": "#/definitions/PingRequest"
                },
                {
                    "$ref": "#/definitions/ListResourcesRequest"
                },
                {
                    "$ref": "#/definitions/ReadResourceRequest"
                },
                {
                    "$ref": "#/definitions/SubscribeRequest"
                },
                {
                    "$ref": "#/definitions/UnsubscribeRequest"
                },
                {
                    "$ref": "#/definitions/ListPromptsRequest"
                },
                {
                    "$ref": "#/definitions/GetPromptRequest"
                },
                {
                    "$ref": "#/definitions/ListToolsRequest"
                },
                {
                    "$ref": "#/definitions/CallToolRequest"
                },
                {
                    "$ref": "#/definitions/SetLevelRequest"
                },
                {
                    "$ref": "#/definitions/CompleteRequest"
                }
            ]
        },
        "ClientResult": {
            "anyOf": [
                {
                    "$ref": "#/definitions/Result"
                },
                {
                    "$ref": "#/definitions/CreateMessageResult"
                },
                {
                    "$ref": "#/definitions/ListRootsResult"
                }
            ]
        },
        "CompleteRequest": {
            "description": "A request from the client to the server, to ask for completion options.",
            "properties": {
                "method": {
                    "const": "completion/complete",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "argument": {
                            "description": "The argument's information",
                            "properties": {
                                "name": {
                                    "description": "The name of the argument",
                                    "type": "string"
                                },
                                "value": {
                                    "description": "The value of the argument to use for completion matching.",
                                    "type": "string"
                                }
                            },
                            "required": [
                                "name",
                                "value"
                            ],
                            "type": "object"
                        },
                        "ref": {
                            "anyOf": [
                                {
                                    "$ref": "#/definitions/PromptReference"
                                },
                                {
                                    "$ref": "#/definitions/ResourceReference"
                                }
                            ]
                        }
                    },
                    "required": [
                        "argument",
                        "ref"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "CompleteResult": {
            "description": "The server's response to a completion/complete request",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "completion": {
                    "properties": {
                        "hasMore": {
                            "description": "Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.",
                            "type": "boolean"
                        },
                        "total": {
                            "description": "The total number of completion options available. This can exceed the number of values actually sent in the response.",
                            "type": "integer"
                        },
                        "values": {
                            "description": "An array of completion values. Must not exceed 100 items.",
                            "items": {
                                "type": "string"
                            },
                            "type": "array"
                        }
                    },
                    "required": [
                        "values"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "completion"
            ],
            "type": "object"
        },
        "CreateMessageRequest": {
            "description": "A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.",
            "properties": {
                "method": {
                    "const": "sampling/createMessage",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "includeContext": {
                            "description": "A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.",
                            "enum": [
                                "allServers",
                                "none",
                                "thisServer"
                            ],
                            "type": "string"
                        },
                        "maxTokens": {
                            "description": "The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.",
                            "type": "integer"
                        },
                        "messages": {
                            "items": {
                                "$ref": "#/definitions/SamplingMessage"
                            },
                            "type": "array"
                        },
                        "metadata": {
                            "additionalProperties": true,
                            "description": "Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.",
                            "properties": {},
                            "type": "object"
                        },
                        "modelPreferences": {
                            "$ref": "#/definitions/ModelPreferences",
                            "description": "The server's preferences for which model to select. The client MAY ignore these preferences."
                        },
                        "stopSequences": {
                            "items": {
                                "type": "string"
                            },
                            "type": "array"
                        },
                        "systemPrompt": {
                            "description": "An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.",
                            "type": "string"
                        },
                        "temperature": {
                            "type": "number"
                        }
                    },
                    "required": [
                        "maxTokens",
                        "messages"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "CreateMessageResult": {
            "description": "The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "content": {
                    "anyOf": [
                        {
                            "$ref": "#/definitions/TextContent"
                        },
                        {
                            "$ref": "#/definitions/ImageContent"
                        }
                    ]
                },
                "model": {
                    "description": "The name of the model that generated the message.",
                    "type": "string"
                },
                "role": {
                    "$ref": "#/definitions/Role"
                },
                "stopReason": {
                    "description": "The reason why sampling stopped, if known.",
                    "type": "string"
                }
            },
            "required": [
                "content",
                "model",
                "role"
            ],
            "type": "object"
        },
        "Cursor": {
            "description": "An opaque token used to represent a cursor for pagination.",
            "type": "string"
        },
        "EmbeddedResource": {
            "description": "The contents of a resource, embedded into a prompt or tool call result.\n\nIt is up to the client how best to render embedded resources for the benefit\nof the LLM and/or the user.",
            "properties": {
                "annotations": {
                    "properties": {
                        "audience": {
                            "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).",
                            "items": {
                                "$ref": "#/definitions/Role"
                            },
                            "type": "array"
                        },
                        "priority": {
                            "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.",
                            "maximum": 1,
                            "minimum": 0,
                            "type": "number"
                        }
                    },
                    "type": "object"
                },
                "resource": {
                    "anyOf": [
                        {
                            "$ref": "#/definitions/TextResourceContents"
                        },
                        {
                            "$ref": "#/definitions/BlobResourceContents"
                        }
                    ]
                },
                "type": {
                    "const": "resource",
                    "type": "string"
                }
            },
            "required": [
                "resource",
                "type"
            ],
            "type": "object"
        },
        "EmptyResult": {
            "$ref": "#/definitions/Result"
        },
        "GetPromptRequest": {
            "description": "Used by the client to get a prompt provided by the server.",
            "properties": {
                "method": {
                    "const": "prompts/get",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "arguments": {
                            "additionalProperties": {
                                "type": "string"
                            },
                            "description": "Arguments to use for templating the prompt.",
                            "type": "object"
                        },
                        "name": {
                            "description": "The name of the prompt or prompt template.",
                            "type": "string"
                        }
                    },
                    "required": [
                        "name"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "GetPromptResult": {
            "description": "The server's response to a prompts/get request from the client.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "description": {
                    "description": "An optional description for the prompt.",
                    "type": "string"
                },
                "messages": {
                    "items": {
                        "$ref": "#/definitions/PromptMessage"
                    },
                    "type": "array"
                }
            },
            "required": [
                "messages"
            ],
            "type": "object"
        },
        "ImageContent": {
            "description": "An image provided to or from an LLM.",
            "properties": {
                "annotations": {
                    "properties": {
                        "audience": {
                            "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).",
                            "items": {
                                "$ref": "#/definitions/Role"
                            },
                            "type": "array"
                        },
                        "priority": {
                            "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.",
                            "maximum": 1,
                            "minimum": 0,
                            "type": "number"
                        }
                    },
                    "type": "object"
                },
                "data": {
                    "description": "The base64-encoded image data.",
                    "format": "byte",
                    "type": "string"
                },
                "mimeType": {
                    "description": "The MIME type of the image. Different providers may support different image types.",
                    "type": "string"
                },
                "type": {
                    "const": "image",
                    "type": "string"
                }
            },
            "required": [
                "data",
                "mimeType",
                "type"
            ],
            "type": "object"
        },
        "Implementation": {
            "description": "Describes the name and version of an MCP implementation.",
            "properties": {
                "name": {
                    "type": "string"
                },
                "version": {
                    "type": "string"
                }
            },
            "required": [
                "name",
                "version"
            ],
            "type": "object"
        },
        "InitializeRequest": {
            "description": "This request is sent from the client to the server when it first connects, asking it to begin initialization.",
            "properties": {
                "method": {
                    "const": "initialize",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "capabilities": {
                            "$ref": "#/definitions/ClientCapabilities"
                        },
                        "clientInfo": {
                            "$ref": "#/definitions/Implementation"
                        },
                        "protocolVersion": {
                            "description": "The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.",
                            "type": "string"
                        }
                    },
                    "required": [
                        "capabilities",
                        "clientInfo",
                        "protocolVersion"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "InitializeResult": {
            "description": "After receiving an initialize request from the client, the server sends this response.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "capabilities": {
                    "$ref": "#/definitions/ServerCapabilities"
                },
                "instructions": {
                    "description": "Instructions describing how to use the server and its features.\n\nThis can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.",
                    "type": "string"
                },
                "protocolVersion": {
                    "description": "The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.",
                    "type": "string"
                },
                "serverInfo": {
                    "$ref": "#/definitions/Implementation"
                }
            },
            "required": [
                "capabilities",
                "protocolVersion",
                "serverInfo"
            ],
            "type": "object"
        },
        "InitializedNotification": {
            "description": "This notification is sent from the client to the server after initialization has finished.",
            "properties": {
                "method": {
                    "const": "notifications/initialized",
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "additionalProperties": {},
                            "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.",
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "JSONRPCError": {
            "description": "A response to a request that indicates an error occurred.",
            "properties": {
                "error": {
                    "properties": {
                        "code": {
                            "description": "The error type that occurred.",
                            "type": "integer"
                        },
                        "data": {
                            "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)."
                        },
                        "message": {
                            "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.",
                            "type": "string"
                        }
                    },
                    "required": [
                        "code",
                        "message"
                    ],
                    "type": "object"
                },
                "id": {
                    "$ref": "#/definitions/RequestId"
                },
                "jsonrpc": {
                    "const": "2.0",
                    "type": "string"
                }
            },
            "required": [
                "error",
                "id",
                "jsonrpc"
            ],
            "type": "object"
        },
        "JSONRPCMessage": {
            "anyOf": [
                {
                    "$ref": "#/definitions/JSONRPCRequest"
                },
                {
                    "$ref": "#/definitions/JSONRPCNotification"
                },
                {
                    "$ref": "#/definitions/JSONRPCResponse"
                },
                {
                    "$ref": "#/definitions/JSONRPCError"
                }
            ]
        },
        "JSONRPCNotification": {
            "description": "A notification which does not expect a response.",
            "properties": {
                "jsonrpc": {
                    "const": "2.0",
                    "type": "string"
                },
                "method": {
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "additionalProperties": {},
                            "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.",
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "jsonrpc",
                "method"
            ],
            "type": "object"
        },
        "JSONRPCRequest": {
            "description": "A request that expects a response.",
            "properties": {
                "id": {
                    "$ref": "#/definitions/RequestId"
                },
                "jsonrpc": {
                    "const": "2.0",
                    "type": "string"
                },
                "method": {
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "properties": {
                                "progressToken": {
                                    "$ref": "#/definitions/ProgressToken",
                                    "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications."
                                }
                            },
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "id",
                "jsonrpc",
                "method"
            ],
            "type": "object"
        },
        "JSONRPCResponse": {
            "description": "A successful (non-error) response to a request.",
            "properties": {
                "id": {
                    "$ref": "#/definitions/RequestId"
                },
                "jsonrpc": {
                    "const": "2.0",
                    "type": "string"
                },
                "result": {
                    "$ref": "#/definitions/Result"
                }
            },
            "required": [
                "id",
                "jsonrpc",
                "result"
            ],
            "type": "object"
        },
        "ListPromptsRequest": {
            "description": "Sent from the client to request a list of prompts and prompt templates the server has.",
            "properties": {
                "method": {
                    "const": "prompts/list",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "cursor": {
                            "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.",
                            "type": "string"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "ListPromptsResult": {
            "description": "The server's response to a prompts/list request from the client.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "nextCursor": {
                    "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
                    "type": "string"
                },
                "prompts": {
                    "items": {
                        "$ref": "#/definitions/Prompt"
                    },
                    "type": "array"
                }
            },
            "required": [
                "prompts"
            ],
            "type": "object"
        },
        "ListResourceTemplatesRequest": {
            "description": "Sent from the client to request a list of resource templates the server has.",
            "properties": {
                "method": {
                    "const": "resources/templates/list",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "cursor": {
                            "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.",
                            "type": "string"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "ListResourceTemplatesResult": {
            "description": "The server's response to a resources/templates/list request from the client.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "nextCursor": {
                    "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
                    "type": "string"
                },
                "resourceTemplates": {
                    "items": {
                        "$ref": "#/definitions/ResourceTemplate"
                    },
                    "type": "array"
                }
            },
            "required": [
                "resourceTemplates"
            ],
            "type": "object"
        },
        "ListResourcesRequest": {
            "description": "Sent from the client to request a list of resources the server has.",
            "properties": {
                "method": {
                    "const": "resources/list",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "cursor": {
                            "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.",
                            "type": "string"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "ListResourcesResult": {
            "description": "The server's response to a resources/list request from the client.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "nextCursor": {
                    "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
                    "type": "string"
                },
                "resources": {
                    "items": {
                        "$ref": "#/definitions/Resource"
                    },
                    "type": "array"
                }
            },
            "required": [
                "resources"
            ],
            "type": "object"
        },
        "ListRootsRequest": {
            "description": "Sent from the server to request a list of root URIs from the client. Roots allow\nservers to ask for specific directories or files to operate on. A common example\nfor roots is providing a set of repositories or directories a server should operate\non.\n\nThis request is typically used when the server needs to understand the file system\nstructure or access specific locations that the client has permission to read from.",
            "properties": {
                "method": {
                    "const": "roots/list",
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "properties": {
                                "progressToken": {
                                    "$ref": "#/definitions/ProgressToken",
                                    "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications."
                                }
                            },
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "ListRootsResult": {
            "description": "The client's response to a roots/list request from the server.\nThis result contains an array of Root objects, each representing a root directory\nor file that the server can operate on.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "roots": {
                    "items": {
                        "$ref": "#/definitions/Root"
                    },
                    "type": "array"
                }
            },
            "required": [
                "roots"
            ],
            "type": "object"
        },
        "ListToolsRequest": {
            "description": "Sent from the client to request a list of tools the server has.",
            "properties": {
                "method": {
                    "const": "tools/list",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "cursor": {
                            "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.",
                            "type": "string"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "ListToolsResult": {
            "description": "The server's response to a tools/list request from the client.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "nextCursor": {
                    "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
                    "type": "string"
                },
                "tools": {
                    "items": {
                        "$ref": "#/definitions/Tool"
                    },
                    "type": "array"
                }
            },
            "required": [
                "tools"
            ],
            "type": "object"
        },
        "LoggingLevel": {
            "description": "The severity of a log message.\n\nThese map to syslog message severities, as specified in RFC-5424:\nhttps://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1",
            "enum": [
                "alert",
                "critical",
                "debug",
                "emergency",
                "error",
                "info",
                "notice",
                "warning"
            ],
            "type": "string"
        },
        "LoggingMessageNotification": {
            "description": "Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.",
            "properties": {
                "method": {
                    "const": "notifications/message",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "data": {
                            "description": "The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here."
                        },
                        "level": {
                            "$ref": "#/definitions/LoggingLevel",
                            "description": "The severity of this log message."
                        },
                        "logger": {
                            "description": "An optional name of the logger issuing this message.",
                            "type": "string"
                        }
                    },
                    "required": [
                        "data",
                        "level"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "ModelHint": {
            "description": "Hints to use for model selection.\n\nKeys not declared here are currently left unspecified by the spec and are up\nto the client to interpret.",
            "properties": {
                "name": {
                    "description": "A hint for a model name.\n\nThe client SHOULD treat this as a substring of a model name; for example:\n - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n - `claude` should match any Claude model\n\nThe client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example:\n - `gemini-1.5-flash` could match `claude-3-haiku-20240307`",
                    "type": "string"
                }
            },
            "type": "object"
        },
        "ModelPreferences": {
            "description": "The server's preferences for model selection, requested of the client during sampling.\n\nBecause LLMs can vary along multiple dimensions, choosing the \"best\" model is\nrarely straightforward.  Different models excel in different areas—some are\nfaster but less capable, others are more capable but more expensive, and so\non. This interface allows servers to express their priorities across multiple\ndimensions to help clients make an appropriate selection for their use case.\n\nThese preferences are always advisory. The client MAY ignore them. It is also\nup to the client to decide how to interpret these preferences and how to\nbalance them against other considerations.",
            "properties": {
                "costPriority": {
                    "description": "How much to prioritize cost when selecting a model. A value of 0 means cost\nis not important, while a value of 1 means cost is the most important\nfactor.",
                    "maximum": 1,
                    "minimum": 0,
                    "type": "number"
                },
                "hints": {
                    "description": "Optional hints to use for model selection.\n\nIf multiple hints are specified, the client MUST evaluate them in order\n(such that the first match is taken).\n\nThe client SHOULD prioritize these hints over the numeric priorities, but\nMAY still use the priorities to select from ambiguous matches.",
                    "items": {
                        "$ref": "#/definitions/ModelHint"
                    },
                    "type": "array"
                },
                "intelligencePriority": {
                    "description": "How much to prioritize intelligence and capabilities when selecting a\nmodel. A value of 0 means intelligence is not important, while a value of 1\nmeans intelligence is the most important factor.",
                    "maximum": 1,
                    "minimum": 0,
                    "type": "number"
                },
                "speedPriority": {
                    "description": "How much to prioritize sampling speed (latency) when selecting a model. A\nvalue of 0 means speed is not important, while a value of 1 means speed is\nthe most important factor.",
                    "maximum": 1,
                    "minimum": 0,
                    "type": "number"
                }
            },
            "type": "object"
        },
        "Notification": {
            "properties": {
                "method": {
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "additionalProperties": {},
                            "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.",
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "PaginatedRequest": {
            "properties": {
                "method": {
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "cursor": {
                            "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.",
                            "type": "string"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "PaginatedResult": {
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "nextCursor": {
                    "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
                    "type": "string"
                }
            },
            "type": "object"
        },
        "PingRequest": {
            "description": "A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.",
            "properties": {
                "method": {
                    "const": "ping",
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "properties": {
                                "progressToken": {
                                    "$ref": "#/definitions/ProgressToken",
                                    "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications."
                                }
                            },
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "ProgressNotification": {
            "description": "An out-of-band notification used to inform the receiver of a progress update for a long-running request.",
            "properties": {
                "method": {
                    "const": "notifications/progress",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "progress": {
                            "description": "The progress thus far. This should increase every time progress is made, even if the total is unknown.",
                            "type": "number"
                        },
                        "progressToken": {
                            "$ref": "#/definitions/ProgressToken",
                            "description": "The progress token which was given in the initial request, used to associate this notification with the request that is proceeding."
                        },
                        "total": {
                            "description": "Total number of items to process (or total progress required), if known.",
                            "type": "number"
                        }
                    },
                    "required": [
                        "progress",
                        "progressToken"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "ProgressToken": {
            "description": "A progress token, used to associate progress notifications with the original request.",
            "type": [
                "string",
                "integer"
            ]
        },
        "Prompt": {
            "description": "A prompt or prompt template that the server offers.",
            "properties": {
                "arguments": {
                    "description": "A list of arguments to use for templating the prompt.",
                    "items": {
                        "$ref": "#/definitions/PromptArgument"
                    },
                    "type": "array"
                },
                "description": {
                    "description": "An optional description of what this prompt provides",
                    "type": "string"
                },
                "name": {
                    "description": "The name of the prompt or prompt template.",
                    "type": "string"
                }
            },
            "required": [
                "name"
            ],
            "type": "object"
        },
        "PromptArgument": {
            "description": "Describes an argument that a prompt can accept.",
            "properties": {
                "description": {
                    "description": "A human-readable description of the argument.",
                    "type": "string"
                },
                "name": {
                    "description": "The name of the argument.",
                    "type": "string"
                },
                "required": {
                    "description": "Whether this argument must be provided.",
                    "type": "boolean"
                }
            },
            "required": [
                "name"
            ],
            "type": "object"
        },
        "PromptListChangedNotification": {
            "description": "An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.",
            "properties": {
                "method": {
                    "const": "notifications/prompts/list_changed",
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "additionalProperties": {},
                            "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.",
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "PromptMessage": {
            "description": "Describes a message returned as part of a prompt.\n\nThis is similar to `SamplingMessage`, but also supports the embedding of\nresources from the MCP server.",
            "properties": {
                "content": {
                    "anyOf": [
                        {
                            "$ref": "#/definitions/TextContent"
                        },
                        {
                            "$ref": "#/definitions/ImageContent"
                        },
                        {
                            "$ref": "#/definitions/EmbeddedResource"
                        }
                    ]
                },
                "role": {
                    "$ref": "#/definitions/Role"
                }
            },
            "required": [
                "content",
                "role"
            ],
            "type": "object"
        },
        "PromptReference": {
            "description": "Identifies a prompt.",
            "properties": {
                "name": {
                    "description": "The name of the prompt or prompt template",
                    "type": "string"
                },
                "type": {
                    "const": "ref/prompt",
                    "type": "string"
                }
            },
            "required": [
                "name",
                "type"
            ],
            "type": "object"
        },
        "ReadResourceRequest": {
            "description": "Sent from the client to the server, to read a specific resource URI.",
            "properties": {
                "method": {
                    "const": "resources/read",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "uri": {
                            "description": "The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.",
                            "format": "uri",
                            "type": "string"
                        }
                    },
                    "required": [
                        "uri"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "ReadResourceResult": {
            "description": "The server's response to a resources/read request from the client.",
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                },
                "contents": {
                    "items": {
                        "anyOf": [
                            {
                                "$ref": "#/definitions/TextResourceContents"
                            },
                            {
                                "$ref": "#/definitions/BlobResourceContents"
                            }
                        ]
                    },
                    "type": "array"
                }
            },
            "required": [
                "contents"
            ],
            "type": "object"
        },
        "Request": {
            "properties": {
                "method": {
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "properties": {
                                "progressToken": {
                                    "$ref": "#/definitions/ProgressToken",
                                    "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications."
                                }
                            },
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "RequestId": {
            "description": "A uniquely identifying ID for a request in JSON-RPC.",
            "type": [
                "string",
                "integer"
            ]
        },
        "Resource": {
            "description": "A known resource that the server is capable of reading.",
            "properties": {
                "annotations": {
                    "properties": {
                        "audience": {
                            "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).",
                            "items": {
                                "$ref": "#/definitions/Role"
                            },
                            "type": "array"
                        },
                        "priority": {
                            "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.",
                            "maximum": 1,
                            "minimum": 0,
                            "type": "number"
                        }
                    },
                    "type": "object"
                },
                "description": {
                    "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.",
                    "type": "string"
                },
                "mimeType": {
                    "description": "The MIME type of this resource, if known.",
                    "type": "string"
                },
                "name": {
                    "description": "A human-readable name for this resource.\n\nThis can be used by clients to populate UI elements.",
                    "type": "string"
                },
                "uri": {
                    "description": "The URI of this resource.",
                    "format": "uri",
                    "type": "string"
                }
            },
            "required": [
                "name",
                "uri"
            ],
            "type": "object"
        },
        "ResourceContents": {
            "description": "The contents of a specific resource or sub-resource.",
            "properties": {
                "mimeType": {
                    "description": "The MIME type of this resource, if known.",
                    "type": "string"
                },
                "uri": {
                    "description": "The URI of this resource.",
                    "format": "uri",
                    "type": "string"
                }
            },
            "required": [
                "uri"
            ],
            "type": "object"
        },
        "ResourceListChangedNotification": {
            "description": "An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.",
            "properties": {
                "method": {
                    "const": "notifications/resources/list_changed",
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "additionalProperties": {},
                            "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.",
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "ResourceReference": {
            "description": "A reference to a resource or resource template definition.",
            "properties": {
                "type": {
                    "const": "ref/resource",
                    "type": "string"
                },
                "uri": {
                    "description": "The URI or URI template of the resource.",
                    "format": "uri-template",
                    "type": "string"
                }
            },
            "required": [
                "type",
                "uri"
            ],
            "type": "object"
        },
        "ResourceTemplate": {
            "description": "A template description for resources available on the server.",
            "properties": {
                "annotations": {
                    "properties": {
                        "audience": {
                            "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).",
                            "items": {
                                "$ref": "#/definitions/Role"
                            },
                            "type": "array"
                        },
                        "priority": {
                            "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.",
                            "maximum": 1,
                            "minimum": 0,
                            "type": "number"
                        }
                    },
                    "type": "object"
                },
                "description": {
                    "description": "A description of what this template is for.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.",
                    "type": "string"
                },
                "mimeType": {
                    "description": "The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.",
                    "type": "string"
                },
                "name": {
                    "description": "A human-readable name for the type of resource this template refers to.\n\nThis can be used by clients to populate UI elements.",
                    "type": "string"
                },
                "uriTemplate": {
                    "description": "A URI template (according to RFC 6570) that can be used to construct resource URIs.",
                    "format": "uri-template",
                    "type": "string"
                }
            },
            "required": [
                "name",
                "uriTemplate"
            ],
            "type": "object"
        },
        "ResourceUpdatedNotification": {
            "description": "A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.",
            "properties": {
                "method": {
                    "const": "notifications/resources/updated",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "uri": {
                            "description": "The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.",
                            "format": "uri",
                            "type": "string"
                        }
                    },
                    "required": [
                        "uri"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "Result": {
            "additionalProperties": {},
            "properties": {
                "_meta": {
                    "additionalProperties": {},
                    "description": "This result property is reserved by the protocol to allow clients and servers to attach additional metadata to their responses.",
                    "type": "object"
                }
            },
            "type": "object"
        },
        "Role": {
            "description": "The sender or recipient of messages and data in a conversation.",
            "enum": [
                "assistant",
                "user"
            ],
            "type": "string"
        },
        "Root": {
            "description": "Represents a root directory or file that the server can operate on.",
            "properties": {
                "name": {
                    "description": "An optional name for the root. This can be used to provide a human-readable\nidentifier for the root, which may be useful for display purposes or for\nreferencing the root in other parts of the application.",
                    "type": "string"
                },
                "uri": {
                    "description": "The URI identifying the root. This *must* start with file:// for now.\nThis restriction may be relaxed in future versions of the protocol to allow\nother URI schemes.",
                    "format": "uri",
                    "type": "string"
                }
            },
            "required": [
                "uri"
            ],
            "type": "object"
        },
        "RootsListChangedNotification": {
            "description": "A notification from the client to the server, informing it that the list of roots has changed.\nThis notification should be sent whenever the client adds, removes, or modifies any root.\nThe server should then request an updated list of roots using the ListRootsRequest.",
            "properties": {
                "method": {
                    "const": "notifications/roots/list_changed",
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "additionalProperties": {},
                            "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.",
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "SamplingMessage": {
            "description": "Describes a message issued to or received from an LLM API.",
            "properties": {
                "content": {
                    "anyOf": [
                        {
                            "$ref": "#/definitions/TextContent"
                        },
                        {
                            "$ref": "#/definitions/ImageContent"
                        }
                    ]
                },
                "role": {
                    "$ref": "#/definitions/Role"
                }
            },
            "required": [
                "content",
                "role"
            ],
            "type": "object"
        },
        "ServerCapabilities": {
            "description": "Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.",
            "properties": {
                "experimental": {
                    "additionalProperties": {
                        "additionalProperties": true,
                        "properties": {},
                        "type": "object"
                    },
                    "description": "Experimental, non-standard capabilities that the server supports.",
                    "type": "object"
                },
                "logging": {
                    "additionalProperties": true,
                    "description": "Present if the server supports sending log messages to the client.",
                    "properties": {},
                    "type": "object"
                },
                "prompts": {
                    "description": "Present if the server offers any prompt templates.",
                    "properties": {
                        "listChanged": {
                            "description": "Whether this server supports notifications for changes to the prompt list.",
                            "type": "boolean"
                        }
                    },
                    "type": "object"
                },
                "resources": {
                    "description": "Present if the server offers any resources to read.",
                    "properties": {
                        "listChanged": {
                            "description": "Whether this server supports notifications for changes to the resource list.",
                            "type": "boolean"
                        },
                        "subscribe": {
                            "description": "Whether this server supports subscribing to resource updates.",
                            "type": "boolean"
                        }
                    },
                    "type": "object"
                },
                "tools": {
                    "description": "Present if the server offers any tools to call.",
                    "properties": {
                        "listChanged": {
                            "description": "Whether this server supports notifications for changes to the tool list.",
                            "type": "boolean"
                        }
                    },
                    "type": "object"
                }
            },
            "type": "object"
        },
        "ServerNotification": {
            "anyOf": [
                {
                    "$ref": "#/definitions/CancelledNotification"
                },
                {
                    "$ref": "#/definitions/ProgressNotification"
                },
                {
                    "$ref": "#/definitions/ResourceListChangedNotification"
                },
                {
                    "$ref": "#/definitions/ResourceUpdatedNotification"
                },
                {
                    "$ref": "#/definitions/PromptListChangedNotification"
                },
                {
                    "$ref": "#/definitions/ToolListChangedNotification"
                },
                {
                    "$ref": "#/definitions/LoggingMessageNotification"
                }
            ]
        },
        "ServerRequest": {
            "anyOf": [
                {
                    "$ref": "#/definitions/PingRequest"
                },
                {
                    "$ref": "#/definitions/CreateMessageRequest"
                },
                {
                    "$ref": "#/definitions/ListRootsRequest"
                }
            ]
        },
        "ServerResult": {
            "anyOf": [
                {
                    "$ref": "#/definitions/Result"
                },
                {
                    "$ref": "#/definitions/InitializeResult"
                },
                {
                    "$ref": "#/definitions/ListResourcesResult"
                },
                {
                    "$ref": "#/definitions/ReadResourceResult"
                },
                {
                    "$ref": "#/definitions/ListPromptsResult"
                },
                {
                    "$ref": "#/definitions/GetPromptResult"
                },
                {
                    "$ref": "#/definitions/ListToolsResult"
                },
                {
                    "$ref": "#/definitions/CallToolResult"
                },
                {
                    "$ref": "#/definitions/CompleteResult"
                }
            ]
        },
        "SetLevelRequest": {
            "description": "A request from the client to the server, to enable or adjust logging.",
            "properties": {
                "method": {
                    "const": "logging/setLevel",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "level": {
                            "$ref": "#/definitions/LoggingLevel",
                            "description": "The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message."
                        }
                    },
                    "required": [
                        "level"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "SubscribeRequest": {
            "description": "Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.",
            "properties": {
                "method": {
                    "const": "resources/subscribe",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "uri": {
                            "description": "The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.",
                            "format": "uri",
                            "type": "string"
                        }
                    },
                    "required": [
                        "uri"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        },
        "TextContent": {
            "description": "Text provided to or from an LLM.",
            "properties": {
                "annotations": {
                    "properties": {
                        "audience": {
                            "description": "Describes who the intended customer of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).",
                            "items": {
                                "$ref": "#/definitions/Role"
                            },
                            "type": "array"
                        },
                        "priority": {
                            "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.",
                            "maximum": 1,
                            "minimum": 0,
                            "type": "number"
                        }
                    },
                    "type": "object"
                },
                "text": {
                    "description": "The text content of the message.",
                    "type": "string"
                },
                "type": {
                    "const": "text",
                    "type": "string"
                }
            },
            "required": [
                "text",
                "type"
            ],
            "type": "object"
        },
        "TextResourceContents": {
            "properties": {
                "mimeType": {
                    "description": "The MIME type of this resource, if known.",
                    "type": "string"
                },
                "text": {
                    "description": "The text of the item. This must only be set if the item can actually be represented as text (not binary data).",
                    "type": "string"
                },
                "uri": {
                    "description": "The URI of this resource.",
                    "format": "uri",
                    "type": "string"
                }
            },
            "required": [
                "text",
                "uri"
            ],
            "type": "object"
        },
        "Tool": {
            "description": "Definition for a tool the client can call.",
            "properties": {
                "description": {
                    "description": "A human-readable description of the tool.",
                    "type": "string"
                },
                "inputSchema": {
                    "description": "A JSON Schema object defining the expected parameters for the tool.",
                    "properties": {
                        "properties": {
                            "additionalProperties": {
                                "additionalProperties": true,
                                "properties": {},
                                "type": "object"
                            },
                            "type": "object"
                        },
                        "required": {
                            "items": {
                                "type": "string"
                            },
                            "type": "array"
                        },
                        "type": {
                            "const": "object",
                            "type": "string"
                        }
                    },
                    "required": [
                        "type"
                    ],
                    "type": "object"
                },
                "name": {
                    "description": "The name of the tool.",
                    "type": "string"
                }
            },
            "required": [
                "inputSchema",
                "name"
            ],
            "type": "object"
        },
        "ToolListChangedNotification": {
            "description": "An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.",
            "properties": {
                "method": {
                    "const": "notifications/tools/list_changed",
                    "type": "string"
                },
                "params": {
                    "additionalProperties": {},
                    "properties": {
                        "_meta": {
                            "additionalProperties": {},
                            "description": "This parameter name is reserved by MCP to allow clients and servers to attach additional metadata to their notifications.",
                            "type": "object"
                        }
                    },
                    "type": "object"
                }
            },
            "required": [
                "method"
            ],
            "type": "object"
        },
        "UnsubscribeRequest": {
            "description": "Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.",
            "properties": {
                "method": {
                    "const": "resources/unsubscribe",
                    "type": "string"
                },
                "params": {
                    "properties": {
                        "uri": {
                            "description": "The URI of the resource to unsubscribe from.",
                            "format": "uri",
                            "type": "string"
                        }
                    },
                    "required": [
                        "uri"
                    ],
                    "type": "object"
                }
            },
            "required": [
                "method",
                "params"
            ],
            "type": "object"
        }
    }
}


```
Page 4/6FirstPrevNextLast