/**
 * ThreadlineMCPServer — MCP Tool Server for Threadline Protocol.
 *
 * Exposes Threadline capabilities as up to 10 MCP tools:
 *   - threadline_discover         — Find Threadline-capable agents
 *   - threadline_send             — Send a message (with optional reply wait)
 *   - threadline_history          — Get conversation history (participant-only)
 *   - threadline_agents           — List known agents and status
 *   - threadline_delete           — Delete a thread permanently
 *   - threadline_pair             — Inspect/drive verified pairings (verify/deny is PIN-gated)
 *   - threadline_registry_search  — Search the persistent agent registry (if registry available)
 *   - threadline_registry_update  — Update your registry listing (if registry available)
 *   - threadline_registry_status  — Check your registration status (if registry available)
 *   - threadline_registry_get     — Look up an agent by ID (if registry available)
 *
 * Transports:
 *   - stdio (default, local)  — No auth required
 *   - SSE (network)           — Bearer token auth
 *   - HTTP streamable (network) — Bearer token auth
 *
 * Part of Threadline Protocol Phase 6B (Network Interop).
 */
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { AgentDiscovery } from './AgentDiscovery.js';
import type { ThreadResumeMap } from './ThreadResumeMap.js';
import type { AgentTrustManager } from './AgentTrustManager.js';
import type { MCPAuth, MCPTokenInfo } from './MCPAuth.js';
export interface ThreadlineMCPServerConfig {
    /** Name of this agent */
    agentName: string;
    /** Threadline protocol version */
    protocolVersion: string;
    /** Transport mode */
    transport: 'stdio' | 'sse' | 'streamable-http';
    /** Port for network transports (SSE, streamable-http) */
    port?: number;
    /** Whether this is a network transport (requires auth) */
    requireAuth: boolean;
}
/** Registry REST API client for registry tools */
export interface RegistryClient {
    /** Make an authenticated REST call to the registry. Returns status + parsed JSON. */
    fetch(path: string, options?: {
        method?: string;
        body?: unknown;
    }): Promise<{
        status: number;
        data: unknown;
    }>;
    /** Whether the registry client has a valid token */
    hasToken(): boolean;
}
/**
 * Minimal interface for the relay client used by network-scope discover.
 * Decouples ThreadlineMCPServer from the concrete ThreadlineClient so tests
 * can inject a stub and so the dep is optional (offline agents still work).
 */
export interface RelayDiscoverer {
    /** 'connected' when the relay WebSocket is live; anything else means cache fallback. */
    readonly connectionState: string;
    /**
     * Ask the relay for its presence registry. Returns an empty array on timeout
     * or if the relay rejects the request. Filter is best-effort — callers must
     * still post-filter the result.
     */
    discover(filter?: {
        capability?: string;
        framework?: string;
        name?: string;
    }): Promise<Array<{
        agentId: string;
        name: string;
        publicKey?: Buffer | string;
        framework?: string;
        capabilities?: string[];
        lastSeen?: string;
    }>>;
}
export interface ThreadlineMCPDeps {
    /** Agent discovery service */
    discovery: AgentDiscovery;
    /** Thread resume map for thread state */
    threadResumeMap: ThreadResumeMap;
    /** Agent trust manager for trust levels */
    trustManager: AgentTrustManager;
    /** MCP auth for network transports (null for stdio) */
    auth: MCPAuth | null;
    /** Message sender function — sends a message and optionally waits for reply */
    sendMessage: (params: SendMessageParams) => Promise<SendMessageResult>;
    /** Thread history retriever */
    getThreadHistory: (threadId: string, limit: number, before?: string) => Promise<ThreadHistoryResult>;
    /**
     * Sealed-handoff keystone: self-mint a Secret Drop request (one-time,
     * never-on-disk submit URL) via the loopback /threadline/secrets/request
     * route — no externalized bearer needed. Optional; absent on transports that
     * cannot reach the local server. See {@link RequestSecretParams}.
     */
    requestSecret?: (params: RequestSecretParams) => Promise<RequestSecretResult>;
    /** Registry REST API client (null if registry not available) */
    registry: RegistryClient | null;
    /** State directory (.instar path) for config access */
    stateDir?: string;
    /**
     * Relay client for live network-scope discover. Optional — when absent or
     * disconnected, threadline_discover with scope=network falls back to the
     * locally-cached known-agents file and marks the response source=cache.
     */
    relayClient?: RelayDiscoverer | null;
}
export interface SendMessageParams {
    targetAgent: string;
    threadId?: string;
    message: string;
    waitForReply: boolean;
    timeoutSeconds: number;
    /** Optional originating Telegram topic ID. Per THREAD-TOPIC-LINKAGE-SPEC.md. */
    originTopicId?: number;
    /** Optional intent string. Stored locally on the commitment, never sent over the wire. */
    purpose?: string;
}
export interface SendMessageResult {
    success: boolean;
    threadId: string;
    messageId: string;
    reply?: string;
    replyFrom?: string;
    error?: string;
    /** Human-readable delivery outcome (e.g. "spawned new session", "resumed existing thread", "queued (no live session)") */
    deliveryOutcome?: string;
    /** How the message was delivered (local, relay) */
    deliveryPath?: string;
    /** Whether the content was actually delivered (false when withheld by the negotiator lease). */
    delivered?: boolean;
    /** True when the single-negotiator lease withheld this content send (G1 holding). */
    held?: boolean;
    /** Human-readable note (e.g. why content was withheld by the lease). */
    note?: string;
    /** Signal-only advisory nudge (e.g. commitment-class prose → anchor via mandate). */
    advisory?: string;
}
export interface RequestSecretParams {
    /** What's being requested — shown as the Secret Drop form title. */
    label: string;
    /** Why it's needed — shown as the form description. */
    description?: string;
    /** Fields to collect (defaults to a single masked "secret" field). */
    fields?: Array<{
        name: string;
        label: string;
        type?: string;
    }>;
    /** Telegram topic to notify on receipt. */
    topicId?: number;
    /** TTL in milliseconds (server bounds: 60_000 … 3_600_000; default 15 min). */
    ttlMs?: number;
    /**
     * R1a sealed-handoff: pin the expected sender's Ed25519 public key (32-byte,
     * hex) so the submit handler verifies the signed payload before accepting it.
     */
    senderVerification?: {
        senderPubKeyHex: string;
    };
}
export interface RequestSecretResult {
    success: boolean;
    /** Opaque one-time token (also embedded in the URLs). */
    token?: string;
    /** Server-relative submit path (`/secrets/drop/<token>`). */
    localUrl?: string;
    /** Tunnel-absolute submit URL when a tunnel is up, else null. */
    tunnelUrl?: string | null;
    /** Milliseconds until the request expires. */
    expiresIn?: number;
    error?: string;
}
export interface ThreadHistoryMessage {
    id: string;
    from: string;
    body: string;
    timestamp: string;
    threadId: string;
}
export interface ThreadHistoryResult {
    threadId: string;
    messages: ThreadHistoryMessage[];
    totalCount: number;
    hasMore: boolean;
}
/**
 * Tracks the authenticated identity for the current request.
 * For stdio: always authorized (local operator).
 * For network: set by bearer token validation.
 */
interface RequestContext {
    /** Whether the request is authenticated */
    authenticated: boolean;
    /** Token info if authenticated via bearer token */
    tokenInfo?: MCPTokenInfo;
    /** Whether this is a local (stdio) connection */
    isLocal: boolean;
}
export declare class ThreadlineMCPServer {
    private readonly mcpServer;
    private readonly config;
    private readonly deps;
    private requestContext;
    private started;
    constructor(config: ThreadlineMCPServerConfig, deps: ThreadlineMCPDeps);
    /**
     * Start the MCP server with the configured transport.
     * For stdio: connects to process stdin/stdout.
     * For network transports: returns the McpServer for external wiring.
     */
    start(): Promise<void>;
    /**
     * Stop the MCP server.
     */
    stop(): Promise<void>;
    /**
     * Get the underlying McpServer for external transport wiring.
     * Used by SSE/streamable-http integrations.
     */
    getServer(): McpServer;
    /**
     * Set the auth context for the current request (network transports).
     * Called by the HTTP middleware before tool handlers execute.
     */
    setRequestContext(ctx: RequestContext): void;
    /**
     * Validate a bearer token and set the request context.
     * Returns true if the token is valid.
     */
    authenticateBearer(rawToken: string): boolean;
    private checkAuth;
    private registerTools;
    private registerDiscoverTool;
    private registerSendTool;
    private registerRequestSecretTool;
    private registerHistoryTool;
    private registerAgentsTool;
    private registerDeleteTool;
    private registerTrustTool;
    private registerPairTool;
    private registerRelayTool;
    /** Resolve the .instar/config.json path from the state directory */
    private resolveConfigPath;
    /** Read and parse config.json */
    private readConfig;
    /** Write config.json atomically */
    private writeConfig;
    private frameRegistryEntry;
    private registerRegistrySearchTool;
    private registerRegistryUpdateTool;
    private registerRegistryStatusTool;
    private registerRegistryGetTool;
}
export {};
//# sourceMappingURL=ThreadlineMCPServer.d.ts.map