-
Notifications
You must be signed in to change notification settings - Fork 82
feat(clp-mcp-server): Introduce session-based MCP capabilities: #1401
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 20 commits
a76ff24
697f366
70dff32
0d8b06a
c5ac54e
d326f76
37f2c41
47d0301
2201266
aa37f1a
a3076b6
d3d7830
ec0f2bc
21e0386
edf68e4
3d2be57
e1c1b3b
7844653
97e7f23
d3ccf3e
15315ec
8ce8a38
6faeba9
466e242
cccd8ec
b7c3b87
9c6b881
184c94e
07aa3f8
1c2d810
02c706f
da0b2e3
142573a
6f426ca
c8816a5
702837c
e267ec4
ed7765b
9e73062
01c6a05
67d183e
ce744d7
4fc5cc3
23797fd
0644fb7
662b47d
1a53ad3
862aa42
b79f681
134591c
50e5db3
1cad6b0
2683bcf
22de748
c934ac7
4a2bd41
ad11e90
a1979d6
2193824
d6a7944
00f9503
9678909
5af4233
392af88
07f17a5
d4f6015
540e78d
c480b33
c411ae0
2601008
e38f988
08c80b3
1de6a46
86184c9
a2a13b8
8a5c204
9caab35
f7a6579
a54b019
046b6f6
ebad693
fa8dcc5
5a12084
acf99a9
3b7daca
7e7b321
2b3f13a
c206f7b
f882168
8e67e3d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
"""Constants for CLP MCP server.""" | ||
|
||
|
||
class CLPMcpConstants: | ||
"""Constants for the CLP MCP Server.""" | ||
|
||
CLEAN_UP_SECONDS = 600 # 10 minutes | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
ITEM_PER_PAGE = 10 | ||
MAX_CACHED_RESULTS = 1000 | ||
SESSION_TTL_MINUTES = 60 | ||
|
||
SERVER_NAME = "clp-mcp-server" | ||
SYSTEM_PROMPT = ( | ||
"You are an AI assistant that helps users query a log database using KQL " | ||
"(Kibana Query Language). When given a user query, you should generate a KQL " | ||
"query that accurately captures the user's intent. The KQL query should be as " | ||
"specific as possible to minimize the number of log messages returned. " | ||
"You should also consider the following guidelines when generating KQL queries: " | ||
"- Use specific field names and values to narrow down the search. " | ||
"- Avoid using wildcards (*) unless absolutely necessary, as they can lead to " | ||
"large result sets. - Use logical operators (AND, OR, NOT) to combine multiple " | ||
"conditions. - Consider the time range of the logs you are searching. If the " | ||
"user specifies a time range, include it in the KQL query. - If the user query " | ||
"is ambiguous or lacks detail, ask clarifying questions to better understand " | ||
"their intent before generating the KQL query. - Always ensure that the " | ||
"generated KQL query is syntactically correct and can be executed without errors. " | ||
|
||
) | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,206 @@ | ||
"""Session management for CLP MCP Server.""" | ||
|
||
import threading | ||
import time | ||
from dataclasses import dataclass, field | ||
from datetime import datetime, timedelta, timezone | ||
from typing import Any | ||
|
||
from paginate import Page | ||
|
||
from .constants import CLPMcpConstants | ||
|
||
|
||
@dataclass(frozen=True) | ||
class QueryResult: | ||
"""Cached results from previous query's response.""" | ||
|
||
total_results: list[str] | ||
|
||
items_per_page: int | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
_total_pages: int = field(init=False, repr=False) | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def __post_init__(self) -> None: | ||
|
||
"""Validates that cached results don't exceed MAX_CACHED_RESULTS.""" | ||
if len(self.total_results) > CLPMcpConstants.MAX_CACHED_RESULTS: | ||
err_msg = ( | ||
f"QueryResult exceeds maximum allowed cached results: " | ||
f"{len(self.total_results)} > {CLPMcpConstants.MAX_CACHED_RESULTS}. " | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
) | ||
raise ValueError(err_msg) | ||
|
||
|
||
object.__setattr__( | ||
self, | ||
"_total_pages", | ||
(len(self.total_results) + self.items_per_page - 1) // self.items_per_page, | ||
) | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def get_page(self, page_number: int) -> Page | None: | ||
""" | ||
Gets a specific page from the cached response. | ||
|
||
:param page_number: One-based indexing, e.g., 1 for the first page | ||
:return: Page object or None if page number is out of bounds | ||
""" | ||
if page_number > self._total_pages or page_number <= 0: | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return None | ||
|
||
return Page( | ||
self.total_results, | ||
page=page_number, | ||
items_per_page=self.items_per_page, | ||
) | ||
|
||
|
||
|
||
@dataclass | ||
class SessionState: | ||
"""State of a single user session.""" | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
session_id: str | ||
items_per_page: int | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
session_ttl_minutes: int | ||
last_accessed: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) | ||
cached_query_result: QueryResult | None = None | ||
ran_instructions: bool = False | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def cache_query_result( | ||
self, | ||
results: list[str], | ||
) -> None: | ||
""" | ||
Caches the latest query result of the session. | ||
|
||
:param query_results: Complete log entries to cache | ||
""" | ||
self.cached_query_result = QueryResult( | ||
total_results=results, items_per_page=self.items_per_page | ||
) | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def get_page_data(self, page_number: int) -> dict[str, Any]: | ||
""" | ||
Gets page data in a dictionary format. | ||
|
||
:param page_number: One-based indexing, e.g., 1 for the first page | ||
:return: On success, dictionary containing paged log entries and pagination metadata. | ||
On error, dictionary with ``{"Error": "error message describing the failure"}``. | ||
""" | ||
if self.cached_query_result is None: | ||
return {"Error": "No previous paginated response in this session."} | ||
|
||
page = self.cached_query_result.get_page(page_number) | ||
if page is None: | ||
return {"Error": "Page index is out of bounds."} | ||
20001020ycx marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return { | ||
"items": list(page), | ||
"total_pages": page.page_count, | ||
"total_items": page.item_count, | ||
"items_per_page": page.items_per_page, | ||
"has_next": page.next_page is not None, | ||
"has_previous": page.previous_page is not None, | ||
} | ||
|
||
def is_expired(self) -> bool: | ||
""":return: whether the session has expired.""" | ||
20001020ycx marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
time_diff = datetime.now(timezone.utc) - self.last_accessed | ||
return time_diff > timedelta(minutes=self.session_ttl_minutes) | ||
|
||
def update_access_time(self) -> None: | ||
"""Updates the last accessed timestamp.""" | ||
self.last_accessed = datetime.now(timezone.utc) | ||
|
||
|
||
class SessionManager: | ||
"""Session manager for all user sessions.""" | ||
|
||
def __init__(self, session_ttl_minutes: int) -> None: | ||
""" | ||
Initializes the SessionManager and starts background cleanup thread. | ||
|
||
:param session_ttl_minutes: Session time-to-live in minutes. | ||
""" | ||
self.session_ttl_minutes = session_ttl_minutes | ||
# sessions is a shared variable as there may be multiple session attached to the MCP server | ||
# session state is NOT a shared variable because each session is accessed by only one | ||
# connection at a time, and API calls for a single session are synchronous. | ||
self._sessions_lock = threading.Lock() | ||
self.sessions: dict[str, SessionState] = {} | ||
self._cleanup_thread = threading.Thread(target=self._cleanup_loop, daemon=True) | ||
self._cleanup_thread.start() | ||
|
||
def _cleanup_loop(self) -> None: | ||
"""Cleans up all expired sessions periodically in a separate cleanup thread.""" | ||
while True: | ||
time.sleep(CLPMcpConstants.CLEAN_UP_SECONDS) | ||
self.cleanup_expired_sessions() | ||
|
||
def cleanup_expired_sessions(self) -> None: | ||
"""Cleans up all expired sessions.""" | ||
with self._sessions_lock: | ||
expired_sessions = [ | ||
sid for sid, session in self.sessions.items() if session.is_expired() | ||
] | ||
|
||
for sid in expired_sessions: | ||
del self.sessions[sid] | ||
|
||
def get_or_create_session(self, session_id: str) -> SessionState: | ||
""" | ||
Gets an existing session or creates a new one. | ||
|
||
:param session_id: Unique identifier for the session | ||
:return: The SessionState object for the given session_id | ||
""" | ||
with self._sessions_lock: | ||
if session_id in self.sessions and self.sessions[session_id].is_expired(): | ||
del self.sessions[session_id] | ||
|
||
if session_id not in self.sessions: | ||
self.sessions[session_id] = SessionState( | ||
session_id, CLPMcpConstants.ITEM_PER_PAGE, self.session_ttl_minutes | ||
) | ||
|
||
session = self.sessions[session_id] | ||
|
||
session.update_access_time() | ||
return session | ||
|
||
def cache_query_result(self, session_id: str, query_results: list[str]) -> dict[str, Any]: | ||
""" | ||
Caches query results for a session and return the first page. | ||
|
||
:param session_id: Unique identifier for the session | ||
:param query_results: Complete log entries to cache | ||
:return: On success, dictionary containing the first page of log entries and | ||
pagination metadata. On error, dictionary with | ||
``{"Error": "error message describing the failure"}``. | ||
""" | ||
session = self.get_or_create_session(session_id) | ||
if session.ran_instructions is False: | ||
return { | ||
"Error": "Please call get_instructions() first" | ||
"to understand how to use this MCP server." | ||
} | ||
|
||
session.cache_query_result(results=query_results) | ||
|
||
return session.get_page_data(1) | ||
|
||
|
||
def get_nth_page(self, session_id: str, page_index: int) -> dict[str, Any]: | ||
""" | ||
Retrieves the n-th page of a paginated response from the previous query. | ||
|
||
:param session_id: Unique identifier for the session | ||
:param page_index: Zero-based index, e.g., 0 for the first page | ||
:return: On success, dictionary containing paged log entries and pagination metadata. | ||
On error, dictionary with ``{"Error": "error message describing the failure"}``. | ||
""" | ||
session = self.get_or_create_session(session_id) | ||
if session.ran_instructions is False: | ||
return { | ||
"Error": "Please call get_instructions() first" | ||
"to understand how to use this MCP server." | ||
} | ||
|
||
page_number = page_index + 1 # Convert zero-based to one-based | ||
return session.get_page_data(page_number) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
"""Test Package for CLP MCP Server.""" |
Uh oh!
There was an error while loading. Please reload this page.