Spaces:
Running

mcp-webcam / server /state /activity.ts
evalstate's picture
evalstate HF Staff
Deploy mcp-webcam v0.3.0 (stateless MCP 2026-07-28 + SEP-3415 Events + Studio UI)
6f5f15e verified
Raw History Blame Contribute Delete
20.6 kB
import {
CLIENT_CAPABILITIES_META_KEY,
CLIENT_INFO_META_KEY,
PROTOCOL_VERSION_META_KEY,
type Implementation,
type ServerContext,
} from '@modelcontextprotocol/server';
import type {
ActivityEntry,
ActivityKind,
CallerView,
ClientIdentity,
DashboardState,
Era,
McpTransportKind,
} from '../../shared/api-types.js';
import type { ActivityApi, RoomChanges } from '../contracts.js';
import { EVENTS_EXTENSION_ID } from '../events/protocol.js';
import { getRequestRemoteAddress } from '../mcp/identity.js';
const MODERN_PROTOCOL = '2026-07-28';
const DEFAULT_FINGERPRINT_TTL_MS = 30 * 60 * 1000;
const DEFAULT_MAX_ACTIVITY = 100;
const DEFAULT_MAX_CALLERS = 100;
const CALLER_ACTIVE_MS = 60 * 1000;
const CALLER_IDLE_MS = 5 * 60 * 1000;
interface FingerprintEntry {
clientInfo: Implementation;
protocolVersion?: string;
eventsCapable?: boolean;
expiresAt: number;
}
export class LegacyFingerprintCache {
private readonly entries = new Map<string, FingerprintEntry>();
private readonly ttlMs: number;
private readonly now: () => number;
constructor(opts?: { ttlMs?: number; now?: () => number }) {
this.ttlMs = opts?.ttlMs ?? DEFAULT_FINGERPRINT_TTL_MS;
this.now = opts?.now ?? (() => Date.now());
}
private key(user: string, userAgent?: string, remoteAddress?: string): string {
return `${user}|${userAgent ?? ''}|${remoteAddress ?? ''}`;
}
remember(
user: string,
userAgent: string | undefined,
remoteAddress: string | undefined,
info: { clientInfo: Implementation; protocolVersion?: string; eventsCapable?: boolean },
): void {
const k = this.key(user, userAgent, remoteAddress);
this.entries.set(k, {
...info,
expiresAt: this.now() + this.ttlMs,
});
}
lookup(
user: string,
userAgent: string | undefined,
remoteAddress: string | undefined,
): Omit<FingerprintEntry, 'expiresAt'> | undefined {
const k = this.key(user, userAgent, remoteAddress);
const entry = this.entries.get(k);
if (!entry) return undefined;
if (this.now() > entry.expiresAt) {
this.entries.delete(k);
return undefined;
}
return {
clientInfo: entry.clientInfo,
protocolVersion: entry.protocolVersion,
eventsCapable: entry.eventsCapable,
};
}
clear(): void {
this.entries.clear();
}
}
export interface ActivityTrackerOptions {
user?: string;
changes?: RoomChanges;
now?: () => number;
fingerprintTtlMs?: number;
maxActivity?: number;
maxCallers?: number;
}
export type ActivityTracker = ActivityApi & {
clear(): void;
markStdioClosed(): void;
};
interface CallerRecord {
client: ClientIdentity;
firstSeenAt: string;
lastSeenAt: string;
lastSeenMs: number;
requests: number;
lastMethod: string;
lastDetail?: string;
lastResponse?: CallerView['lastResponse'];
methods: Record<string, number>;
open?: boolean;
}
interface JsonRpcLike {
id?: string | number | null;
method?: string;
params?: Record<string, unknown>;
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function extractClientInfo(value: unknown): Implementation | undefined {
const rec = asRecord(value);
if (!rec || typeof rec.name !== 'string' || !rec.name) return undefined;
return {
name: rec.name,
version: typeof rec.version === 'string' ? rec.version : '',
...(typeof rec.title === 'string' ? { title: rec.title } : {}),
};
}
function hasEventsCapability(capabilities: unknown): boolean {
const caps = asRecord(capabilities);
const exts = asRecord(caps?.extensions);
return exts !== undefined && EVENTS_EXTENSION_ID in exts;
}
function parseUserAgentToken(ua?: string): { name: string; version?: string } | undefined {
if (!ua) return undefined;
const first = ua.trim().split(/\s+/)[0];
if (!first) return undefined;
const slash = first.indexOf('/');
if (slash === -1) return { name: first };
const name = first.slice(0, slash);
const version = first.slice(slash + 1);
return name ? { name, ...(version ? { version } : {}) } : undefined;
}
function extractDetail(method: string, params?: Record<string, unknown>): string | undefined {
if (!params) return undefined;
if (method === 'tools/call' || method === 'events/poll' || method === 'events/stream' || method === 'prompts/get') {
return typeof params.name === 'string' ? params.name : undefined;
}
if (method === 'resources/read') {
return typeof params.uri === 'string' ? params.uri : undefined;
}
return undefined;
}
function buildIdentityKey(
transport: McpTransportKind,
name: string | undefined,
version: string | undefined,
userAgent: string | undefined,
remoteAddress: string | undefined,
): string {
if (transport === 'stdio') return 'stdio';
return `${name ?? 'unknown'}@${version ?? ''}|${userAgent ?? ''}|${remoteAddress ?? ''}`;
}
export function createActivityTracker(opts: ActivityTrackerOptions = {}): ActivityTracker {
const user = opts.user ?? 'default';
const changes = opts.changes;
const now = opts.now ?? (() => Date.now());
const maxActivity = opts.maxActivity ?? DEFAULT_MAX_ACTIVITY;
const maxCallers = opts.maxCallers ?? DEFAULT_MAX_CALLERS;
const fingerprints = new LegacyFingerprintCache({ ttlMs: opts.fingerprintTtlMs, now });
const callers = new Map<string, CallerRecord>();
const activity: ActivityEntry[] = [];
let nextActivityId = 1;
let lastHttpCallerKey: string | undefined;
const reqToCallerKey = new WeakMap<Request, string>();
const reqIdToCallerKey = new Map<string, string>();
let stdioClientInfo: Implementation | undefined;
let stdioProtocolVersion: string | undefined;
let stdioEventsCapable: boolean | undefined;
function resolveIdentityInternal(input: {
envelopeMeta?: Record<string, unknown>;
initializeParams?: { clientInfo?: Implementation; protocolVersion?: string; capabilities?: unknown };
serverClientVersion?: { name: string; version: string; title?: string };
protocolVersionHeader?: string;
userAgent?: string;
remoteAddress?: string;
transport: McpTransportKind;
legacyHint?: boolean;
}): ClientIdentity {
const envMeta = input.envelopeMeta;
const envClientInfo = extractClientInfo(envMeta?.[CLIENT_INFO_META_KEY]);
const envProto = typeof envMeta?.[PROTOCOL_VERSION_META_KEY] === 'string'
? (envMeta[PROTOCOL_VERSION_META_KEY] as string)
: undefined;
const envCaps = envMeta?.[CLIENT_CAPABILITIES_META_KEY];
const initClientInfo = input.initializeParams?.clientInfo;
const initProto = input.initializeParams?.protocolVersion;
const initCaps = input.initializeParams?.capabilities;
const protocolVersion = envProto ?? initProto ?? input.protocolVersionHeader;
const era: Era =
envProto === MODERN_PROTOCOL || input.protocolVersionHeader === MODERN_PROTOCOL
? 'modern'
: input.legacyHint === false
? 'modern'
: 'legacy';
let name: string | undefined;
let version: string | undefined;
let title: string | undefined;
let source: ClientIdentity['source'] = 'unknown';
let eventsCapable: boolean | undefined;
if (envCaps !== undefined) {
eventsCapable = hasEventsCapability(envCaps);
} else if (initCaps !== undefined) {
eventsCapable = hasEventsCapability(initCaps);
}
if (envClientInfo) {
name = envClientInfo.name;
version = envClientInfo.version || undefined;
title = envClientInfo.title;
source = 'envelope';
} else if (initClientInfo) {
name = initClientInfo.name;
version = initClientInfo.version || undefined;
title = initClientInfo.title;
source = input.transport === 'stdio' ? 'session' : 'initialize';
} else if (input.serverClientVersion?.name) {
name = input.serverClientVersion.name;
version = input.serverClientVersion.version || undefined;
title = input.serverClientVersion.title;
source = 'session';
} else if (input.transport === 'stdio' && stdioClientInfo) {
name = stdioClientInfo.name;
version = stdioClientInfo.version || undefined;
title = stdioClientInfo.title;
source = 'session';
if (eventsCapable === undefined) eventsCapable = stdioEventsCapable;
} else {
const inferred =
input.transport === 'http'
? fingerprints.lookup(user, input.userAgent, input.remoteAddress)
: undefined;
if (inferred) {
name = inferred.clientInfo.name;
version = inferred.clientInfo.version || undefined;
title = inferred.clientInfo.title;
source = 'inferred';
if (eventsCapable === undefined) eventsCapable = inferred.eventsCapable;
} else {
const uaToken = parseUserAgentToken(input.userAgent);
if (uaToken) {
name = uaToken.name;
version = uaToken.version;
source = 'user-agent';
}
}
}
const key = buildIdentityKey(input.transport, name, version, input.userAgent, input.remoteAddress);
return {
key,
...(name !== undefined ? { name } : {}),
...(version !== undefined ? { version } : {}),
...(title !== undefined ? { title } : {}),
source,
era,
...(protocolVersion !== undefined ? { protocolVersion } : {}),
transport: input.transport,
...(input.userAgent !== undefined ? { userAgent: input.userAgent } : {}),
...(input.remoteAddress !== undefined ? { remoteAddress: input.remoteAddress } : {}),
...(eventsCapable !== undefined ? { eventsCapable } : {}),
};
}
function upsertCaller(
identity: ClientIdentity,
method: string,
detail: string | undefined,
open?: boolean,
): CallerRecord {
const atMs = now();
const atIso = new Date(atMs).toISOString();
let rec = callers.get(identity.key);
if (!rec) {
if (callers.size >= maxCallers) {
const oldestKey = callers.keys().next().value;
if (oldestKey !== undefined) callers.delete(oldestKey);
}
rec = {
client: identity,
firstSeenAt: atIso,
lastSeenAt: atIso,
lastSeenMs: atMs,
requests: 0,
lastMethod: method,
methods: {},
...(open !== undefined ? { open } : {}),
};
callers.set(identity.key, rec);
}
rec.client = {
...rec.client,
...identity,
eventsCapable: identity.eventsCapable ?? rec.client.eventsCapable,
};
rec.lastSeenAt = atIso;
rec.lastSeenMs = atMs;
rec.requests++;
rec.lastMethod = method;
rec.lastDetail = detail;
rec.methods[method] = (rec.methods[method] ?? 0) + 1;
if (open !== undefined) {
rec.open = open;
}
return rec;
}
function clientLabel(client: ClientIdentity): string {
if (client.name) {
return client.version ? `${client.name} ${client.version}` : client.name;
}
return client.key;
}
function log(kind: ActivityKind, summary: string, extra?: Partial<ActivityEntry>): void {
const atIso = new Date(now()).toISOString();
// Coalesce repeated empty polls from the same client + eventName
if (kind === 'poll' && extra?.detail?.delivered === 0 && activity.length > 0) {
const top = activity[0];
if (
top.kind === 'poll' &&
top.client === extra.client &&
top.detail?.delivered === 0 &&
top.detail?.eventName === extra.detail?.eventName
) {
top.count = (top.count ?? 1) + 1;
top.at = atIso;
top.summary = summary;
changes?.emit('state');
return;
}
}
const entry: ActivityEntry = {
id: nextActivityId++,
at: atIso,
kind,
summary,
...(extra?.client !== undefined ? { client: extra.client } : {}),
...(extra?.detail !== undefined ? { detail: extra.detail } : {}),
...(extra?.count !== undefined ? { count: extra.count } : {}),
};
activity.unshift(entry);
if (activity.length > maxActivity) {
activity.length = maxActivity;
}
changes?.emit('state');
}
function observeHttpMessage(
raw: unknown,
legacy: boolean,
req: Request,
remote?: string,
): void {
const msg = asRecord(raw) as JsonRpcLike | undefined;
if (!msg || typeof msg.method !== 'string') return;
const method = msg.method;
const params = asRecord(msg.params);
const meta = asRecord(params?._meta);
const userAgent = req.headers.get('user-agent') ?? undefined;
const protocolVersionHeader = req.headers.get('mcp-protocol-version') ?? undefined;
let initializeParams:
| { clientInfo?: Implementation; protocolVersion?: string; capabilities?: unknown }
| undefined;
if (method === 'initialize' && params) {
const clientInfo = extractClientInfo(params.clientInfo);
const protocolVersion =
typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined;
const capabilities = params.capabilities;
initializeParams = { clientInfo, protocolVersion, capabilities };
if (clientInfo) {
fingerprints.remember(user, userAgent, remote, {
clientInfo,
protocolVersion,
eventsCapable: hasEventsCapability(capabilities),
});
}
}
const identity = resolveIdentityInternal({
envelopeMeta: meta,
initializeParams,
protocolVersionHeader,
userAgent,
remoteAddress: remote,
transport: 'http',
legacyHint: legacy,
});
const detail = extractDetail(method, params);
upsertCaller(identity, method, detail);
lastHttpCallerKey = identity.key;
reqToCallerKey.set(req, identity.key);
if (msg.id !== undefined && msg.id !== null) {
reqIdToCallerKey.set(String(msg.id), identity.key);
if (reqIdToCallerKey.size > 200) {
const first = reqIdToCallerKey.keys().next().value;
if (first !== undefined) reqIdToCallerKey.delete(first);
}
}
// Avoid duplicating poll/stream entries that hub.ts logs directly
if (method !== 'events/poll' && method !== 'events/stream') {
log('call', detail ? `${method} (${detail})` : method, {
client: clientLabel(identity),
detail: { method, ...(detail ? { target: detail } : {}), era: identity.era },
});
}
changes?.emit('pulse', {
type: 'pulse',
channel: 'call',
ref: method,
at: new Date(now()).toISOString(),
});
changes?.emit('state');
}
function observeHttp(o: { message: unknown; legacy: boolean; req: Request; remote?: string }): void {
if (Array.isArray(o.message)) {
for (const item of o.message) {
observeHttpMessage(item, o.legacy, o.req, o.remote);
}
return;
}
observeHttpMessage(o.message, o.legacy, o.req, o.remote);
}
function observeHttpResponse(
message: unknown,
status: number,
contentType: string | null,
req?: Request,
): void {
const responseKind: CallerView['lastResponse'] =
status >= 400
? 'error'
: status === 202
? 'accepted'
: contentType?.includes('text/event-stream')
? 'sse'
: 'json';
let updated = false;
if (req) {
const key = reqToCallerKey.get(req);
if (key) {
const caller = callers.get(key);
if (caller) {
caller.lastResponse = responseKind;
updated = true;
}
}
}
if (!updated) {
const items = Array.isArray(message) ? message : [message];
for (const item of items) {
const rec = asRecord(item) as JsonRpcLike | undefined;
if (rec && rec.id !== undefined && rec.id !== null) {
const key = reqIdToCallerKey.get(String(rec.id));
if (key) {
reqIdToCallerKey.delete(String(rec.id));
const caller = callers.get(key);
if (caller) {
caller.lastResponse = responseKind;
updated = true;
}
}
}
}
}
if (!updated && lastHttpCallerKey) {
const caller = callers.get(lastHttpCallerKey);
if (caller) {
caller.lastResponse = responseKind;
updated = true;
}
}
if (updated) {
changes?.emit('state');
}
}
function observeStdio(direction: 'in' | 'out', message: unknown, _user: string): void {
if (direction !== 'in') {
return;
}
const items = Array.isArray(message) ? message : [message];
for (const item of items) {
const msg = asRecord(item) as JsonRpcLike | undefined;
if (!msg || typeof msg.method !== 'string') continue;
const method = msg.method;
const params = asRecord(msg.params);
let initializeParams:
| { clientInfo?: Implementation; protocolVersion?: string; capabilities?: unknown }
| undefined;
if (method === 'initialize' && params) {
const clientInfo = extractClientInfo(params.clientInfo);
const protocolVersion =
typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined;
const capabilities = params.capabilities;
initializeParams = { clientInfo, protocolVersion, capabilities };
if (clientInfo) stdioClientInfo = clientInfo;
if (protocolVersion) stdioProtocolVersion = protocolVersion;
stdioEventsCapable = hasEventsCapability(capabilities);
}
const identity = resolveIdentityInternal({
envelopeMeta: asRecord(params?._meta),
initializeParams,
protocolVersionHeader: stdioProtocolVersion,
transport: 'stdio',
});
const detail = extractDetail(method, params);
upsertCaller(identity, method, detail, true);
if (method !== 'events/poll' && method !== 'events/stream') {
log('call', detail ? `${method} (${detail})` : method, {
client: clientLabel(identity),
detail: { method, ...(detail ? { target: detail } : {}), transport: 'stdio' },
});
}
changes?.emit('pulse', {
type: 'pulse',
channel: 'call',
ref: method,
at: new Date(now()).toISOString(),
});
changes?.emit('state');
}
}
function identityForRequest(
ctx: ServerContext,
mcpClientVersion?: { name: string; version: string },
): ClientIdentity {
// Published SDK 2.4.0 d.mts flattens RequestMetaEnvelope to {}, so cast safely
const envelopeMeta = asRecord(ctx.mcpReq.envelope as unknown);
const httpReq = (ctx.http as { req?: Request } | undefined)?.req;
const transport: McpTransportKind = httpReq ? 'http' : 'stdio';
const userAgent = httpReq?.headers.get('user-agent') ?? undefined;
const protocolVersionHeader = httpReq?.headers.get('mcp-protocol-version') ?? undefined;
const remoteAddress = httpReq ? getRequestRemoteAddress(httpReq) : undefined;
return resolveIdentityInternal({
envelopeMeta,
serverClientVersion: mcpClientVersion,
protocolVersionHeader: protocolVersionHeader ?? (transport === 'stdio' ? stdioProtocolVersion : undefined),
userAgent,
remoteAddress,
transport,
});
}
function clear(): void {
activity.length = 0;
changes?.emit('state');
}
function markStdioClosed(): void {
const rec = callers.get('stdio');
if (rec) {
rec.open = false;
changes?.emit('state');
}
}
function views(): Pick<DashboardState, 'callers' | 'activity'> {
const nowMs = now();
const callerViews: CallerView[] = Array.from(callers.values()).map((c) => {
const age = nowMs - c.lastSeenMs;
const status: CallerView['status'] =
age < CALLER_ACTIVE_MS ? 'active' : age < CALLER_IDLE_MS ? 'idle' : 'stale';
return {
client: c.client,
firstSeenAt: c.firstSeenAt,
lastSeenAt: c.lastSeenAt,
requests: c.requests,
lastMethod: c.lastMethod,
...(c.lastDetail !== undefined ? { lastDetail: c.lastDetail } : {}),
...(c.lastResponse !== undefined ? { lastResponse: c.lastResponse } : {}),
methods: { ...c.methods },
status,
...(c.open !== undefined ? { open: c.open } : {}),
};
});
return {
callers: callerViews,
activity: activity.map((a) => ({ ...a })),
};
}
return {
observeHttp,
observeHttpResponse,
observeStdio,
identityForRequest,
log,
views,
clear,
markStdioClosed,
};
}