Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

checkpoint: File edit:

rUv1764e2588639
diff --git a/.claude/settings.json b/.claude/settings.json
index b9f59b48a2..222b0abd2c 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -73,7 +73,7 @@
{
"type": "command",
"timeout": 5000,
- "command": ".claude/helpers/guidance-hooks.sh pre-edit \"$TOOL_INPUT_file_path\""
+ "command": "/workspaces/claude-flow/.claude/helpers/guidance-hooks.sh pre-edit \"$TOOL_INPUT_file_path\""
}
]
},
diff --git a/v3/@claude-flow/mcp/src/index.ts b/v3/@claude-flow/mcp/src/index.ts
index 6246db85ba..758f595eb7 100644
--- a/v3/@claude-flow/mcp/src/index.ts
+++ b/v3/@claude-flow/mcp/src/index.ts
@@ -141,6 +141,47 @@ export type { PromptHandler, PromptDefinition, PromptRegistryOptions } from './p
export { TaskManager, createTaskManager } from './task-manager.js';
export type { TaskExecutor, TaskManagerOptions } from './task-manager.js';
+// Schema Validator
+export {
+ validateSchema,
+ formatValidationErrors,
+ createValidator,
+} from './schema-validator.js';
+export type { ValidationError, ValidationResult } from './schema-validator.js';
+
+// Rate Limiter
+export {
+ RateLimiter,
+ createRateLimiter,
+ rateLimitMiddleware,
+} from './rate-limiter.js';
+export type { RateLimitConfig, RateLimitResult } from './rate-limiter.js';
+
+// Sampling (Server-initiated LLM)
+export {
+ SamplingManager,
+ createSamplingManager,
+ createMockProvider,
+ createAnthropicProvider,
+} from './sampling.js';
+export type { LLMProvider, SamplingConfig, SamplingContext } from './sampling.js';
+
+// OAuth 2.1
+export {
+ OAuthManager,
+ createOAuthManager,
+ oauthMiddleware,
+ InMemoryTokenStorage,
+ createGitHubOAuthConfig,
+ createGoogleOAuthConfig,
+} from './oauth.js';
+export type {
+ OAuthConfig,
+ OAuthTokens,
+ TokenStorage,
+ AuthorizationRequest,
+} from './oauth.js';
+
// Transport layer
export {
createTransport,
diff --git a/v3/@claude-flow/mcp/src/oauth.ts b/v3/@claude-flow/mcp/src/oauth.ts
new file mode 100644
index 0000000000..4e4baeeb5c
--- /dev/null
+++ b/v3/@claude-flow/mcp/src/oauth.ts
@@ -0,0 +1,447 @@
+/**
+ * @claude-flow/mcp - OAuth 2.1 Authentication
+ *
+ * MCP 2025-11-25 compliant OAuth 2.1 with PKCE
+ */
+
+import { EventEmitter } from 'events';
+import * as crypto from 'crypto';
+import type { ILogger } from './types.js';
+
+/**
+ * OAuth 2.1 configuration
+ */
+export interface OAuthConfig {
+ /** Client ID */
+ clientId: string;
+ /** Client secret (for confidential clients) */
+ clientSecret?: string;
+ /** Authorization endpoint */
+ authorizationEndpoint: string;
+ /** Token endpoint */
+ tokenEndpoint: string;
+ /** Redirect URI */
+ redirectUri: string;
+ /** Scopes to request */
+ scopes?: string[];
+ /** Token storage adapter */
+ tokenStorage?: TokenStorage;
+ /** Enable PKCE (default: true) */
+ usePKCE?: boolean;
+ /** State parameter generator */
+ stateGenerator?: () => string;
+}
+
+/**
+ * OAuth tokens
+ */
+export interface OAuthTokens {
+ accessToken: string;
+ refreshToken?: string;
+ tokenType: string;
+ expiresIn?: number;
+ expiresAt?: number;
+ scope?: string;
+}
+
+/**
+ * Token storage interface
+ */
+export interface TokenStorage {
+ save(key: string, tokens: OAuthTokens): Promise<void>;
+ load(key: string): Promise<OAuthTokens | null>;
+ delete(key: string): Promise<void>;
+}
+
+/**
+ * Authorization request
+ */
+export interface AuthorizationRequest {
+ url: string;
+ state: string;
+ codeVerifier?: string;
+}
+
+/**
+ * Token response from OAuth server
+ */
+interface TokenResponse {
+ access_token: string;
+ refresh_token?: string;
+ token_type: string;
+ expires_in?: number;
+ scope?: string;
+}
+
+/**
+ * In-memory token storage (for development)
+ */
+export class InMemoryTokenStorage implements TokenStorage {
+ private tokens: Map<string, OAuthTokens> = new Map();
+
+ async save(key: string, tokens: OAuthTokens): Promise<void> {
+ this.tokens.set(key, tokens);
+ }
+
+ async load(key: string): Promise<OAuthTokens | null> {
+ return this.tokens.get(key) || null;
+ }
+
+ async delete(key: string): Promise<void> {
+ this.tokens.delete(key);
+ }
+}
+
+/**
+ * OAuth 2.1 Manager
+ */
+export class OAuthManager extends EventEmitter {
+ private readonly config: OAuthConfig;
+ private readonly tokenStorage: TokenStorage;
+ private pendingRequests: Map<string, { codeVerifier?: string; timestamp: number }> = new Map();
+ private cleanupTimer?: NodeJS.Timeout;
+
+ constructor(
+ private readonly logger: ILogger,
+ config: OAuthConfig
+ ) {
+ super();
+ this.config = {
+ usePKCE: true,
+ scopes: [],
+ stateGenerator: () => this.generateRandomString(32),
+ ...config,
+ };
+ this.tokenStorage = config.tokenStorage || new InMemoryTokenStorage();
+ this.startCleanup();
+ }
+
+ /**
+ * Generate authorization URL for OAuth flow
+ */
+ createAuthorizationRequest(): AuthorizationRequest {
+ const state = this.config.stateGenerator!();
+ let codeVerifier: string | undefined;
+ let codeChallenge: string | undefined;
+
+ if (this.config.usePKCE) {
+ codeVerifier = this.generateCodeVerifier();
+ codeChallenge = this.generateCodeChallenge(codeVerifier);
+ }
+
+ const params = new URLSearchParams({
+ response_type: 'code',
+ client_id: this.config.clientId,
+ redirect_uri: this.config.redirectUri,
+ state,
+ });
+
+ if (this.config.scopes && this.config.scopes.length > 0) {
+ params.set('scope', this.config.scopes.join(' '));
+ }
+
+ if (codeChallenge) {
+ params.set('code_challenge', codeChallenge);
+ params.set('code_challenge_method', 'S256');
+ }
+
+ // Store pending request for validation
+ this.pendingRequests.set(state, {
+ codeVerifier,
+ timestamp: Date.now(),
+ });
+
+ const url = `${this.config.authorizationEndpoint}?${params.toString()}`;
+
+ this.logger.debug('Created authorization request', { state, usePKCE: !!codeVerifier });
+ this.emit('authorization:created', { state });
+
+ return { url, state, codeVerifier };
+ }
+
+ /**
+ * Exchange authorization code for tokens
+ */
+ async exchangeCode(code: string, state: string): Promise<OAuthTokens> {
+ const pending = this.pendingRequests.get(state);
+ if (!pending) {
+ throw new Error('Invalid or expired state parameter');
+ }
+
+ this.pendingRequests.delete(state);
+
+ const params = new URLSearchParams({
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: this.config.redirectUri,
+ client_id: this.config.clientId,
+ });
+
+ if (this.config.clientSecret) {
+ params.set('client_secret', this.config.clientSecret);
+ }
+
+ if (pending.codeVerifier) {
+ params.set('code_verifier', pending.codeVerifier);
+ }
+
+ const response = await fetch(this.config.tokenEndpoint, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: params.toString(),
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ this.logger.error('Token exchange failed', { status: response.status, error });
+ throw new Error(`Token exchange failed: ${response.status}`);
+ }
+
+ const data = (await response.json()) as TokenResponse;
+ const tokens = this.parseTokenResponse(data);
+
+ await this.tokenStorage.save('default', tokens);
+ this.logger.info('Token exchange successful');
+ this.emit('tokens:received', { expiresIn: tokens.expiresIn });
+
+ return tokens;
+ }
+
+ /**
+ * Refresh access token using refresh token
+ */
+ async refreshTokens(storageKey: string = 'default'): Promise<OAuthTokens> {
+ const existing = await this.tokenStorage.load(storageKey);
+ if (!existing?.refreshToken) {
+ throw new Error('No refresh token available');
+ }
+
+ const params = new URLSearchParams({
+ grant_type: 'refresh_token',
+ refresh_token: existing.refreshToken,
+ client_id: this.config.clientId,
+ });
+
+ if (this.config.clientSecret) {
+ params.set('client_secret', this.config.clientSecret);
+ }
+
+ const response = await fetch(this.config.tokenEndpoint, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: params.toString(),
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ this.logger.error('Token refresh failed', { status: response.status, error });
+ // Clear invalid tokens
+ await this.tokenStorage.delete(storageKey);
+ throw new Error(`Token refresh failed: ${response.status}`);
+ }
+
+ const data = (await response.json()) as TokenResponse;
+ const tokens = this.parseTokenResponse(data);
+
+ // Preserve refresh token if not returned in response
+ if (!tokens.refreshToken && existing.refreshToken) {
+ tokens.refreshToken = existing.refreshToken;
+ }
+
+ await this.tokenStorage.save(storageKey, tokens);
+ this.logger.info('Token refresh successful');
+ this.emit('tokens:refreshed', { expiresIn: tokens.expiresIn });
+
+ return tokens;
+ }
+
+ /**
+ * Get valid access token (auto-refresh if expired)
+ */
+ async getAccessToken(storageKey: string = 'default'): Promise<string | null> {
+ const tokens = await this.tokenStorage.load(storageKey);
+ if (!tokens) {
+ return null;
+ }
+
+ // Check if token is expired (with 60 second buffer)
+ if (tokens.expiresAt && Date.now() >= tokens.expiresAt - 60000) {
+ if (tokens.refreshToken) {
+ try {
+ const refreshed = await this.refreshTokens(storageKey);
+ return refreshed.accessToken;
+ } catch {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ return tokens.accessToken;
+ }
+
+ /**
+ * Revoke tokens
+ */
+ async revokeTokens(storageKey: string = 'default'): Promise<void> {
+ await this.tokenStorage.delete(storageKey);
+ this.logger.info('Tokens revoked');
+ this.emit('tokens:revoked', { storageKey });
+ }
+
+ /**
+ * Check if authenticated
+ */
+ async isAuthenticated(storageKey: string = 'default'): Promise<boolean> {
+ const token = await this.getAccessToken(storageKey);
+ return token !== null;
+ }
+
+ /**
+ * Destroy manager and cleanup
+ */
+ destroy(): void {
+ if (this.cleanupTimer) {
+ clearInterval(this.cleanupTimer);
+ this.cleanupTimer = undefined;
+ }
+ this.pendingRequests.clear();
+ this.removeAllListeners();
+ }
+
+ /**
+ * Parse token response
+ */
+ private parseTokenResponse(data: TokenResponse): OAuthTokens {
+ return {
+ accessToken: data.access_token,
+ refreshToken: data.refresh_token,
+ tokenType: data.token_type,
+ expiresIn: data.expires_in,
+ expiresAt: data.expires_in ? Date.now() + data.expires_in * 1000 : undefined,
+ scope: data.scope,
+ };
+ }
+
+ /**
+ * Generate PKCE code verifier
+ */
+ private generateCodeVerifier(): string {
+ return this.generateRandomString(64);
+ }
+
+ /**
+ * Generate PKCE code challenge (S256)
+ */
+ private generateCodeChallenge(verifier: string): string {
+ const hash = crypto.createHash('sha256').update(verifier).digest();
+ return this.base64UrlEncode(hash);
+ }
+
+ /**
+ * Generate random string
+ */
+ private generateRandomString(length: number): string {
+ const bytes = crypto.randomBytes(length);
+ return this.base64UrlEncode(bytes).substring(0, length);
+ }
+
+ /**
+ * Base64 URL encode
+ */
+ private base64UrlEncode(buffer: Buffer): string {
+ return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
+ }
+
+ /**
+ * Start cleanup of expired pending requests
+ */
+ private startCleanup(): void {
+ this.cleanupTimer = setInterval(() => {
+ const now = Date.now();
+ const expireTime = 10 * 60 * 1000; // 10 minutes
+
+ for (const [state, request] of this.pendingRequests) {
+ if (now - request.timestamp > expireTime) {
+ this.pendingRequests.delete(state);
+ this.logger.debug('Expired pending OAuth request', { state });
+ }
+ }
+ }, 60000);
+ }
+}
+
+/**
+ * Create OAuth manager
+ */
+export function createOAuthManager(logger: ILogger, config: OAuthConfig): OAuthManager {
+ return new OAuthManager(logger, config);
+}
+
+/**
+ * OAuth middleware for Express/Connect
+ */
+export function oauthMiddleware(oauthManager: OAuthManager, storageKey: string = 'default') {
+ return async (req: any, res: any, next: () => void) => {
+ const token = await oauthManager.getAccessToken(storageKey);
+
+ if (!token) {
+ res.status(401).json({
+ jsonrpc: '2.0',
+ id: null,
+ error: {
+ code: -32000,
+ message: 'Unauthorized - OAuth authentication required',
+ },
+ });
+ return;
+ }
+
+ req.oauthToken = token;
+ next();
+ };
+}
+
+/**
+ * Create GitHub OAuth provider config
+ */
+export function createGitHubOAuthConfig(
+ clientId: string,
+ clientSecret: string,
+ redirectUri: string,
+ scopes: string[] = ['read:user']
+): OAuthConfig {
+ return {
+ clientId,
+ clientSecret,
+ redirectUri,
+ scopes,
+ authorizationEndpoint: 'https://github.com/login/oauth/authorize',
+ tokenEndpoint: 'https://github.com/login/oauth/access_token',
+ usePKCE: false, // GitHub doesn't support PKCE for OAuth apps
+ };
+}
+
+/**
+ * Create Google OAuth provider config
+ */
+export function createGoogleOAuthConfig(
+ clientId: string,
+ clientSecret: string,
+ redirectUri: string,
+ scopes: string[] = ['openid', 'profile', 'email']
+): OAuthConfig {
+ return {
+ clientId,
+ clientSecret,
+ redirectUri,
+ scopes,
+ authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
+ tokenEndpoint: 'https://oauth2.googleapis.com/token',
+ usePKCE: true,
+ };
+}
diff --git a/v3/@claude-flow/mcp/src/rate-limiter.ts b/v3/@claude-flow/mcp/src/rate-limiter.ts
new file mode 100644
index 0000000000..3b5bf3ca7f
--- /dev/null
+++ b/v3/@claude-flow/mcp/src/rate-limiter.ts
@@ -0,0 +1,266 @@
+/**
+ * @claude-flow/mcp - Rate Limiter
+ *
+ * Token bucket rate limiting for DoS protection
+ */
+
+import { EventEmitter } from 'events';
+import type { ILogger } from './types.js';
+
+export interface RateLimitConfig {
+ /** Requests per second */
+ requestsPerSecond: number;
+ /** Burst size (max tokens) */
+ burstSize: number;
+ /** Per-session limits (if different from global) */
+ perSessionLimit?: number;
+ /** Cleanup interval for expired sessions */
+ cleanupInterval?: number;
+}
+
+export interface RateLimitResult {
+ allowed: boolean;
+ remaining: number;
+ resetIn: number; // ms until bucket refills
+ retryAfter?: number; // seconds to wait (for 429 response)
+}
+
+interface TokenBucket {
+ tokens: number;
+ lastRefill: number;
+}
+
+const DEFAULT_CONFIG: RateLimitConfig = {
+ requestsPerSecond: 100,
+ burstSize: 200,
+ perSessionLimit: 50,
+ cleanupInterval: 60000, // 1 minute
+};
+
+export class RateLimiter extends EventEmitter {
+ private readonly config: Required<RateLimitConfig>;
+ private globalBucket: TokenBucket;
+ private sessionBuckets: Map<string, TokenBucket> = new Map();
+ private cleanupTimer?: NodeJS.Timeout;
+
+ constructor(
+ private readonly logger: ILogger,
+ config: Partial<RateLimitConfig> = {}
+ ) {
+ super();
+ this.config = { ...DEFAULT_CONFIG, ...config } as Required<RateLimitConfig>;
+
+ // Initialize global bucket
+ this.globalBucket = {
+ tokens: this.config.burstSize,
+ lastRefill: Date.now(),
+ };
+
+ this.startCleanup();
+ }
+
+ /**
+ * Check if request is allowed (global limit)
+ */
+ checkGlobal(): RateLimitResult {
+ return this.checkBucket(this.globalBucket, this.config.requestsPerSecond, this.config.burstSize);
+ }
+
+ /**
+ * Check if request is allowed (per-session limit)
+ */
+ checkSession(sessionId: string): RateLimitResult {
+ let bucket = this.sessionBuckets.get(sessionId);
+ if (!bucket) {
+ bucket = {
+ tokens: this.config.perSessionLimit,
+ lastRefill: Date.now(),
+ };
+ this.sessionBuckets.set(sessionId, bucket);
+ }
+
+ return this.checkBucket(
+ bucket,
+ this.config.perSessionLimit / 10, // Refill rate (10 seconds to full)
+ this.config.perSessionLimit
+ );
+ }
+
+ /**
+ * Check both global and session limits
+ */
+ check(sessionId?: string): RateLimitResult {
+ const globalResult = this.checkGlobal();
+ if (!globalResult.allowed) {
+ this.emit('rate-limit:global', { remaining: globalResult.remaining });
+ return globalResult;
+ }
+
+ if (sessionId) {
+ const sessionResult = this.checkSession(sessionId);
+ if (!sessionResult.allowed) {
+ this.emit('rate-limit:session', { sessionId, remaining: sessionResult.remaining });
+ return sessionResult;
+ }
+ return sessionResult;
+ }
+
+ return globalResult;
+ }
+
+ /**
+ * Consume a token (call after request is processed)
+ */
+ consume(sessionId?: string): void {
+ this.consumeFromBucket(this.globalBucket);
+ if (sessionId) {
+ const bucket = this.sessionBuckets.get(sessionId);
+ if (bucket) {
+ this.consumeFromBucket(bucket);
+ }
+ }
+ }
+
+ /**
+ * Reset session bucket
+ */
+ resetSession(sessionId: string): void {
+ this.sessionBuckets.delete(sessionId);
+ this.logger.debug('Rate limit session reset', { sessionId });
+ }
+
+ /**
+ * Get current stats
+ */
+ getStats(): {
+ globalTokens: number;
+ globalBurstSize: number;
+ sessionCount: number;
+ config: RateLimitConfig;
+ } {
+ this.refillBucket(this.globalBucket, this.config.requestsPerSecond, this.config.burstSize);
+ return {
+ globalTokens: Math.floor(this.globalBucket.tokens),
+ globalBurstSize: this.config.burstSize,
+ sessionCount: this.sessionBuckets.size,
+ config: this.config,
+ };
+ }
+
+ /**
+ * Destroy the rate limiter
+ */
+ destroy(): void {
+ if (this.cleanupTimer) {
+ clearInterval(this.cleanupTimer);
+ this.cleanupTimer = undefined;
+ }
+ this.sessionBuckets.clear();
+ this.removeAllListeners();
+ }
+
+ /**
+ * Check bucket and refill tokens
+ */
+ private checkBucket(
+ bucket: TokenBucket,
+ refillRate: number,
+ maxTokens: number
+ ): RateLimitResult {
+ this.refillBucket(bucket, refillRate, maxTokens);
+
+ if (bucket.tokens >= 1) {
+ return {
+ allowed: true,
+ remaining: Math.floor(bucket.tokens) - 1,
+ resetIn: Math.ceil((maxTokens - bucket.tokens) / refillRate * 1000),
+ };
+ }
+
+ // Calculate when bucket will have 1 token
+ const tokensNeeded = 1 - bucket.tokens;
+ const retryAfter = Math.ceil(tokensNeeded / refillRate);
+
+ return {
+ allowed: false,
+ remaining: 0,
+ resetIn: retryAfter * 1000,
+ retryAfter,
+ };
+ }
+
+ /**
+ * Refill tokens based on elapsed time
+ */
+ private refillBucket(bucket: TokenBucket, refillRate: number, maxTokens: number): void {
+ const now = Date.now();
+ const elapsed = (now - bucket.lastRefill) / 1000; // seconds
+ const tokensToAdd = elapsed * refillRate;
+
+ bucket.tokens = Math.min(maxTokens, bucket.tokens + tokensToAdd);
+ bucket.lastRefill = now;
+ }
+
+ /**
+ * Consume a token from bucket
+ */
+ private consumeFromBucket(bucket: TokenBucket): void {
+ if (bucket.tokens >= 1) {
+ bucket.tokens -= 1;
+ }
+ }
+
+ /**
+ * Start cleanup timer for expired sessions
+ */
+ private startCleanup(): void {
+ this.cleanupTimer = setInterval(() => {
+ const now = Date.now();
+ const expireTime = this.config.cleanupInterval * 2;
+
+ for (const [sessionId, bucket] of this.sessionBuckets) {
+ if (now - bucket.lastRefill > expireTime) {
+ this.sessionBuckets.delete(sessionId);
+ this.logger.debug('Rate limit session expired', { sessionId });
+ }
+ }
+ }, this.config.cleanupInterval);
+ }
+}
+
+export function createRateLimiter(
+ logger: ILogger,
+ config?: Partial<RateLimitConfig>
+): RateLimiter {
+ return new RateLimiter(logger, config);
+}
+
+/**
+ * Express/Connect middleware for rate limiting
+ */
+export function rateLimitMiddleware(rateLimiter: RateLimiter) {
+ return (req: any, res: any, next: () => void) => {
+ const sessionId = req.headers['x-session-id'] || req.ip;
+ const result = rateLimiter.check(sessionId);
+
+ res.setHeader('X-RateLimit-Remaining', result.remaining);
+ res.setHeader('X-RateLimit-Reset', Math.ceil(Date.now() / 1000) + Math.ceil(result.resetIn / 1000));
+
+ if (!result.allowed) {
+ res.setHeader('Retry-After', result.retryAfter);
+ res.status(429).json({
+ jsonrpc: '2.0',
+ id: null,
+ error: {
+ code: -32000,
+ message: 'Rate limit exceeded',
+ data: { retryAfter: result.retryAfter },
+ },
+ });
+ return;
+ }
+
+ rateLimiter.consume(sessionId);
+ next();
+ };
+}
diff --git a/v3/@claude-flow/mcp/src/sampling.ts b/v3/@claude-flow/mcp/src/sampling.ts
new file mode 100644
index 0000000000..d47d2c3dcc
--- /dev/null
+++ b/v3/@claude-flow/mcp/src/sampling.ts
@@ -0,0 +1,363 @@
+/**
+ * @claude-flow/mcp - Sampling (Server-Initiated LLM)
+ *
+ * MCP 2025-11-25 compliant sampling for server-initiated LLM calls
+ */
+
+import { EventEmitter } from 'events';
+import type {
+ SamplingMessage,
+ ModelPreferences,
+ CreateMessageRequest,
+ CreateMessageResult,
+ PromptContent,
+ ILogger,
+} from './types.js';
+
+/**
+ * External LLM provider interface
+ */
+export interface LLMProvider {
+ name: string;
+ createMessage(request: CreateMessageRequest): Promise<CreateMessageResult>;
+ isAvailable(): Promise<boolean>;
+}
+
+/**
+ * Sampling configuration
+ */
+export interface SamplingConfig {
+ /** Default model preferences */
+ defaultModelPreferences?: ModelPreferences;
+ /** Maximum tokens for any request */
+ maxTokensLimit?: number;
+ /** Default temperature */
+ defaultTemperature?: number;
+ /** Timeout for LLM calls (ms) */
+ timeout?: number;
+ /** Enable request logging */
+ enableLogging?: boolean;
+}
+
+/**
+ * Sampling request context
+ */
+export interface SamplingContext {
+ sessionId: string;
+ serverId?: string;
+ metadata?: Record<string, unknown>;
+}
+
+const DEFAULT_CONFIG: Required<SamplingConfig> = {
+ defaultModelPreferences: {
+ intelligencePriority: 0.5,
+ speedPriority: 0.3,
+ costPriority: 0.2,
+ },
+ maxTokensLimit: 4096,
+ defaultTemperature: 0.7,
+ timeout: 30000,
+ enableLogging: true,
+};
+
+export class SamplingManager extends EventEmitter {
+ private readonly config: Required<SamplingConfig>;
+ private providers: Map<string, LLMProvider> = new Map();
+ private defaultProvider?: string;
+ private requestCount = 0;
+ private totalTokens = 0;
+
+ constructor(
+ private readonly logger: ILogger,
+ config: Partial<SamplingConfig> = {}
+ ) {
+ super();
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
+
+ /**
+ * Register an LLM provider
+ */
+ registerProvider(provider: LLMProvider, isDefault: boolean = false): void {
+ this.providers.set(provider.name, provider);
+ if (isDefault || !this.defaultProvider) {
+ this.defaultProvider = provider.name;
+ }
+ this.logger.info('LLM provider registered', { name: provider.name, isDefault });
+ this.emit('provider:registered', { name: provider.name });
+ }
+
+ /**
+ * Unregister a provider
+ */
+ unregisterProvider(name: string): boolean {
+ const removed = this.providers.delete(name);
+ if (removed && this.defaultProvider === name) {
+ this.defaultProvider = this.providers.keys().next().value;
+ }
+ return removed;
+ }
+
+ /**
+ * Create a message (sampling/createMessage)
+ */
+ async createMessage(
+ request: CreateMessageRequest,
+ context?: SamplingContext
+ ): Promise<CreateMessageResult> {
+ const startTime = Date.now();
+ this.requestCount++;
+
+ // Validate request
+ this.validateRequest(request);
+
+ // Select provider
+ const provider = this.selectProvider(request.modelPreferences);
+ if (!provider) {
+ throw new Error('No LLM provider available');
+ }
+
+ // Apply defaults
+ const fullRequest = this.applyDefaults(request);
+
+ if (this.config.enableLogging) {
+ this.logger.debug('Sampling request', {
+ provider: provider.name,
+ messageCount: request.messages.length,
+ maxTokens: fullRequest.maxTokens,
+ sessionId: context?.sessionId,
+ });
+ }
+
+ this.emit('sampling:start', { provider: provider.name, context });
+
+ try {
+ // Call provider with timeout
+ const result = await this.callWithTimeout(
+ provider.createMessage(fullRequest),
+ this.config.timeout
+ );
+
+ const duration = Date.now() - startTime;
+
+ if (this.config.enableLogging) {
+ this.logger.info('Sampling complete', {
+ provider: provider.name,
+ duration: `${duration}ms`,
+ stopReason: result.stopReason,
+ });
+ }
+
+ this.emit('sampling:complete', {
+ provider: provider.name,
+ duration,
+ result,
+ context,
+ });
+
+ return result;
+ } catch (error) {
+ const duration = Date.now() - startTime;
+
+ this.logger.error('Sampling failed', {
+ provider: provider.name,
+ duration: `${duration}ms`,
+ error,
+ });
+
+ this.emit('sampling:error', {
+ provider: provider.name,
+ duration,
+ error,
+ context,
+ });
+
+ throw error;
+ }
+ }
+
+ /**
+ * Check if sampling is available
+ */
+ async isAvailable(): Promise<boolean> {
+ if (this.providers.size === 0) {
+ return false;
+ }
+
+ for (const provider of this.providers.values()) {
+ if (await provider.isAvailable()) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Get available providers
+ */
+ getProviders(): string[] {
+ return Array.from(this.providers.keys());
+ }
+
+ /**
+ * Get stats
+ */
+ getStats(): {
+ requestCount: number;
+ totalTokens: number;
+ providerCount: number;
+ defaultProvider?: string;
+ } {
+ return {
+ requestCount: this.requestCount,
+ totalTokens: this.totalTokens,
+ providerCount: this.providers.size,
+ defaultProvider: this.defaultProvider,
+ };
+ }
+
+ /**
+ * Validate sampling request
+ */
+ private validateRequest(request: CreateMessageRequest): void {
+ if (!request.messages || request.messages.length === 0) {
+ throw new Error('Messages are required');
+ }
+
+ if (request.maxTokens > this.config.maxTokensLimit) {
+ throw new Error(`maxTokens exceeds limit of ${this.config.maxTokensLimit}`);
+ }
+
+ if (request.temperature !== undefined && (request.temperature < 0 || request.temperature > 2)) {
+ throw new Error('Temperature must be between 0 and 2');
+ }
+ }
+
+ /**
+ * Select provider based on preferences
+ */
+ private selectProvider(preferences?: ModelPreferences): LLMProvider | undefined {
+ // If hints provided, try to find matching provider
+ if (preferences?.hints) {
+ for (const hint of preferences.hints) {
+ if (hint.name && this.providers.has(hint.name)) {
+ return this.providers.get(hint.name);
+ }
+ }
+ }
+
+ // Use default provider
+ if (this.defaultProvider) {
+ return this.providers.get(this.defaultProvider);
+ }
+
+ // Return first available
+ return this.providers.values().next().value;
+ }
+
+ /**
+ * Apply default values to request
+ */
+ private applyDefaults(request: CreateMessageRequest): CreateMessageRequest {
+ return {
+ ...request,
+ modelPreferences: request.modelPreferences || this.config.defaultModelPreferences,
+ temperature: request.temperature ?? this.config.defaultTemperature,
+ maxTokens: Math.min(request.maxTokens, this.config.maxTokensLimit),
+ };
+ }
+
+ /**
+ * Call with timeout
+ */
+ private async callWithTimeout<T>(promise: Promise<T>, timeout: number): Promise<T> {
+ return Promise.race([
+ promise,
+ new Promise<T>((_, reject) => {
+ setTimeout(() => reject(new Error('Sampling timeout')), timeout);
+ }),
+ ]);
+ }
+}
+
+export function createSamplingManager(
+ logger: ILogger,
+ config?: Partial<SamplingConfig>
+): SamplingManager {
+ return new SamplingManager(logger, config);
+}
+
+/**
+ * Create a mock LLM provider for testing
+ */
+export function createMockProvider(name: string = 'mock'): LLMProvider {
+ return {
+ name,
+ async createMessage(request: CreateMessageRequest): Promise<CreateMessageResult> {
+ // Simulate processing time
+ await new Promise((r) => setTimeout(r, 100));
+
+ return {
+ role: 'assistant',
+ content: {
+ type: 'text',
+ text: `Mock response to: ${JSON.stringify(request.messages[0]?.content)}`,
+ },
+ model: `${name}-model`,
+ stopReason: 'endTurn',
+ };
+ },
+ async isAvailable(): Promise<boolean> {
+ return true;
+ },
+ };
+}
+
+/**
+ * Create an Anthropic provider (requires API key)
+ */
+export function createAnthropicProvider(apiKey: string): LLMProvider {
+ return {
+ name: 'anthropic',
+ async createMessage(request: CreateMessageRequest): Promise<CreateMessageResult> {
+ const response = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-api-key': apiKey,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: 'claude-3-haiku-20240307',
+ max_tokens: request.maxTokens,
+ temperature: request.temperature,
+ system: request.systemPrompt,
+ messages: request.messages.map((m) => ({
+ role: m.role,
+ content: m.content.type === 'text' ? (m.content as any).text : m.content,
+ })),
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Anthropic API error: ${response.status}`);
+ }
+
+ const data = await response.json() as any;
+
+ return {
+ role: 'assistant',
+ content: {
+ type: 'text',
+ text: data.content[0]?.text || '',
+ },
+ model: data.model,
+ stopReason: data.stop_reason === 'end_turn' ? 'endTurn' : 'maxTokens',
+ };
+ },
+ async isAvailable(): Promise<boolean> {
+ return !!apiKey;
+ },
+ };
+}
diff --git a/v3/@claude-flow/mcp/src/schema-validator.ts b/v3/@claude-flow/mcp/src/schema-validator.ts
new file mode 100644
index 0000000000..f2550154ea
--- /dev/null
+++ b/v3/@claude-flow/mcp/src/schema-validator.ts
@@ -0,0 +1,213 @@
+/**
+ * @claude-flow/mcp - JSON Schema Validator
+ *
+ * Lightweight JSON Schema validation for tool inputs
+ * Implements JSON Schema Draft 2020-12 subset
+ */
+
+import type { JSONSchema } from './types.js';
+
+export interface ValidationError {
+ path: string;
+ message: string;
+ keyword: string;
+ params?: Record<string, unknown>;
+}
+
+export interface ValidationResult {
+ valid: boolean;
+ errors: ValidationError[];
+}
+
+/**
+ * Validate data against JSON Schema
+ */
+export function validateSchema(
+ data: unknown,
+ schema: JSONSchema,
+ path: string = ''
+): ValidationResult {
+ const errors: ValidationError[] = [];
+
+ // Type validation
+ if (schema.type) {
+ const typeValid = validateType(data, schema.type);
+ if (!typeValid) {
+ errors.push({
+ path: path || 'root',
+ message: `Expected type "${schema.type}", got "${typeof data}"`,
+ keyword: 'type',
+ params: { expected: schema.type, actual: typeof data },
+ });
+ return { valid: false, errors };
+ }
+ }
+
+ // Null check
+ if (data === null || data === undefined) {
+ if (schema.type && schema.type !== 'null') {
+ errors.push({
+ path: path || 'root',
+ message: 'Value cannot be null or undefined',
+ keyword: 'type',
+ });
+ }
+ return { valid: errors.length === 0, errors };
+ }
+
+ // String validations
+ if (schema.type === 'string' && typeof data === 'string') {
+ if (schema.minLength !== undefined && data.length < schema.minLength) {
+ errors.push({
+ path,
+ message: `String length must be >= ${schema.minLength}`,
+ keyword: 'minLength',
+ params: { limit: schema.minLength, actual: data.length },
+ });
+ }
+ if (schema.maxLength !== undefined && data.length > schema.maxLength) {
+ errors.push({
+ path,
+ message: `String length must be <= ${schema.maxLength}`,
+ keyword: 'maxLength',
+ params: { limit: schema.maxLength, actual: data.length },
+ });
+ }
+ if (schema.pattern) {
+ const regex = new RegExp(schema.pattern);
+ if (!regex.test(data)) {
+ errors.push({
+ path,
+ message: `String must match pattern "${schema.pattern}"`,
+ keyword: 'pattern',
+ params: { pattern: schema.pattern },
+ });
+ }
+ }
+ if (schema.enum && !schema.enum.includes(data)) {
+ errors.push({
+ path,
+ message: `Value must be one of: ${schema.enum.join(', ')}`,
+ keyword: 'enum',
+ params: { allowedValues: schema.enum },
+ });
+ }
+ }
+
+ // Number validations
+ if ((schema.type === 'number' || schema.type === 'integer') && typeof data === 'number') {
+ if (schema.type === 'integer' && !Number.isInteger(data)) {
+ errors.push({
+ path,
+ message: 'Value must be an integer',
+ keyword: 'type',
+ });
+ }
+ if (schema.minimum !== undefined && data < schema.minimum) {
+ errors.push({
+ path,
+ message: `Value must be >= ${schema.minimum}`,
+ keyword: 'minimum',
+ params: { limit: schema.minimum, actual: data },
+ });
+ }
+ if (schema.maximum !== undefined && data > schema.maximum) {
+ errors.push({
+ path,
+ message: `Value must be <= ${schema.maximum}`,
+ keyword: 'maximum',
+ params: { limit: schema.maximum, actual: data },
+ });
+ }
+ }
+
+ // Array validations
+ if (schema.type === 'array' && Array.isArray(data)) {
+ if (schema.items) {
+ for (let i = 0; i < data.length; i++) {
+ const itemResult = validateSchema(data[i], schema.items, `${path}[${i}]`);
+ errors.push(...itemResult.errors);
+ }
+ }
+ }
+
+ // Object validations
+ if (schema.type === 'object' && typeof data === 'object' && !Array.isArray(data)) {
+ const obj = data as Record<string, unknown>;
+
+ // Required properties
+ if (schema.required) {
+ for (const requiredProp of schema.required) {
+ if (!(requiredProp in obj)) {
+ errors.push({
+ path: path ? `${path}.${requiredProp}` : requiredProp,
+ message: `Required property "${requiredProp}" is missing`,
+ keyword: 'required',
+ params: { missingProperty: requiredProp },
+ });
+ }
+ }
+ }
+
+ // Property validations
+ if (schema.properties) {
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
+ if (propName in obj) {
+ const propPath = path ? `${path}.${propName}` : propName;
+ const propResult = validateSchema(obj[propName], propSchema, propPath);
+ errors.push(...propResult.errors);
+ }
+ }
+ }
+
+ // Additional properties check
+ if (schema.additionalProperties === false && schema.properties) {
+ const allowedProps = new Set(Object.keys(schema.properties));
+ for (const propName of Object.keys(obj)) {
+ if (!allowedProps.has(propName)) {
+ errors.push({
+ path: path ? `${path}.${propName}` : propName,
+ message: `Additional property "${propName}" is not allowed`,
+ keyword: 'additionalProperties',
+ params: { additionalProperty: propName },
+ });
+ }
+ }
+ }
+ }
+
+ return { valid: errors.length === 0, errors };
+}
+
+/**
+ * Validate type
+ */
+function validateType(data: unknown, expectedType: string): boolean {
+ if (expectedType === 'null') {
+ return data === null;
+ }
+ if (expectedType === 'array') {
+ return Array.isArray(data);
+ }
+ if (expectedType === 'integer') {
+ return typeof data === 'number' && Number.isInteger(data);
+ }
+ if (expectedType === 'object') {
+ return typeof data === 'object' && data !== null && !Array.isArray(data);
+ }
+ return typeof data === expectedType;
+}
+
+/**
+ * Format validation errors for display
+ */
+export function formatValidationErrors(errors: ValidationError[]): string {
+ return errors.map((e) => `${e.path}: ${e.message}`).join('; ');
+}
+
+/**
+ * Create a validator function for a specific schema
+ */
+export function createValidator(schema: JSONSchema): (data: unknown) => ValidationResult {
+ return (data: unknown) => validateSchema(data, schema);
+}
diff --git a/v3/@claude-flow/mcp/src/server.ts b/v3/@claude-flow/mcp/src/server.ts
index 5f04520ab0..87279aa2a9 100644
--- a/v3/@claude-flow/mcp/src/server.ts
+++ b/v3/@claude-flow/mcp/src/server.ts
@@ -31,6 +31,8 @@ import { ResourceRegistry, createResourceRegistry } from './resource-registry.js
import { PromptRegistry, createPromptRegistry } from './prompt-registry.js';
import { TaskManager, createTaskManager } from './task-manager.js';
import { createTransport, TransportManager, createTransportManager } from './transport/index.js';
+import { RateLimiter, createRateLimiter, type RateLimitConfig } from './rate-limiter.js';
+import { SamplingManager, createSamplingManager, type SamplingConfig, type LLMProvider } from './sampling.js';
const DEFAULT_CONFIG: Partial<MCPServerConfig> = {
name: 'Claude-Flow MCP Server V3',
@@ -71,6 +73,8 @@ export class MCPServer extends EventEmitter implements IMCPServer {
private readonly taskManager: TaskManager;
private readonly connectionPool?: ConnectionPool;
private readonly transportManager: TransportManager;
+ private readonly rateLimiter: RateLimiter;
+ private readonly samplingManager: SamplingManager;
private transport?: ITransport;
private running = false;
private startTime?: Date;
@@ -91,11 +95,12 @@ export class MCPServer extends EventEmitter implements IMCPServer {
};
// Full MCP 2025-11-25 capabilities
- private readonly capabilities: MCPCapabilities = {
+ private capabilities: MCPCapabilities = {
logging: { level: 'info' },
tools: { listChanged: true },
resources: { listChanged: true, subscribe: true },
prompts: { listChanged: true },
+ sampling: {},
};
private requestStats = {
@@ -130,6 +135,12 @@ export class MCPServer extends EventEmitter implements IMCPServer {
taskTimeout: 300000,
});
this.transportManager = createTransportManager(logger);
+ this.rateLimiter = createRateLimiter(logger, {
+ requestsPerSecond: 100,
+ burstSize: 200,
+ perSessionLimit: 50,
+ });
+ this.samplingManager = createSamplingManager(logger);
if (this.config.connectionPool) {
this.connectionPool = createConnectionPool(
@@ -163,6 +174,27 @@ export class MCPServer extends EventEmitter implements IMCPServer {
return this.taskManager;
}
+ /**
+ * Get rate limiter for configuration
+ */
+ getRateLimiter(): RateLimiter {
+ return this.rateLimiter;
+ }
+
+ /**
+ * Get sampling manager for LLM provider registration
+ */
+ getSamplingManager(): SamplingManager {
+ return this.samplingManager;
+ }
+
+ /**
+ * Register an LLM provider for sampling
+ */
+ registerLLMProvider(provider: LLMProvider, isDefault: boolean = false): void {
+ this.samplingManager.registerProvider(provider, isDefault);
+ }
+
async start(): Promise<void> {
if (this.running) {
throw new MCPServerError('Server already running');
@@ -235,6 +267,7 @@ export class MCPServer extends EventEmitter implements IMCPServer {
this.sessionManager.clearAll();
this.taskManager.destroy();
this.resourceSubscriptions.clear();
+ this.rateLimiter.destroy();
if (this.connectionPool) {
await this.connectionPool.clear();
@@ -354,6 +387,25 @@ export class MCPServer extends EventEmitter implements IMCPServer {
method: request.method,
});
+ // Rate limiting check (skip for initialize)
+ if (request.method !== 'initialize') {
+ const sessionId = this.currentSession?.id;
+ const rateLimitResult = this.rateLimiter.check(sessionId);
+ if (!rateLimitResult.allowed) {
+ this.requestStats.failed++;
+ return {
+ jsonrpc: '2.0',
+ id: request.id,
+ error: {
+ code: -32000,
+ message: 'Rate limit exceeded',
+ data: { retryAfter: rateLimitResult.retryAfter },
+ },
+ };
+ }
+ this.rateLimiter.consume(sessionId);
+ }
+
try {
if (request.method === 'initialize') {
return await this.handleInitialize(request);
@@ -493,6 +545,10 @@ export class MCPServer extends EventEmitter implements IMCPServer {
case 'logging/setLevel':
return this.handleLoggingSetLevel(request);
+ // Sampling (MCP 2025-11-25)
+ case 'sampling/createMessage':
+ return this.handleSamplingCreateMessage(request);
+
// Utility
case 'ping':
return {
@@ -872,6 +928,75 @@ export class MCPServer extends EventEmitter implements IMCPServer {
};
}
+ // ============================================================================
+ // Sampling Handler (MCP 2025-11-25)
+ // ============================================================================
+
+ private async handleSamplingCreateMessage(request: MCPRequest): Promise<MCPResponse> {
+ const params = request.params as {
+ messages: Array<{ role: string; content: { type: string; text?: string } }>;
+ maxTokens: number;
+ systemPrompt?: string;
+ modelPreferences?: { hints?: Array<{ name?: string }>; intelligencePriority?: number; speedPriority?: number; costPriority?: number };
+ includeContext?: string;
+ temperature?: number;
+ stopSequences?: string[];
+ metadata?: Record<string, unknown>;
+ } | undefined;
+
+ if (!params?.messages || !params?.maxTokens) {
+ return this.createErrorResponse(
+ request.id,
+ ErrorCodes.INVALID_PARAMS,
+ 'messages and maxTokens are required'
+ );
+ }
+
+ // Check if sampling is available
+ const available = await this.samplingManager.isAvailable();
+ if (!available) {
+ return this.createErrorResponse(
+ request.id,
+ ErrorCodes.INTERNAL_ERROR,
+ 'No LLM provider available for sampling'
+ );
+ }
+
+ try {
+ const result = await this.samplingManager.createMessage(
+ {
+ messages: params.messages.map((m) => ({
+ role: m.role as 'user' | 'assistant',
+ content: m.content as any,
+ })),
+ maxTokens: params.maxTokens,
+ systemPrompt: params.systemPrompt,
+ modelPreferences: params.modelPreferences,
+ includeContext: params.includeContext as 'none' | 'thisServer' | 'allServers' | undefined,
+ temperature: params.temperature,
+ stopSequences: params.stopSequences,
+ metadata: params.metadata,
+ },
+ {
+ sessionId: this.currentSession?.id || 'unknown',
+ serverId: this.serverInfo.name,
+ }
+ );
+
+ return {
+ jsonrpc: '2.0',
+ id: request.id,
+ result,
+ };
+ } catch (error) {
+ return this.createErrorResponse(
+ request.id,
+ ErrorCodes.INTERNAL_ERROR,
+ error instanceof Error ? error.message : 'Sampling failed'
+ );
+ }
+ }
+
// ============================================================================
// Notification Sender
// ============================================================================
diff --git a/v3/@claude-flow/mcp/src/tool-registry.ts b/v3/@claude-flow/mcp/src/tool-registry.ts
index 0fb82399b9..187737b896 100644
--- a/v3/@claude-flow/mcp/src/tool-registry.ts
+++ b/v3/@claude-flow/mcp/src/tool-registry.ts
@@ -14,6 +14,7 @@ import type {
ToolRegistrationOptions,
ILogger,
} from './types.js';
+import { validateSchema, formatValidationErrors } from './schema-validator.js';
interface ToolMetadata {
tool: MCPTool;
@@ -281,6 +282,22 @@ export class ToolRegistry extends EventEmitter {
};
}
+ // Validate input against schema (security feature)
+ if (metadata.tool.inputSchema) {
+ const validation = validateSchema(input, metadata.tool.inputSchema);
+ if (!validation.valid) {
+ const errorMsg = formatValidationErrors(validation.errors);
+ this.logger.warn('Tool input validation failed', {
+ name,
+ errors: validation.errors,
+ });
+ return {
+ content: [{ type: 'text', text: `Invalid input: ${errorMsg}` }],
+ isError: true,
+ };
+ }
+ }
+
const execContext: ToolContext = {
sessionId: context?.sessionId || this.defaultContext?.sessionId || 'default-session',
...this.defaultContext,
diff --git a/v3/@claude-flow/mcp/src/types.ts b/v3/@claude-flow/mcp/src/types.ts
index e18e753dc0..228ea6743f 100644
--- a/v3/@claude-flow/mcp/src/types.ts
+++ b/v3/@claude-flow/mcp/src/types.ts
@@ -155,6 +155,7 @@ export interface MCPCapabilities {
prompts?: {
listChanged: boolean;
};
+ sampling?: Record<string, unknown>;
experimental?: Record<string, unknown>;
}
diff --git a/v3/docs/adr/ADR-011-llm-provider-system.md b/v3/docs/adr/ADR-011-llm-provider-system.md
index da915db161..2c200240af 100644
--- a/v3/docs/adr/ADR-011-llm-provider-system.md
+++ b/v3/docs/adr/ADR-011-llm-provider-system.md
@@ -1,11 +1,14 @@
# ADR-011: LLM Provider System
## Status
-Accepted
+**Implemented** βœ…
## Date
2026-01-05
+## Last Updated
+2026-01-05
+
## Context
V3 needs a unified LLM provider system that:
@@ -26,13 +29,16 @@ A dedicated package for LLM provider implementations:
v3/@claude-flow/providers/
β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ types.ts # Unified type definitions
-β”‚ β”œβ”€β”€ base-provider.ts # Abstract base class
+β”‚ β”œβ”€β”€ base-provider.ts # Abstract base class with circuit breaker
β”‚ β”œβ”€β”€ anthropic-provider.ts # Claude models
-β”‚ β”œβ”€β”€ openai-provider.ts # GPT models
+β”‚ β”œβ”€β”€ openai-provider.ts # GPT models (+ OpenRouter support)
β”‚ β”œβ”€β”€ google-provider.ts # Gemini models
β”‚ β”œβ”€β”€ cohere-provider.ts # Command models
β”‚ β”œβ”€β”€ ollama-provider.ts # Local models
+β”‚ β”œβ”€β”€ ruvector-provider.ts # RuVector/ruvLLM with SONA learning
β”‚ β”œβ”€β”€ provider-manager.ts # Orchestration layer
+β”‚ β”œβ”€β”€ __tests__/ # Integration tests
+β”‚ β”‚ └── quick-test.ts # Provider test suite
β”‚ └── index.ts # Public exports
β”œβ”€β”€ package.json
└── tsconfig.json
@@ -99,6 +105,11 @@ Include latest models:
- o1-preview
- o1-mini
+**OpenRouter (via OpenAI provider):**
+- openai/gpt-4o-mini
+- anthropic/claude-3-haiku
+- Any OpenRouter-supported model
+
**Google:**
- gemini-2.0-flash
- gemini-1.5-pro
@@ -114,6 +125,14 @@ Include latest models:
- mistral
- codellama
- phi-4
+- qwen2.5 (including 0.5b, 1.5b variants)
+
+**RuVector/ruvLLM (Self-Learning Local):**
+- ruvector-auto (auto-selects optimal)
+- ruvector-fast (speed-optimized)
+- ruvector-quality (quality-optimized)
+- ruvector-balanced
+- Any Ollama model via fallback
## Consequences
@@ -135,22 +154,61 @@ Include latest models:
## Implementation Notes
-### Phase 1: Core Implementation
-1. Create package structure
-2. Implement base provider and types
-3. Implement Anthropic and OpenAI providers
-
-### Phase 2: Extended Providers
-4. Implement Google, Cohere, Ollama providers
-5. Implement provider manager
-
-### Phase 3: Hooks Integration
-6. Add LLM hooks to @claude-flow/hooks
-7. Integration testing
+### Phase 1: Core Implementation βœ… Complete
+1. βœ… Create package structure
+2. βœ… Implement base provider and types (with circuit breaker, caching)
+3. βœ… Implement Anthropic and OpenAI providers
+
+### Phase 2: Extended Providers βœ… Complete
+4. βœ… Implement Google, Cohere, Ollama providers
+5. βœ… Implement RuVector provider with Ollama fallback
+6. βœ… Implement provider manager with load balancing
+
+### Phase 3: Hooks Integration πŸ”„ Pending
+7. Add LLM hooks to @claude-flow/hooks
+8. Integration testing with hooks system
+
+## Validation Results
+
+**Test Date:** 2026-01-05
+
+| Provider | Model | Status | Notes |
+|----------|-------|--------|-------|
+| Anthropic | claude-3-haiku-20240307 | βœ… Pass | Full API integration |
+| Google | gemini-2.0-flash | βœ… Pass | Free tier, streaming support |
+| OpenRouter | openai/gpt-4o-mini | βœ… Pass | Via OpenAI-compatible API |
+| Ollama | qwen2.5:0.5b | βœ… Pass | Local CPU-friendly model |
+| RuVector | qwen2.5:0.5b | βœ… Pass | Ollama fallback working |
+| Manager | Multi-provider | βœ… Pass | Load balancing + 0ms cache |
+
+**All 6 providers passing validation.**
+
+### Key Implementation Details
+
+**BaseProvider Features:**
+- Circuit breaker pattern (failure threshold: 5, reset: 30s)
+- LRU request caching with TTL
+- Automatic retry with exponential backoff
+- Token estimation for cost calculation
+- Event emitter for monitoring
+
+**RuVector Provider:**
+- Native ruvLLM server support (port 3000, `/query` endpoint)
+- Automatic Ollama fallback when server unavailable
+- SONA self-learning integration (when available)
+- HNSW vector memory support
+- CPU-friendly model support (qwen2.5:0.5b, smollm, tinyllama)
+
+**Provider Manager:**
+- Round-robin load balancing
+- Automatic failover with configurable attempts
+- Response caching (0ms cache hits)
+- Provider health monitoring
## References
- V2 Provider System: `v2/src/providers/`
- V3 Multi-Model Router: `v3/@claude-flow/integration/src/multi-model-router.ts`
+- RuVector ruvLLM: `https://github.com/ruvnet/ruvector/tree/main/examples/ruvLLM`
- ADR-001: agentic-flow Integration
- ADR-006: Unified Memory Service
diff --git a/v3/docs/adr/ADR-012-mcp-security-features.md b/v3/docs/adr/ADR-012-mcp-security-features.md
new file mode 100644
index 0000000000..57c0adef11
--- /dev/null
+++ b/v3/docs/adr/ADR-012-mcp-security-features.md
@@ -0,0 +1,119 @@
+# ADR-012: MCP Security and Feature Implementation
+
+## Status
+Accepted
+
+## Date
+2026-01-05
+
+## Context
+
+The `@claude-flow/mcp` package implements the Model Context Protocol (MCP) 2025-11-25 specification. A security audit identified several vulnerabilities and missing features that need to be addressed to ensure production readiness.
+
+### Security Vulnerabilities Identified
+1. **Path Traversal (Critical)** - Fixed in createFileResource
+2. **ReDoS (Critical)** - Fixed with regex escaping
+3. **WebSocket Auth Bypass (High)** - Fixed with token validation
+4. **Timing Attack (Medium)** - Fixed with crypto.timingSafeEqual
+5. **Cache Exhaustion (Medium)** - Fixed with LRU eviction
+6. **Missing Tool Input Validation (High)** - Needs implementation
+7. **No Rate Limiting (Medium)** - Needs implementation
+
+### Missing MCP 2025-11-25 Features
+1. **Sampling** - Server-initiated LLM calls
+2. **OAuth 2.1** - Full authentication flow
+3. **Tool Schema Validation** - JSON Schema enforcement
+
+## Decision
+
+### 1. JSON Schema Validation for Tool Inputs
+
+**Decision**: Implement runtime JSON Schema validation using a lightweight validator.
+
+**Rationale**:
+- Tools define `inputSchema` but it wasn't enforced
+- Invalid inputs can cause crashes or security issues
+- Schema validation provides defense-in-depth
+
+**Implementation**:
+```typescript
+// Validate before execution
+const validationResult = validateSchema(input, tool.inputSchema);
+if (!validationResult.valid) {
+ throw new MCPServerError('Invalid input', ErrorCodes.INVALID_PARAMS, validationResult.errors);
+}
+```
+
+### 2. Sampling (Server-Initiated LLM Calls)
+
+**Decision**: Implement `sampling/createMessage` per MCP 2025-11-25 spec.
+
+**Rationale**:
+- Required for servers that need to invoke LLM during tool execution
+- Enables agentic workflows where server needs AI assistance
+- Part of complete MCP 2025-11-25 compliance
+
+**Implementation**:
+- Add `SamplingHandler` callback to server config
+- Implement `sampling/createMessage` method
+- Support model preferences and context inclusion
+
+### 3. Rate Limiting
+
+**Decision**: Implement token bucket rate limiting with configurable limits.
+
+**Rationale**:
+- Prevents DoS attacks
+- Protects against runaway clients
+- Industry standard for API security
+
+**Implementation**:
+- Token bucket algorithm (efficient, fair)
+- Per-session and global limits
+- Configurable via `rateLimitConfig`
+- Returns 429 with Retry-After header
+
+### 4. OAuth 2.1 Flow
+
+**Decision**: Implement OAuth 2.1 with PKCE for secure authentication.
+
+**Rationale**:
+- Industry standard for API authentication
+- Required for enterprise deployments
+- More secure than static tokens
+
+**Implementation**:
+- Authorization code flow with PKCE
+- Token refresh support
+- Configurable providers (custom, GitHub, Google)
+
+## Consequences
+
+### Positive
+- Full MCP 2025-11-25 compliance
+- Production-ready security posture
+- Enterprise authentication support
+- Protection against common attacks
+
+### Negative
+- Increased complexity
+- Additional dependencies (ajv for schema validation)
+- Slight performance overhead for validation
+
+### Risks
+- OAuth implementation complexity
+- Rate limiting tuning for different use cases
+
+## Implementation Plan
+
+1. **Phase 1**: JSON Schema validation (security priority)
+2. **Phase 2**: Rate limiting (security priority)
+3. **Phase 3**: Sampling support (feature)
+4. **Phase 4**: OAuth 2.1 (feature)
+
+## References
+
+- [MCP 2025-11-25 Specification](https://modelcontextprotocol.io/specification/2025-11-25)
+- [OAuth 2.1 Draft](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-07)
+- [JSON Schema Validation](https://json-schema.org/draft/2020-12/json-schema-validation.html)
+- [Token Bucket Algorithm](https://en.wikipedia.org/wiki/Token_bucket)
diff --git a/v3/implementation/adrs/v3-adrs.md b/v3/implementation/adrs/v3-adrs.md
index 55dbd1ded4..78619df954 100644
--- a/v3/implementation/adrs/v3-adrs.md
+++ b/v3/implementation/adrs/v3-adrs.md
@@ -21,6 +21,8 @@
| ADR-008 | Vitest Over Jest | Proposed | 2026-01-03 |
| ADR-009 | Hybrid Memory Backend as Default | Proposed | 2026-01-03 |
| ADR-010 | Remove Deno Support | Proposed | 2026-01-03 |
+| ADR-011 | LLM Provider System | **Implemented** βœ… | 2026-01-05 |
+| ADR-012 | MCP Security Features | Proposed | 2026-01-05 |
---
@@ -917,5 +919,5 @@ Links to other ADRs
---
**Document Maintained By:** Architecture Team
-**Last Updated:** 2026-01-03
+**Last Updated:** 2026-01-05
**Next Review:** After Sprint 4 (2026-02-01)