Skip to main content
Glama

deepseek_sessions

Manage conversation sessions for DeepSeek AI models. List active sessions, delete specific ones, or clear all to control stored chat history.

Instructions

Manage multi-turn conversation sessions. List active sessions, delete a specific session, or clear all sessions. Sessions store conversation history for use with the session_id parameter in deepseek_chat.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYesAction to perform. "list": show all active sessions, "clear": remove all sessions, "delete": remove a specific session (requires session_id)
session_idNoSession ID to delete (required when action is "delete")

Implementation Reference

  • The main implementation of deepseek_sessions tool. This file contains the registerSessionsTool function that registers the tool with the MCP server and defines the complete handler logic (lines 31-113) that processes list, delete, and clear actions for session management.
    export function registerSessionsTool(server: McpServer): void {
      server.registerTool(
        'deepseek_sessions',
        {
          title: 'DeepSeek Session Management',
          description:
            'Manage multi-turn conversation sessions. List active sessions, delete a specific session, or clear all sessions. ' +
            'Sessions store conversation history for use with the session_id parameter in deepseek_chat.',
          inputSchema: {
            action: z
              .enum(['list', 'clear', 'delete'])
              .describe(
                'Action to perform. "list": show all active sessions, "clear": remove all sessions, "delete": remove a specific session (requires session_id)'
              ),
            session_id: z
              .string()
              .optional()
              .describe('Session ID to delete (required when action is "delete")'),
          },
        },
        async (input: { action: 'list' | 'clear' | 'delete'; session_id?: string }) => {
          try {
            const store = SessionStore.getInstance();
    
            switch (input.action) {
              case 'list': {
                const sessions = store.list();
                if (sessions.length === 0) {
                  return {
                    content: [
                      {
                        type: 'text' as const,
                        text: 'No active sessions.',
                      },
                    ],
                  };
                }
    
                let text = `**Active Sessions (${sessions.length}):**\n\n`;
                for (const s of sessions) {
                  const created = new Date(s.createdAt).toISOString();
                  const lastAccess = new Date(s.lastAccessedAt).toISOString();
                  text += `- **${s.id}**\n`;
                  text += `  Messages: ${s.messageCount} | Requests: ${s.requestCount} | Cost: $${s.totalCost.toFixed(4)}\n`;
                  text += `  Created: ${created} | Last access: ${lastAccess}\n\n`;
                }
    
                return {
                  content: [{ type: 'text' as const, text }],
                };
              }
    
              case 'delete': {
                if (!input.session_id) {
                  return {
                    content: [
                      {
                        type: 'text' as const,
                        text: 'Error: session_id is required for delete action.',
                      },
                    ],
                    isError: true,
                  };
                }
    
                const deleted = store.delete(input.session_id);
                return {
                  content: [
                    {
                      type: 'text' as const,
                      text: deleted
                        ? `Session "${input.session_id}" deleted successfully.`
                        : `Session "${input.session_id}" not found.`,
                    },
                  ],
                };
              }
    
              case 'clear': {
                const count = store.clear();
                return {
                  content: [
                    {
                      type: 'text' as const,
                      text: `Cleared ${count} session(s).`,
                    },
                  ],
                };
              }
            }
          } catch (error: unknown) {
            console.error('[DeepSeek MCP] Session error:', error);
            return {
              content: [
                {
                  type: 'text' as const,
                  text: `Error: ${getErrorMessage(error)}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • Input schema definition for the deepseek_sessions tool using Zod validation. Defines two fields: action (enum with 'list', 'clear', 'delete') and optional session_id (string, required for delete action).
      action: z
        .enum(['list', 'clear', 'delete'])
        .describe(
          'Action to perform. "list": show all active sessions, "clear": remove all sessions, "delete": remove a specific session (requires session_id)'
        ),
      session_id: z
        .string()
        .optional()
        .describe('Session ID to delete (required when action is "delete")'),
    },
  • Tool registration aggregator that calls registerSessionsTool to register the deepseek_sessions tool with the MCP server along with other tools.
    export function registerAllTools(server: McpServer, client: DeepSeekClient): void {
      registerChatTool(server, client);
      registerSessionsTool(server);
    }
  • SessionStore helper class providing the underlying session management functionality used by deepseek_sessions. Implements singleton pattern with methods for create, get, addMessages, delete, list, and clear operations on in-memory sessions.
    export class SessionStore {
      private static instance: SessionStore | null = null;
      private sessions = new Map<string, Session>();
      private requestCounter = 0;
    
      private constructor() {}
    
      static getInstance(): SessionStore {
        if (!SessionStore.instance) {
          SessionStore.instance = new SessionStore();
        }
        return SessionStore.instance;
      }
    
      /**
       * Reset singleton (for testing)
       */
      static resetInstance(): void {
        SessionStore.instance = null;
      }
    
      /**
       * Create a new session or return existing one
       */
      create(sessionId?: string): Session {
        const id = sessionId || randomUUID();
    
        const existing = this.sessions.get(id);
        if (existing) {
          existing.lastAccessedAt = Date.now();
          return existing;
        }
    
        // Enforce max sessions limit
        const config = getConfig();
        if (this.sessions.size >= config.maxSessions) {
          this.cleanup();
          // If still at limit after cleanup, remove oldest session
          if (this.sessions.size >= config.maxSessions) {
            this.removeOldest();
          }
        }
    
        const session: Session = {
          id,
          messages: [],
          createdAt: Date.now(),
          lastAccessedAt: Date.now(),
          totalCost: 0,
          requestCount: 0,
        };
    
        this.sessions.set(id, session);
        return session;
      }
    
      /**
       * Get a session by ID, returns undefined if not found or expired
       */
      get(sessionId: string): Session | undefined {
        const session = this.sessions.get(sessionId);
        if (!session) return undefined;
    
        // Check TTL
        if (this.isExpired(session)) {
          this.sessions.delete(sessionId);
          return undefined;
        }
    
        session.lastAccessedAt = Date.now();
        return session;
      }
    
      /**
       * Add messages to a session
       */
      addMessages(sessionId: string, messages: ChatMessage[]): void {
        const session = this.get(sessionId);
        if (!session) {
          throw new Error(`Session not found: ${sessionId}`);
        }
        session.messages.push(...messages);
    
        // Enforce message limit (sliding window)
        const config = getConfig();
        if (session.messages.length > config.maxSessionMessages) {
          session.messages = session.messages.slice(-config.maxSessionMessages);
        }
      }
    
      /**
       * Get all messages from a session
       */
      getMessages(sessionId: string): ChatMessage[] {
        const session = this.get(sessionId);
        if (!session) return [];
        return [...session.messages];
      }
    
      /**
       * Delete a session
       */
      delete(sessionId: string): boolean {
        return this.sessions.delete(sessionId);
      }
    
      /**
       * List all active (non-expired) sessions
       */
      list(): SessionInfo[] {
        this.lazyCleanup();
        const result: SessionInfo[] = [];
        for (const session of this.sessions.values()) {
          if (!this.isExpired(session)) {
            result.push({
              id: session.id,
              messageCount: session.messages.length,
              createdAt: session.createdAt,
              lastAccessedAt: session.lastAccessedAt,
              totalCost: session.totalCost,
              requestCount: session.requestCount,
            });
          }
        }
        return result;
      }
    
      /**
       * Clean up expired sessions, returns number of removed sessions
       */
      cleanup(): number {
        let removed = 0;
        for (const [id, session] of this.sessions) {
          if (this.isExpired(session)) {
            this.sessions.delete(id);
            removed++;
          }
        }
        return removed;
      }
    
      /**
       * Get total cost across all sessions
       */
      getTotalCost(): number {
        let total = 0;
        for (const session of this.sessions.values()) {
          total += session.totalCost;
        }
        return total;
      }
    
      /**
       * Get active session count
       */
      get size(): number {
        return this.sessions.size;
      }
    
      /**
       * Clear all sessions
       */
      clear(): number {
        const count = this.sessions.size;
        this.sessions.clear();
        return count;
      }
    
      /**
       * Lazy cleanup: runs full cleanup every 10 requests
       */
      private lazyCleanup(): void {
        this.requestCounter++;
        if (this.requestCounter % 10 === 0) {
          this.cleanup();
        }
      }
    
      private isExpired(session: Session): boolean {
        const config = getConfig();
        const ttlMs = config.sessionTtlMinutes * 60 * 1000;
        return Date.now() - session.lastAccessedAt > ttlMs;
      }
    
      private removeOldest(): void {
        let oldestId: string | null = null;
        let oldestTime = Infinity;
        for (const [id, session] of this.sessions) {
          if (session.lastAccessedAt < oldestTime) {
            oldestTime = session.lastAccessedAt;
            oldestId = id;
          }
        }
        if (oldestId) {
          this.sessions.delete(oldestId);
        }
      }
    }
  • Type definitions for Session and SessionInfo interfaces. Session holds full session data including messages, while SessionInfo is used for listing sessions without exposing full message history.
    export interface Session {
      id: string;
      messages: ChatMessage[];
      createdAt: number;
      lastAccessedAt: number;
      totalCost: number;
      requestCount: number;
    }
    
    /**
     * Session info for listing (without full message history)
     */
    export interface SessionInfo {
      id: string;
      messageCount: number;
      createdAt: number;
      lastAccessedAt: number;
      totalCost: number;
      requestCount: number;
    }
Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/arikusi/deepseek-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server