Skip to content

Feat/mcp implementation#7

Open
DIodide wants to merge 30 commits intostagingfrom
feat/mcp-implementation
Open

Feat/mcp implementation#7
DIodide wants to merge 30 commits intostagingfrom
feat/mcp-implementation

Conversation

@DIodide
Copy link
Owner

@DIodide DIodide commented Mar 4, 2026

Fun fact, the PR description for this was generated by Harness itself, I'm sure that says enough
image


Feat: Complete MCP Implementation with OAuth Support, Chat Queues & Interrupts

This PR implements a comprehensive Model Context Protocol (MCP) integration with advanced chat features and OAuth authentication support.

Key Features

MCP OAuth & Authentication

  • Full OAuth 2.1 Support: Complete implementation following MCP authorization spec (RFC 9728, RFC 8414, RFC 7591, RFC 8707)
  • Dynamic Discovery: Automatic discovery of authorization servers and protected resource metadata
  • Multi-Auth Types: Support for none, bearer, and oauth authentication types
  • Token Management: Automatic token refresh and secure storage in Convex
  • Pre-registered Clients: Built-in support for known providers (GitHub)
  • Dynamic Client Registration: Fallback registration for unknown providers

Advanced Chat Experience

  • Message Queuing: Queue messages while model is responding instead of blocking
  • Stream Interruption: Stop generation mid-stream and save partial responses
  • Thinking Support: Real-time display of model reasoning (Claude Sonnet 4, DeepSeek R1)
  • Tool Call Visualization: Collapsible, detailed view of function calls and results
  • Message Actions: Copy, regenerate, and developer info based on display mode
  • Prompt History: Arrow key navigation through previous user messages

MCP Server Management

  • Visual MCP Editor: Dedicated harness editing page with server configuration
  • Real-time OAuth Status: Live connection status with one-click authentication
  • Inline URL Editing: Edit server URLs directly with keyboard shortcuts
  • Server Type Indicators: Visual badges for authentication types

Enhanced UI/UX

  • Display Modes: Zen (minimal), Standard (copy), Developer (full debugging)
  • Streaming Parts: Chronological display of reasoning, text, and tool calls
  • Usage Tracking: Token counts and cost tracking for each response
  • Interrupted Messages: Visual indicators for partial responses
  • Queue Chips: Visual queue with send-now and remove actions

Technical Implementation

Backend (FastAPI)

  • MCP Client Refactor: Complete rewrite with session management, streaming support, and error handling
  • OAuth Service: Full OAuth 2.1 implementation with PKCE, discovery, and refresh flows
  • Parallel Tool Execution: Execute multiple tool calls concurrently and stream results
  • Usage Backfilling: Capture and backfill usage data even when streams are interrupted
  • Thinking Models: Support for models with reasoning capabilities

Frontend (React)

  • Queue State Management: React state for message queuing with automatic processing
  • Stream Interruption: Graceful handling of aborted streams with data preservation
  • Parts-based Rendering: Dynamic rendering of mixed content types (text, reasoning, tools)
  • Real-time OAuth: Popup-based OAuth flows with message passing
  • Harness Editor: Dedicated editing interface with live validation

Database (Convex)

  • OAuth Token Storage: Secure token storage with user/server indexing
  • Enhanced Message Schema: Support for reasoning, tool calls, parts, usage, and interruption flags
  • Migration System: Automated schema migrations for harness data structure changes
  • Display Settings: User preference storage for UI display modes

Data Flow Improvements

Message Processing

  1. Streaming: Real-time token, reasoning, and tool call streaming
  2. Interruption: Graceful abort handling with partial data preservation
  3. Queuing: Automatic queue processing when streams complete
  4. Persistence: Enhanced data persistence with usage and metadata

MCP Integration

  1. Discovery: Automatic OAuth server discovery and metadata fetching
  2. Authentication: Secure token management with automatic refresh
  3. Tool Execution: Parallel execution with real-time result streaming
  4. Error Handling: Comprehensive error handling with re-auth prompts

Breaking Changes

  • Harness schema migrated from mcps: string[] to mcpServers: McpServer[]
  • Message schema enhanced with new optional fields (backward compatible)
  • FastAPI MCP client completely rewritten (internal implementation)

New Dependencies

  • Frontend: Enhanced React state management and animation libraries
  • Backend: OAuth discovery and token management utilities
  • Database: New Convex tables for OAuth tokens and enhanced schemas

Usage Examples

Adding MCP Servers

// New MCP server configuration
{
  name: "GitHub",
  url: "https://mcp.example.com/github",
  authType: "oauth", // or "bearer" or "none"
  authToken?: "optional_bearer_token"
}

OAuth Flow

  1. User clicks "Connect" on OAuth server
  2. Popup opens with authorization URL
  3. User authorizes with provider
  4. Tokens automatically stored in Convex
  5. Server immediately available for use

Message Queuing

  • Type message while model is responding → automatically queued
  • Visual chips show queued messages
  • Click "Send Now" to interrupt and prioritize
  • Automatic processing when stream completes

This implementation provides a production-ready MCP integration with enterprise-grade OAuth support and significantly enhanced chat experience. All features are backward compatible and include comprehensive error handling and user feedback.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR introduces a full MCP (Model Context Protocol) integration across the stack, adding OAuth-based MCP server auth, richer streaming chat UX (thinking/tool parts, interrupts, queues), and expanded message/harness schemas to persist the new metadata.

Changes:

  • Adds MCP server configuration (URL + auth type) and an OAuth flow (FastAPI routes + Convex token storage).
  • Refactors MCP client/tooling to support sessions, SSE responses, tool name sanitization, and parallel tool execution.
  • Upgrades chat streaming end-to-end: reasoning parts, tool call visualization, interrupts/queueing, and usage capture/backfill.

Reviewed changes

Copilot reviewed 26 out of 27 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
packages/fastapi/app/services/openrouter.py Adds usage-inclusive streaming options, thinking support, and improved error/log handling for OpenRouter streams.
packages/fastapi/app/services/mcp_oauth.py Implements OAuth discovery, PKCE, code exchange/refresh, and Convex token persistence helpers.
packages/fastapi/app/services/mcp_client.py Major MCP client refactor: session caching, SSE-safe requests, parallel tool listing/calls, OAuth header resolution.
packages/fastapi/app/services/convex.py Extends message save payload and adds usage backfill mutation helper.
packages/fastapi/app/routes/mcp_oauth.py Adds OAuth start/callback/status/revoke endpoints for MCP servers.
packages/fastapi/app/routes/chat.py Adds thinking/tool parts streaming, tool parallelism, interrupt draining for usage, and expanded persistence payload.
packages/fastapi/app/models.py Introduces McpServer model and updates harness config to mcp_servers.
packages/fastapi/app/main.py Registers new OAuth router and updates CORS allowlist.
packages/fastapi/app/config.py Adds model mappings (incl. thinking variants) and OAuth-related settings.
packages/convex-backend/convex/userSettings.ts Adds displayMode setting with validation/defaulting.
packages/convex-backend/convex/seed.ts Updates seed harnesses to new mcpServers shape.
packages/convex-backend/convex/schema.ts Adds MCP servers to harness schema, expands message schema (parts/toolCalls/usage/interrupted), adds mcpOAuthTokens table.
packages/convex-backend/convex/migrations.ts Adds a harness migration helper for the new mcpServers field.
packages/convex-backend/convex/messages.ts Adds message removal, interrupted message saving, assistant message enrichment, and usage backfill mutation.
packages/convex-backend/convex/mcpOAuthTokens.ts Adds token storage/query/revoke endpoints for MCP OAuth tokens.
packages/convex-backend/convex/harnesses.ts Updates harness create/update mutations for mcpServers.
packages/convex-backend/convex/conversations.ts Limits conversation list query to 50 entries.
packages/convex-backend/convex/_generated/api.d.ts Regenerates API typing for new Convex modules.
apps/web/vite.config.ts Adds allowedHosts entry for an ngrok host.
apps/web/src/routes/onboarding.tsx Replaces MCP selection with MCP server entry management (name/url/auth).
apps/web/src/routes/harnesses/index.tsx Adds navigation to a dedicated harness edit route and updates MCP count display.
apps/web/src/routes/harnesses/$harnessId.tsx New harness editor route with MCP server editing and OAuth connect/status UI.
apps/web/src/routes/chat/index.tsx Adds message queueing, interrupts, thinking/tool part rendering, display modes, regenerate, and usage/model UI plumbing.
apps/web/src/routeTree.gen.ts Route tree regeneration to include /harnesses/$harnessId.
apps/web/src/lib/use-chat-stream.ts Extends stream protocol to include thinking events + usage/model on done; adds abort callback.
apps/web/src/lib/models.ts Centralizes model options for the frontend.
apps/web/src/components/message-actions.tsx Adds per-message actions (copy/regenerate/dev info) gated by display mode.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +167 to +176
return f"""<!DOCTYPE html>
<html>
<head><title>MCP OAuth</title></head>
<body>
<p>{"Connected successfully!" if success else f"Error: {error}"}</p>
<p>You can close this window.</p>
<script>
if (window.opener) {{
window.opener.postMessage({json.dumps(message_data)}, "*");
}}
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The OAuth callback HTML both (1) interpolates error directly into the HTML (potential XSS if the error ever contains attacker-controlled text) and (2) posts a message to the opener with targetOrigin="*". Please HTML-escape any user-visible strings and restrict postMessage to a known origin (e.g. settings.frontend_url) so other origins can’t spoof the callback.

Copilot uses AI. Check for mistakes.
Comment on lines +616 to +629
const handler = (event: MessageEvent) => {
if (event.data?.type === "mcp-oauth-callback") {
window.removeEventListener("message", handler);
if (event.data.success) {
setStatus("connected");
toast.success("Connected to MCP server via OAuth");
} else {
toast.error(event.data.error || "OAuth connection failed");
}
setConnecting(false);
popup?.close();
}
};
window.addEventListener("message", handler);
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The message event handler accepts any postMessage payload with { type: "mcp-oauth-callback" } without validating event.origin or event.source (the popup). This allows any site to spoof a successful OAuth callback in the parent window. Please verify the origin matches your FastAPI base URL and that event.source === popup (and consider including/verifying a nonce/state).

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants