Skip to main content
Glama

DeepSeek Session Management

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;
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the three actions (list, clear, delete) and mentions that sessions store conversation history, but doesn't cover important behavioral aspects like authentication requirements, rate limits, what 'clear all sessions' actually destroys, or whether these operations are reversible. It provides basic functionality but lacks depth for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly concise with two sentences that each earn their place. The first sentence states the core functionality, and the second provides important context about the relationship to the sibling tool. There's zero wasted language and it's effectively front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given this is a mutation tool (with delete/clear actions) with no annotations and no output schema, the description should do more to explain behavioral implications. While it covers the basic purpose and relationship to deepseek_chat, it doesn't address what the tool returns, error conditions, or the consequences of destructive operations like 'clear all sessions'. The description is adequate but has clear gaps for a tool with mutation capabilities.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, so the schema already documents both parameters thoroughly. The description doesn't add any parameter semantics beyond what's in the schema - it mentions session_id in the context of deepseek_chat but doesn't provide additional meaning about the parameters themselves. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('manage', 'list', 'delete', 'clear') and resources ('multi-turn conversation sessions'), and distinguishes it from the sibling tool deepseek_chat by explaining that sessions store conversation history for use with that tool. This provides excellent differentiation and clarity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about when to use this tool (for managing sessions that store conversation history for deepseek_chat), but doesn't explicitly state when NOT to use it or mention alternatives. It implies usage relative to the sibling tool but lacks explicit exclusions or comparison guidelines.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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