instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Auto-generate documentation strings for this file |
import os
import subprocess
import sys
import time
from pathlib import Path
from typing import Literal, Optional, Union
import psutil
import requests
from tvm.runtime import Device
from mlc_llm.serve.config import EngineConfig
from mlc_llm.serve.engine_base import _check_engine_config
class PopenServer: # pylint:... | --- +++ @@ -1,3 +1,4 @@+"""The MLC LLM server launched in a subprocess."""
import os
import subprocess
@@ -15,6 +16,11 @@
class PopenServer: # pylint: disable=too-many-instance-attributes
+ """The wrapper of MLC LLM server, which runs the server in
+ a background subprocess.
+
+ This server can be use... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/server/popen_server.py |
Add docstrings that explain logic |
from typing import List, Tuple, Union
import tvm_ffi
from tvm.runtime import Object, ShapeTuple
from . import _ffi_api
@tvm_ffi.register_object("mlc.serve.PagedRadixTree") # pylint: disable=protected-access
class PagedRadixTree(Object):
def __init__(self): # pylint: disable=super-init-not-called
sel... | --- +++ @@ -1,3 +1,4 @@+"""The Paged Radix Tree class."""
from typing import List, Tuple, Union
@@ -9,11 +10,30 @@
@tvm_ffi.register_object("mlc.serve.PagedRadixTree") # pylint: disable=protected-access
class PagedRadixTree(Object):
+ """The paged radix tree to manage prefix and sequence."""
def __in... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/radix_tree.py |
Provide clean and structured docstrings |
import tvm_ffi
from tvm.runtime import Object
from . import _ffi_api
@tvm_ffi.register_object("mlc.serve.EventTraceRecorder") # pylint: disable=protected-access
class EventTraceRecorder(Object):
def __init__(self) -> None: # pylint: disable=super-init-not-called
self.__init_handle_by_constructor__(
... | --- +++ @@ -1,3 +1,4 @@+"""The event trace recorder in MLC LLM serving"""
import tvm_ffi
from tvm.runtime import Object
@@ -7,16 +8,34 @@
@tvm_ffi.register_object("mlc.serve.EventTraceRecorder") # pylint: disable=protected-access
class EventTraceRecorder(Object):
+ """The event trace recorder for requests.""... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/event_trace_recorder.py |
Write beginner-friendly docstrings |
import json
from dataclasses import asdict, dataclass
from typing import List, Literal
import tvm
import tvm_ffi
from tvm.runtime import Object
from . import _ffi_api
@dataclass
class TokenizerInfo: # pylint: disable=too-many-instance-attributes
token_postproc_method: Literal["byte_fallback", "byte_level"] =... | --- +++ @@ -1,3 +1,8 @@+"""The tokenizer and related tools in MLC LLM.
+This tokenizer essentially wraps and binds the HuggingFace tokenizer
+library and sentencepiece.
+Reference: https://github.com/mlc-ai/tokenizers-cpp
+"""
import json
from dataclasses import asdict, dataclass
@@ -12,39 +17,114 @@
@dataclass
... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/tokenizers/tokenizers.py |
Document this code for team use | from typing import List, Tuple, Dict, Any
from docling.document_converter import DocumentConverter as DoclingConverter, PdfFormatOption
from docling.datamodel.pipeline_options import PdfPipelineOptions, OcrMacOptions
from docling.datamodel.base_models import InputFormat
import fitz # PyMuPDF for quick text inspection
... | --- +++ @@ -6,6 +6,10 @@ import os
class DocumentConverter:
+ """
+ A class to convert various document formats to structured Markdown using the docling library.
+ Supports PDF, DOCX, HTML, and other formats.
+ """
# Mapping of file extensions to InputFormat
SUPPORTED_FORMATS = {
@@ -18,6... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/ingestion/document_converter.py |
Add standardized docstrings across the file | import os
import json
import sys
import argparse
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# The sys.path manipulation has been removed to prevent import conflicts.
# This script should be run as a module from the project root, e.g.:
# python -m rag_system.main api
from... | --- +++ @@ -165,6 +165,15 @@ # ============================================================================
def get_agent(mode: str = "default") -> Agent:
+ """
+ Factory function to get an instance of the RAG agent based on the specified mode.
+
+ Args:
+ mode: Configuration mode ("default", "fa... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/main.py |
Add docstrings to improve readability |
import argparse
import sys
class ArgumentParser(argparse.ArgumentParser):
def error(self, message):
print("-" * 25 + " Usage " + "-" * 25)
self.print_help()
print("-" * 25 + " Error " + "-" * 25)
print(message, file=sys.stderr)
sys.exit(2) | --- +++ @@ -1,13 +1,16 @@+"""An enhanced argument parser for mlc-chat."""
import argparse
import sys
class ArgumentParser(argparse.ArgumentParser):
+ """An enhanced argument parser for mlc-chat."""
def error(self, message):
+ """Overrides the behavior when erroring out"""
print("-" * ... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/argparse.py |
Add minimal docstrings for each function |
from typing import List, Union
import tvm_ffi
from tvm.runtime import Object, ShapeTuple
from . import _ffi_api
from .tokenizers import Tokenizer
@tvm_ffi.register_object("mlc.TextStreamer") # pylint: disable=protected-access
class TextStreamer(Object):
def __init__(self, tokenizer: Tokenizer) -> None: # py... | --- +++ @@ -1,3 +1,4 @@+"""Streamers in MLC LLM."""
from typing import List, Union
@@ -10,14 +11,33 @@
@tvm_ffi.register_object("mlc.TextStreamer") # pylint: disable=protected-access
class TextStreamer(Object):
+ """The class that streams back validated utf-8 text strings
+ that generated by tokenizer.
+... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/tokenizers/streamer.py |
Add docstrings explaining edge cases | from __future__ import annotations
"""Docling-aware chunker (simplified).
For now we proxy the old MarkdownRecursiveChunker but add:
• sentence-aware packing to max_tokens with overlap
• breadcrumb metadata stubs so downstream code already handles them
In a follow-up we can replace the internals with true Docling el... | --- +++ @@ -45,6 +45,7 @@ return max(1, len(text) // 4)
def split_markdown(self, markdown: str, *, document_id: str, metadata: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Split one Markdown doc into chunks with max_tokens limit."""
base_chunks = self.legacy.chunk(markdown, document_... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/ingestion/docling_chunker.py |
Add docstrings to clarify complex logic |
from dataclasses import dataclass
from typing import Any, Callable, List, Literal, Optional, Tuple
import tvm
from tvm import DataType, DataTypeCode, IRModule, relax, te, tir
from tvm.relax.frontend import nn
from tvm.runtime import Tensor
from tvm.s_tir import dlight as dl
from tvm.target import Target
from ..loade... | --- +++ @@ -1,3 +1,4 @@+"""The FasterTransformer quantization config"""
from dataclasses import dataclass
from typing import Any, Callable, List, Literal, Optional, Tuple
@@ -26,6 +27,7 @@
@dataclass
class FTQuantize: # pylint: disable=too-many-instance-attributes
+ """Configuration for FasterTransformer qua... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/ft_quantization.py |
Write docstrings for data processing functions | # pylint: disable=invalid-name, exec-used
import os
import shutil
from setuptools import find_packages, setup
from setuptools.dist import Distribution
CURRENT_DIR = os.path.dirname(__file__)
CONDA_BUILD = os.getenv("CONDA_BUILD") is not None
def get_lib_path():
# Directly exec libinfo to get the right setup
... | --- +++ @@ -1,4 +1,5 @@ # pylint: disable=invalid-name, exec-used
+"""Setup MLC LLM package."""
import os
import shutil
@@ -11,6 +12,7 @@
def get_lib_path():
+ """Get library path, name and version"""
# Directly exec libinfo to get the right setup
libinfo_py = os.path.join(CURRENT_DIR, "./mlc_llm/l... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/setup.py |
Provide docstrings following PEP 257 | import requests
import json
import os
from typing import List, Dict, Optional
class OllamaClient:
def __init__(self, base_url: Optional[str] = None):
if base_url is None:
base_url = os.getenv("OLLAMA_HOST", "http://localhost:11434")
self.base_url = base_url
self.api_url = f"{bas... | --- +++ @@ -11,6 +11,7 @@ self.api_url = f"{base_url}/api"
def is_ollama_running(self) -> bool:
+ """Check if Ollama server is running"""
try:
response = requests.get(f"{self.base_url}/api/tags", timeout=5)
return response.status_code == 200
@@ -18,6 +19,7 @@... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/backend/ollama_client.py |
Generate docstrings for each module |
# pylint: disable=too-few-public-methods
import dataclasses
import json
from pathlib import Path
from typing import Any, Dict, Type, TypeVar
from . import logging
from .style import bold, red
logger = logging.getLogger(__name__)
ConfigClass = TypeVar("ConfigClass", bound="ConfigBase")
@dataclasses.dataclass
class... | --- +++ @@ -1,3 +1,14 @@+"""
+A common base class for configuration. A configuration could be initialized from its constructor,
+a JSON string or a JSON file, and irrelevant fields during initialization are automatically moved
+to the `kwargs` field.
+
+Take model configuration as an example: it is usually a JSON file ... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/config.py |
Document functions with clear intent | import json
import http.server
import socketserver
import cgi
import os
import uuid
from urllib.parse import urlparse, parse_qs
import requests # 🆕 Import requests for making HTTP calls
import sys
from datetime import datetime
# Add parent directory to path so we can import rag_system modules
sys.path.append(os.path... | --- +++ @@ -39,6 +39,7 @@ super().__init__(*args, **kwargs)
def do_OPTIONS(self):
+ """Handle CORS preflight requests"""
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, DELETE, ... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/backend/server.py |
Create docstrings for all classes and functions |
from typing import List
import tvm_ffi
from tvm.runtime import Object
from mlc_llm.protocol.generation_config import GenerationConfig
from . import _ffi_api
from .data import Data
@tvm_ffi.register_object("mlc.serve.Request") # pylint: disable=protected-access
class Request(Object):
@property
def inputs... | --- +++ @@ -1,3 +1,4 @@+"""The request class in MLC LLM serving"""
from typing import List
@@ -12,13 +13,24 @@
@tvm_ffi.register_object("mlc.serve.Request") # pylint: disable=protected-access
class Request(Object):
+ """The user submitted text-generation request, which contains
+ a unique request id, a l... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/request.py |
Fully document this Python code with docstrings | from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
from typing import List, Dict, Any
class QwenReranker:
def __init__(self, model_name: str = "BAAI/bge-reranker-base"):
# Auto-select the best available device: CUDA > MPS > CPU
if torch.cuda.is_available():
... | --- +++ @@ -3,6 +3,9 @@ from typing import List, Dict, Any
class QwenReranker:
+ """
+ A reranker that uses a local Hugging Face transformer model.
+ """
def __init__(self, model_name: str = "BAAI/bge-reranker-base"):
# Auto-select the best available device: CUDA > MPS > CPU
if torch.... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/rerankers/reranker.py |
Provide docstrings following PEP 257 |
import json
from pathlib import Path
from typing import List, Optional, Tuple
from . import logging
from .style import bold, green, red
logger = logging.getLogger(__name__)
FOUND = green("Found")
NOT_FOUND = red("Not found")
def detect_weight(
weight_path: Path,
config_json_path: Path,
weight_format: ... | --- +++ @@ -1,3 +1,4 @@+"""Help functions for detecting weight paths and weight formats."""
import json
from pathlib import Path
@@ -17,6 +18,36 @@ config_json_path: Path,
weight_format: str = "auto",
) -> Tuple[Path, str]:
+ """Detect the weight directory, and detect the weight format.
+
+ Paramete... | https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/auto_weight.py |
Write proper docstrings for these functions | from __future__ import annotations
"""Sentence-level context pruning using the Provence model (ICLR 2025).
This lightweight helper wraps the HuggingFace model hosted at
`naver/provence-reranker-debertav3-v1` and exposes a thread-safe
`prune_documents()` method that converts a list of RAG chunks into their
pruned vari... | --- +++ @@ -18,6 +18,7 @@
class SentencePruner:
+ """Lightweight singleton wrapper around the Provence model."""
_model = None # shared across all instances
_init_lock: Lock = Lock()
@@ -30,6 +31,7 @@ # Internal helpers
# ---------------------------------------------------------------------... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/rerankers/sentence_pruner.py |
Annotate my code with docstrings | from typing import List, Dict, Any
import os
import networkx as nx
from rag_system.ingestion.document_converter import DocumentConverter
from rag_system.ingestion.chunking import MarkdownRecursiveChunker
from rag_system.indexing.representations import EmbeddingGenerator, select_embedder
from rag_system.indexing.embedde... | --- +++ @@ -129,6 +129,11 @@ self.latechunk_enabled = False
def run(self, file_paths: List[str] | None = None, *, documents: List[str] | None = None):
+ """
+ Processes and indexes documents based on the pipeline's configuration.
+ Accepts legacy keyword *documents* as an ali... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/pipelines/indexing_pipeline.py |
Add missing documentation to my Python functions | import json
from typing import List, Dict, Any, Optional
import base64
from io import BytesIO
from PIL import Image
class WatsonXClient:
def __init__(
self,
api_key: str,
project_id: str,
url: str = "https://us-south.ml.cloud.ibm.com",
):
self.api_key = api_key
... | --- +++ @@ -6,12 +6,24 @@
class WatsonXClient:
+ """
+ A client for IBM Watson X AI that provides similar interface to OllamaClient
+ for seamless integration with the RAG system.
+ """
def __init__(
self,
api_key: str,
project_id: str,
url: str = "https://us-sou... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/utils/watsonx_client.py |
Add detailed docstrings explaining each function | import requests
import json
from typing import List, Dict, Any
import base64
from io import BytesIO
from PIL import Image
import httpx, asyncio
class OllamaClient:
def __init__(self, host: str = "http://localhost:11434"):
self.host = host
self.api_url = f"{host}/api"
# (Connection check rem... | --- +++ @@ -7,12 +7,16 @@ import httpx, asyncio
class OllamaClient:
+ """
+ An enhanced client for Ollama that now handles image data for VLM models.
+ """
def __init__(self, host: str = "http://localhost:11434"):
self.host = host
self.api_url = f"{host}/api"
# (Connection ch... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/utils/ollama_client.py |
Write Python docstrings for this snippet | import lancedb
import pickle
import json
from typing import List, Dict, Any
import numpy as np
import networkx as nx
import os
from PIL import Image
from transformers import CLIPProcessor, CLIPModel
import torch
import logging
import pandas as pd
import math
import concurrent.futures
from functools import lru_cache
fr... | --- +++ @@ -53,6 +53,9 @@
# region === MultiVectorRetriever ===
class MultiVectorRetriever:
+ """
+ Performs hybrid (vector + FTS) or vector-only retrieval.
+ """
def __init__(self, db_manager: LanceDBManager, text_embedder: QwenEmbedder, vision_model: LocalVisionModel = None, *, fusion_config: Dict[st... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/retrieval/retrievers.py |
Add docstrings explaining edge cases | import logging
from typing import List, Dict
from textwrap import shorten
logger = logging.getLogger("rag-system")
# Global log format – only set if user has not configured logging
if not logger.handlers:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)-7s | %(name)s | %... | --- +++ @@ -13,6 +13,8 @@
def log_query(query: str, sub_queries: List[str] | None = None) -> None:
+ """Emit a nicely-formatted block describing the incoming query and any
+ decomposition."""
border = "=" * 60
logger.info("\n%s\nUSER QUERY: %s", border, query)
if sub_queries:
@@ -22,6 +24,7 @@ ... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/utils/logging_utils.py |
Generate consistent documentation across files | #!/usr/bin/env python3
import sys
import os
# Add parent directories to path for imports
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from rag_system.main import (
PIPELINE_CONFIGS,
OLLAMA_CONFIG,
EXTERNAL_MODELS,
validate_model_config
)
def print_he... | --- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python3
+"""
+Model Configuration Validation Script
+=====================================
+
+This script validates the consolidated model configuration system to ensure:
+1. No configuration conflicts exist
+2. All model names are consistent across components
+3. Models are acce... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/utils/validate_model_config.py |
Provide clean and structured docstrings | #!/usr/bin/env python3
import os
import sys
import json
import argparse
from typing import List, Optional
from pathlib import Path
# Add the project root to the path so we can import rag_system modules
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
from rag_system.main import PIPELINE_CONFIG... | --- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python3
+"""
+Interactive Index Creation Script for LocalGPT RAG System
+
+This script provides a user-friendly interface for creating document indexes
+using the LocalGPT RAG system. It supports both single documents and batch
+processing of multiple documents.
+
+Usage:
+ py... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/create_index_script.py |
Help me comply with documentation standards | import time
import logging
from typing import List, Dict, Any, Callable, Optional, Iterator
from contextlib import contextmanager
import gc
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@contextmanager
def timer(operation_name: str):
start = time.time()
try:
... | --- +++ @@ -10,6 +10,7 @@
@contextmanager
def timer(operation_name: str):
+ """Context manager to time operations"""
start = time.time()
try:
yield
@@ -18,6 +19,7 @@ logger.info(f"{operation_name} completed in {duration:.2f}s")
class ProgressTracker:
+ """Tracks progress and perfo... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/utils/batch_processor.py |
Generate docstrings with parameter types |
import uuid
from typing import List, Dict, Any
import PyPDF2
from io import BytesIO
import sqlite3
from datetime import datetime
class SimplePDFProcessor:
def __init__(self, db_path: str = "chat_data.db"):
self.db_path = db_path
self.init_database()
print("✅ Simple PDF processor initialize... | --- +++ @@ -1,3 +1,7 @@+"""
+Simple PDF Processing Service
+Handles PDF upload and text extraction for RAG functionality
+"""
import uuid
from typing import List, Dict, Any
@@ -8,11 +12,13 @@
class SimplePDFProcessor:
def __init__(self, db_path: str = "chat_data.db"):
+ """Initialize simple PDF proces... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/backend/simple_pdf_processor.py |
Write docstrings for data processing functions | #!/usr/bin/env python3
import sys
import traceback
from pathlib import Path
def print_status(message, success=None):
if success is True:
print(f"✅ {message}")
elif success is False:
print(f"❌ {message}")
else:
print(f"🔍 {message}")
def check_imports():
print_status("Testing b... | --- +++ @@ -1,10 +1,15 @@ #!/usr/bin/env python3
+"""
+System Health Check for RAG System
+Quick validation of configurations, models, and data access.
+"""
import sys
import traceback
from pathlib import Path
def print_status(message, success=None):
+ """Print status with emoji"""
if success is True:
... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/system_health_check.py |
Generate missing documentation strings | import json
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs
import os
import requests
import sys
import logging
# Add backend directory to path for database imports
backend_dir = os.path.join(os.path.dirname(__file__), '..', 'backend')
if backend_dir not in sys.path:
sys.path.app... | --- +++ @@ -40,6 +40,7 @@ # -------------- Helper ----------------
def _apply_index_embedding_model(idx_ids):
+ """Ensure retrieval pipeline uses the embedding model stored with the first index."""
debug_info = f"🔧 _apply_index_embedding_model called with idx_ids: {idx_ids}\n"
if not idx_ids:
@@ ... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/api_server.py |
Add well-formatted docstrings | #!/usr/bin/env python3
import subprocess
import threading
import time
import signal
import sys
import os
import argparse
import json
import requests
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, TextIO
import logging
from dataclasses import dataclass
import psutil
@da... | --- +++ @@ -1,4 +1,24 @@ #!/usr/bin/env python3
+"""
+RAG System Unified Launcher
+===========================
+
+A comprehensive launcher that starts all RAG system components:
+- Ollama server
+- RAG API server (port 8001)
+- Backend server (port 8000)
+- Frontend server (port 3000)
+
+Features:
+- Single command s... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/run_system.py |
Add docstrings that explain inputs and outputs | import json
import threading
import time
from typing import Dict, List, Any
import logging
from urllib.parse import urlparse, parse_qs
import http.server
import socketserver
# Import the core logic and batch processing utilities
from rag_system.main import get_agent
from rag_system.utils.batch_processor import Progres... | --- +++ @@ -27,22 +27,26 @@ print("✅ RAG Agent initialized successfully.")
class ServerSentEventsHandler:
+ """Handler for Server-Sent Events (SSE) for real-time progress updates"""
active_connections: Dict[str, Any] = {}
@classmethod
def add_connection(cls, session_id: str, response_ha... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/api_server_with_progress.py |
Create docstrings for all classes and functions | from typing import Dict, Any, Optional
import json
import time, asyncio, os
import numpy as np
import concurrent.futures
from cachetools import TTLCache, LRUCache
from rag_system.utils.ollama_client import OllamaClient
from rag_system.pipelines.retrieval_pipeline import RetrievalPipeline
from rag_system.agent.verifier ... | --- +++ @@ -11,6 +11,9 @@ from rag_system.retrieval.retrievers import GraphRetriever
class Agent:
+ """
+ The main agent, now fully wired to use a live Ollama client.
+ """
def __init__(self, pipeline_configs: Dict[str, Dict], llm_client: OllamaClient, ollama_config: Dict[str, str]):
self.pipe... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/agent/loop.py |
Add docstrings to existing functions | import json
from rag_system.utils.ollama_client import OllamaClient
class VerificationResult:
def __init__(self, is_grounded: bool, reasoning: str, verdict: str, confidence_score: int):
self.is_grounded = is_grounded
self.reasoning = reasoning
self.verdict = verdict
self.confidence_... | --- +++ @@ -9,6 +9,9 @@ self.confidence_score = confidence_score
class Verifier:
+ """
+ Verifies if a generated answer is grounded in the provided context using Ollama.
+ """
def __init__(self, llm_client: OllamaClient, llm_model: str):
self.llm_client = llm_client
self.llm_m... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/agent/verifier.py |
Write docstrings that follow conventions | from dotenv import load_dotenv
def get_agent(mode: str = "default"):
from rag_system.agent.loop import Agent
from rag_system.utils.ollama_client import OllamaClient
from rag_system.main import PIPELINE_CONFIGS, OLLAMA_CONFIG, LLM_BACKEND, WATSONX_CONFIG
load_dotenv()
# Initialize the appropri... | --- +++ @@ -1,6 +1,10 @@ from dotenv import load_dotenv
def get_agent(mode: str = "default"):
+ """
+ Factory function to get an instance of the RAG agent based on the specified mode.
+ This uses local imports to prevent circular dependencies.
+ """
from rag_system.agent.loop import Agent
from ... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/factory.py |
Please document this code using docstrings | #!/usr/bin/env python3
import argparse
import re
import sys
from pathlib import Path
def get_github_url(file_path: str) -> str:
base_url = "https://github.com/modelcontextprotocol/python-sdk/blob/main"
return f"{base_url}/{file_path}"
def process_snippet_block(match: re.Match[str], check_mode: bool = False... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""Update README.md with live code snippets from example files.
+
+This script finds specially marked code blocks in README.md and updates them
+with the actual code from the referenced files.
+
+Usage:
+ python scripts/update_readme_snippets.py
+ python scripts/up... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/scripts/update_readme_snippets.py |
Write Python docstrings for this snippet | from typing import List, Dict, Any, Protocol
import numpy as np
from transformers import AutoModel, AutoTokenizer
import torch
import os
# We keep the protocol to ensure a consistent interface
class EmbeddingModel(Protocol):
def create_embeddings(self, texts: List[str]) -> np.ndarray: ...
# Global cache for model... | --- +++ @@ -13,6 +13,9 @@
# --- New Ollama Embedder ---
class QwenEmbedder(EmbeddingModel):
+ """
+ An embedding model that uses a local Hugging Face transformer model.
+ """
def __init__(self, model_name: str = "Qwen/Qwen3-Embedding-0.6B"):
self.model_name = model_name
# Auto-select ... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/indexing/representations.py |
Improve my code by adding docstrings | class OAuthFlowError(Exception):
class OAuthTokenError(OAuthFlowError):
class OAuthRegistrationError(OAuthFlowError): | --- +++ @@ -1,7 +1,10 @@ class OAuthFlowError(Exception):
+ """Base exception for OAuth flow errors."""
class OAuthTokenError(OAuthFlowError):
+ """Raised when token operations fail."""
-class OAuthRegistrationError(OAuthFlowError):+class OAuthRegistrationError(OAuthFlowError):
+ """Raised when client... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/auth/exceptions.py |
Write Python docstrings for this snippet | from __future__ import annotations
"""Late Chunking encoder.
This helper feeds the *entire* document to the embedding model, collects
per-token hidden-states and then mean-pools those vectors inside pre-defined
chunk spans. The end result is one vector per chunk – but each vector has
been produced with knowledge of ... | --- +++ @@ -19,6 +19,7 @@ import numpy as np
class LateChunkEncoder:
+ """Generate late-chunked embeddings given character-offset spans."""
def __init__(self, model_name: str = "Qwen/Qwen3-Embedding-0.6B", *, max_tokens: int = 8192) -> None:
self.model_name = model_name
@@ -40,6 +41,15 @@
@t... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/indexing/latechunk.py |
Generate documentation strings for clarity | from typing import List, Dict, Any
from rag_system.utils.ollama_client import OllamaClient
from rag_system.ingestion.chunking import create_contextual_window
import logging
import re
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Define the structured prompt templates,... | --- +++ @@ -26,6 +26,10 @@ Answer *only* with the succinct context and nothing else."""
class ContextualEnricher:
+ """
+ Enriches chunks with a prepended summary of their surrounding context using Ollama,
+ while preserving the original text.
+ """
def __init__(self, llm_client: OllamaClient, llm_m... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/indexing/contextualizer.py |
Add docstrings to incomplete code | from typing import List, Dict, Any, Optional
import re
from transformers import AutoTokenizer
class MarkdownRecursiveChunker:
def __init__(self, max_chunk_size: int = 1500, min_chunk_size: int = 200, tokenizer_model: str = "Qwen/Qwen3-Embedding-0.6B"):
self.max_chunk_size = max_chunk_size
self.min... | --- +++ @@ -3,6 +3,10 @@ from transformers import AutoTokenizer
class MarkdownRecursiveChunker:
+ """
+ A recursive chunker that splits Markdown text based on its semantic structure
+ and embeds document-level metadata into each chunk.
+ """
def __init__(self, max_chunk_size: int = 1500, min_chunk... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/ingestion/chunking.py |
Add docstrings including usage examples |
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING, Any, TypeVar
from mcp import types
from mcp.shared.experimental.tasks.polling import poll_until_terminal
from mcp.types._types import RequestParamsMeta
if TYPE_CHECKING:
from mcp.client.session import ClientSession
ResultT = TypeVar("Re... | --- +++ @@ -1,3 +1,29 @@+"""Experimental client-side task support.
+
+This module provides client methods for interacting with MCP tasks.
+
+WARNING: These APIs are experimental and may change without notice.
+
+Example:
+ ```python
+ # Call a tool as a task
+ result = await session.experimental.call_tool_as_t... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/experimental/tasks.py |
Write reusable docstrings |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Protocol
from pydantic import TypeAdapter
from mcp import types
from mcp.shared._context import RequestContext
from mcp.shared.session import RequestResponder
if TYPE_CHECKING:
from mcp.client.session ... | --- +++ @@ -1,3 +1,15 @@+"""Experimental task handler protocols for server -> client requests.
+
+This module provides Protocol types and default handlers for when servers
+send task-related requests to clients (the reverse of normal client -> server flow).
+
+WARNING: These APIs are experimental and may change without... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/experimental/task_handlers.py |
Generate docstrings for each module | import fitz # PyMuPDF
from PIL import Image
import torch
import os
from typing import List, Dict, Any
from rag_system.indexing.embedders import LanceDBManager, VectorIndexer
from rag_system.indexing.representations import QwenEmbedder
from transformers import ColPaliForRetrieval, ColPaliProcessor, Qwen2TokenizerFas... | --- +++ @@ -11,6 +11,9 @@ from transformers import ColPaliForRetrieval, ColPaliProcessor, Qwen2TokenizerFast
class LocalVisionModel:
+ """
+ A wrapper for a local vision model (ColPali) from the transformers library.
+ """
def __init__(self, model_name: str = "vidore/colqwen2-v1.0", device: str = "cpu"... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/indexing/multimodal.py |
Add standardized docstrings across the file |
from __future__ import annotations
from contextlib import AsyncExitStack
from dataclasses import KW_ONLY, dataclass, field
from typing import Any
from mcp.client._memory import InMemoryTransport
from mcp.client._transport import Transport
from mcp.client.session import ClientSession, ElicitationFnT, ListRootsFnT, Lo... | --- +++ @@ -1,3 +1,4 @@+"""Unified MCP Client that wraps ClientSession with transport management."""
from __future__ import annotations
@@ -34,6 +35,29 @@
@dataclass
class Client:
+ """A high-level MCP client for connecting to MCP servers.
+
+ Supports in-memory transport for testing (pass a Server or MCP... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/client.py |
Auto-generate documentation strings for this file | import re
from urllib.parse import urljoin, urlparse
from httpx import Request, Response
from pydantic import AnyUrl, ValidationError
from mcp.client.auth import OAuthRegistrationError, OAuthTokenError
from mcp.client.streamable_http import MCP_PROTOCOL_VERSION
from mcp.shared.auth import (
OAuthClientInformation... | --- +++ @@ -17,6 +17,11 @@
def extract_field_from_www_auth(response: Response, field_name: str) -> str | None:
+ """Extract field from WWW-Authenticate header.
+
+ Returns:
+ Field value if found in WWW-Authenticate header, None otherwise
+ """
www_auth_header = response.headers.get("WWW-Authen... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/auth/utils.py |
Create docstrings for reusable components |
import base64
import hashlib
import logging
import secrets
import string
import time
from collections.abc import AsyncGenerator, Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any, Protocol
from urllib.parse import quote, urlencode, urljoin, urlparse
import anyio
import httpx
from pyd... | --- +++ @@ -1,3 +1,7 @@+"""OAuth2 Authentication implementation for HTTPX.
+
+Implements authorization code flow with PKCE and automatic token refresh.
+"""
import base64
import hashlib
@@ -50,12 +54,14 @@
class PKCEParameters(BaseModel):
+ """PKCE (Proof Key for Code Exchange) parameters."""
code_ver... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/auth/oauth2.py |
Add docstrings explaining edge cases | from __future__ import annotations
import logging
from typing import Any, Protocol
import anyio.lowlevel
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from pydantic import TypeAdapter
from mcp import types
from mcp.client.experimental import ExperimentalClientFeatures
from mcp.cl... | --- +++ @@ -192,15 +192,31 @@ return result
def get_server_capabilities(self) -> types.ServerCapabilities | None:
+ """Return the server capabilities received during initialization.
+
+ Returns None if the session has not been initialized yet.
+ """
return self._server_capab... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/session.py |
Improve my code by adding docstrings |
import asyncio
import json
import logging
import os
import sys
from collections.abc import Callable, Coroutine
from typing import Any, cast
from urllib.parse import parse_qs, urlparse
import httpx
from pydantic import AnyUrl
from mcp import ClientSession, types
from mcp.client.auth import OAuthClientProvider, TokenS... | --- +++ @@ -1,3 +1,23 @@+"""MCP unified conformance test client.
+
+This client is designed to work with the @modelcontextprotocol/conformance npm package.
+It handles all conformance test scenarios via environment variables and CLI arguments.
+
+Contract:
+ - MCP_CONFORMANCE_SCENARIO env var -> scenario name
+ -... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/.github/actions/conformance/client.py |
Insert docstrings into my code |
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from types import TracebackType
from typing import Any
import anyio
from mcp.client._transport import TransportStreams
from mcp.server import Server
from mcp.server.mc... | --- +++ @@ -1,3 +1,4 @@+"""In-memory transport for testing MCP servers without network overhead."""
from __future__ import annotations
@@ -15,14 +16,27 @@
class InMemoryTransport:
+ """In-memory transport for testing MCP servers without network overhead.
+
+ This transport starts the server in a backgrou... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/_memory.py |
Add return value explanations in docstrings |
import json
import os
import shutil
import sys
from pathlib import Path
from typing import Any
from mcp.server.mcpserver.utilities.logging import get_logger
logger = get_logger(__name__)
MCP_PACKAGE = "mcp[cli]"
def get_claude_config_path() -> Path | None: # pragma: no cover
if sys.platform == "win32":
... | --- +++ @@ -1,3 +1,4 @@+"""Claude app integration utilities."""
import json
import os
@@ -14,6 +15,7 @@
def get_claude_config_path() -> Path | None: # pragma: no cover
+ """Get the Claude config directory based on platform."""
if sys.platform == "win32":
path = Path(Path.home(), "AppData", "Ro... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/cli/claude.py |
Write reusable docstrings |
import time
import warnings
from collections.abc import Awaitable, Callable
from typing import Any, Literal
from uuid import uuid4
import httpx
import jwt
from pydantic import BaseModel, Field
from mcp.client.auth import OAuthClientProvider, OAuthFlowError, OAuthTokenError, TokenStorage
from mcp.shared.auth import O... | --- +++ @@ -1,3 +1,11 @@+"""OAuth client credential extensions for MCP.
+
+Provides OAuth providers for machine-to-machine authentication flows:
+- ClientCredentialsOAuthProvider: For client_credentials with client_id + client_secret
+- PrivateKeyJWTOAuthProvider: For client_credentials with private_key_jwt authenticat... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/auth/extensions/client_credentials.py |
Add detailed docstrings explaining each function | import pymupdf
from typing import List, Dict, Any, Tuple, Optional
from PIL import Image
import concurrent.futures
import time
import json
import lancedb
import logging
import math
import numpy as np
from threading import Lock
from rag_system.utils.ollama_client import OllamaClient
from rag_system.retrieval.retrievers... | --- +++ @@ -41,6 +41,9 @@ _sentence_pruner_lock: Lock = Lock()
class RetrievalPipeline:
+ """
+ Orchestrates the state-of-the-art multimodal RAG pipeline.
+ """
def __init__(self, config: Dict[str, Any], ollama_client: OllamaClient, ollama_config: Dict[str, Any]):
self.config = config
... | https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/rag_system/pipelines/retrieval_pipeline.py |
Add clean documentation to messy code | from dataclasses import dataclass
from functools import partial
from typing import Any, Literal
from pydantic import BaseModel, ValidationError
from starlette.requests import Request
from starlette.responses import Response
from mcp.server.auth.errors import (
stringify_pydantic_error,
)
from mcp.server.auth.json... | --- +++ @@ -15,6 +15,7 @@
class RevocationRequest(BaseModel):
+ """See https://datatracker.ietf.org/doc/html/rfc7009#section-2.1"""
token: str
token_type_hint: Literal["access_token", "refresh_token"] | None = None
@@ -33,6 +34,7 @@ client_authenticator: ClientAuthenticator
async def handl... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/auth/handlers/revoke.py |
Add professional docstrings to my codebase |
import importlib.metadata
import importlib.util
import os
import subprocess
import sys
from pathlib import Path
from typing import Annotated, Any
from mcp.server import MCPServer
from mcp.server import Server as LowLevelServer
try:
import typer
except ImportError: # pragma: no cover
print("Error: typer is r... | --- +++ @@ -1,3 +1,4 @@+"""MCP CLI tools."""
import importlib.metadata
import importlib.util
@@ -39,6 +40,7 @@
def _get_npx_command():
+ """Get the correct npx command for the current platform."""
if sys.platform == "win32":
# Try both npx.cmd and npx.exe on Windows
for cmd in ["npx.cm... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/cli/cli.py |
Document helper functions with docstrings |
import logging
import shutil
import subprocess
import sys
from pathlib import Path
from typing import BinaryIO, TextIO, cast
import anyio
from anyio import to_thread
from anyio.abc import Process
from anyio.streams.file import FileReadStream, FileWriteStream
from typing_extensions import deprecated
logger = logging.... | --- +++ @@ -1,3 +1,4 @@+"""Windows-specific functionality for stdio client operations."""
import logging
import shutil
@@ -31,6 +32,17 @@
def get_windows_executable_command(command: str) -> str:
+ """Get the correct executable command normalized for Windows.
+
+ On Windows, commands might exist with speci... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/os/win32/utilities.py |
Write docstrings for backend logic |
from __future__ import annotations
from contextlib import AbstractAsyncContextManager
from typing import Protocol
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from mcp.shared.message import SessionMessage
TransportStreams = tuple[MemoryObjectReceiveStream[SessionMessage | Exce... | --- +++ @@ -1,3 +1,4 @@+"""Transport protocol for MCP clients."""
from __future__ import annotations
@@ -11,4 +12,9 @@ TransportStreams = tuple[MemoryObjectReceiveStream[SessionMessage | Exception], MemoryObjectSendStream[SessionMessage]]
-class Transport(AbstractAsyncContextManager[TransportStreams], Protocol... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/_transport.py |
Write reusable docstrings |
import logging
import os
import signal
import anyio
from anyio.abc import Process
logger = logging.getLogger(__name__)
async def terminate_posix_process_tree(process: Process, timeout_seconds: float = 2.0) -> None:
pid = getattr(process, "pid", None) or getattr(getattr(process, "popen", None), "pid", None)
... | --- +++ @@ -1,3 +1,4 @@+"""POSIX-specific functionality for stdio client operations."""
import logging
import os
@@ -10,6 +11,14 @@
async def terminate_posix_process_tree(process: Process, timeout_seconds: float = 2.0) -> None:
+ """Terminate a process and all its children on POSIX systems.
+
+ Uses os.ki... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/os/posix/utilities.py |
Write docstrings for this repository | import json
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
import anyio
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from pydantic import ValidationError
from websockets.asyncio.client import connect as ws_connect
from websockets.typing impor... | --- +++ @@ -19,6 +19,16 @@ tuple[MemoryObjectReceiveStream[SessionMessage | Exception], MemoryObjectSendStream[SessionMessage]],
None,
]:
+ """WebSocket client transport for MCP, symmetrical to the server version.
+
+ Connects to 'url' using the 'mcp' subprotocol, then yields:
+ (read_stream, wri... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/websocket.py |
Include argument descriptions in docstrings |
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
import anyio
from anyio.abc import TaskGroup
from mcp.server.experimental.task_result_handler import TaskResultHandler
from mcp.server.session import ServerSession
from mcp.shared.experimenta... | --- +++ @@ -1,3 +1,8 @@+"""TaskSupport - Configuration for experimental task support.
+
+This module provides the TaskSupport class which encapsulates all the
+infrastructure needed for task-augmented requests: store, queue, and handler.
+"""
from collections.abc import AsyncIterator
from contextlib import asynccon... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/experimental/task_support.py |
Expand my code with proper documentation strings |
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
from mcp.server.experimental.task_context import ServerTaskContext
from mcp.server.experimental.task_support import TaskSupport
from mcp.server.session import ServerSession
from mcp.shared.exceptions import... | --- +++ @@ -1,3 +1,10 @@+"""Experimental request context features.
+
+This module provides the Experimental class which gives access to experimental
+features within a request context, such as task-augmented request handling.
+
+WARNING: These APIs are experimental and may change without notice.
+"""
from collection... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/experimental/request_context.py |
Write proper docstrings for these functions |
from __future__ import annotations as _annotations
import contextlib
import logging
from collections.abc import AsyncGenerator, Awaitable, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass
import anyio
import httpx
from anyio.abc import TaskGroup
from anyio.streams.memory import M... | --- +++ @@ -1,3 +1,4 @@+"""Implements StreamableHTTP transport for MCP clients."""
from __future__ import annotations as _annotations
@@ -50,13 +51,16 @@
class StreamableHTTPError(Exception):
+ """Base exception for StreamableHTTP transport errors."""
class ResumptionError(StreamableHTTPError):
+ ""... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/streamable_http.py |
Create documentation for each function signature |
from typing import Any
import anyio
from mcp.server.experimental.task_result_handler import TaskResultHandler
from mcp.server.session import ServerSession
from mcp.server.validation import validate_sampling_tools, validate_tool_use_result_messages
from mcp.shared.exceptions import MCPError
from mcp.shared.experiment... | --- +++ @@ -1,3 +1,10 @@+"""ServerTaskContext - Server-integrated task context with elicitation and sampling.
+
+This wraps the pure TaskContext and adds server-specific functionality:
+- Elicitation (task.elicit())
+- Sampling (task.create_message())
+- Status notifications
+"""
from typing import Any
@@ -41,6 +4... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/experimental/task_context.py |
Replace inline comments with docstrings |
from __future__ import annotations
import logging
import warnings
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import AbstractAsyncContextManager, AsyncExitStack, asynccontextmanager
from importlib.metadata import version as importlib_version
from typing import Any, Generic
import a... | --- +++ @@ -1,3 +1,38 @@+"""MCP Server Module
+
+This module provides a framework for creating an MCP (Model Context Protocol) server.
+It allows you to easily define and handle various types of requests and notifications
+using constructor-based handler registration.
+
+Usage:
+1. Define handler functions:
+ async d... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/lowlevel/server.py |
Generate docstrings for this script |
import contextlib
import logging
from collections.abc import Callable
from dataclasses import dataclass
from types import TracebackType
from typing import Any, TypeAlias
import anyio
import httpx
from pydantic import BaseModel, Field
from typing_extensions import Self
import mcp
from mcp import types
from mcp.client... | --- +++ @@ -1,3 +1,10 @@+"""SessionGroup concurrently manages multiple MCP session connections.
+
+Tools, resources, and prompts are aggregated across servers. Servers may
+be connected to or disconnected from at any point after initialization.
+
+This abstraction can handle naming collisions using a custom user-provid... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/session_group.py |
Add docstrings to my Python code |
import logging
from typing import Any
import anyio
from mcp.server.session import ServerSession
from mcp.shared.exceptions import MCPError
from mcp.shared.experimental.tasks.helpers import RELATED_TASK_METADATA_KEY, is_terminal
from mcp.shared.experimental.tasks.message_queue import TaskMessageQueue
from mcp.shared.... | --- +++ @@ -1,3 +1,13 @@+"""TaskResultHandler - Integrated handler for tasks/result endpoint.
+
+This implements the dequeue-send-wait pattern from the MCP Tasks spec:
+1. Dequeue all pending messages for the task
+2. Send them to the client via transport with relatedRequestId routing
+3. Wait if task is not in termina... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/experimental/task_result_handler.py |
Generate docstrings for each module |
from __future__ import annotations
import logging
from collections.abc import Awaitable, Callable
from typing import Any, Generic
from typing_extensions import TypeVar
from mcp.server.context import ServerRequestContext
from mcp.server.experimental.task_support import TaskSupport
from mcp.shared.exceptions import M... | --- +++ @@ -1,3 +1,7 @@+"""Experimental handlers for the low-level MCP server.
+
+WARNING: These APIs are experimental and may change without notice.
+"""
from __future__ import annotations
@@ -40,6 +44,10 @@
class ExperimentalHandlers(Generic[LifespanResultT]):
+ """Experimental request/notification handle... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/lowlevel/experimental.py |
Document helper functions with docstrings |
from __future__ import annotations
import inspect
import typing
from collections.abc import Callable
from typing import Any
from mcp.server.mcpserver.context import Context
def find_context_parameter(fn: Callable[..., Any]) -> str | None:
# Get type hints to properly resolve string annotations
try:
... | --- +++ @@ -1,3 +1,4 @@+"""Context injection utilities for MCPServer."""
from __future__ import annotations
@@ -10,6 +11,17 @@
def find_context_parameter(fn: Callable[..., Any]) -> str | None:
+ """Find the parameter that should receive the Context object.
+
+ Searches through the function's signature to... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/utilities/context_injection.py |
Write proper docstrings for these functions |
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING, Any, TypeVar
from mcp import types
from mcp.server.validation import validate_sampling_tools, validate_tool_use_result_messages
from mcp.shared.experimental.tasks.capabilities import (
require_task_augmented_elicitation,
require_task_... | --- +++ @@ -1,3 +1,10 @@+"""Experimental server session features for server→client task operations.
+
+This module provides the server-side equivalent of ExperimentalClientFeatures,
+allowing the server to send task-augmented requests to the client and poll for results.
+
+WARNING: These APIs are experimental and may c... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/experimental/session_features.py |
Create documentation for each function signature |
class MCPServerError(Exception):
class ValidationError(MCPServerError):
class ResourceError(MCPServerError):
class ToolError(MCPServerError):
class InvalidSignature(Exception): | --- +++ @@ -1,15 +1,21 @@+"""Custom exceptions for MCPServer."""
class MCPServerError(Exception):
+ """Base error for MCPServer."""
class ValidationError(MCPServerError):
+ """Error in validating parameters or return values."""
class ResourceError(MCPServerError):
+ """Error in resource operatio... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/exceptions.py |
Add docstrings to existing functions |
import logging
from pydantic import BaseModel, Field
from starlette.requests import Request
from starlette.responses import Response
logger = logging.getLogger(__name__)
# TODO(Marcelo): We should flatten these settings. To be fair, I don't think we should even have this middleware.
class TransportSecuritySettings... | --- +++ @@ -1,3 +1,4 @@+"""DNS rebinding protection for MCP server transports."""
import logging
@@ -10,6 +11,10 @@
# TODO(Marcelo): We should flatten these settings. To be fair, I don't think we should even have this middleware.
class TransportSecuritySettings(BaseModel):
+ """Settings for MCP transport sec... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/transport_security.py |
Add return value explanations in docstrings | from __future__ import annotations
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any, Generic, Literal
from pydantic import AnyUrl, BaseModel
from mcp.server.context import LifespanContextT, RequestT, ServerRequestContext
from mcp.server.elicitation import (
ElicitationResult,
Elicit... | --- +++ @@ -20,6 +20,38 @@
class Context(BaseModel, Generic[LifespanContextT, RequestT]):
+ """Context object providing access to MCP capabilities.
+
+ This provides a cleaner interface to MCP's RequestContext functionality.
+ It gets injected into tool and resource functions that request it via type hints... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/context.py |
Create docstrings for API functions | import functools
import inspect
import json
from collections.abc import Awaitable, Callable, Sequence
from itertools import chain
from types import GenericAlias
from typing import Annotated, Any, cast, get_args, get_origin, get_type_hints
import anyio
import anyio.to_thread
import pydantic_core
from pydantic import Ba... | --- +++ @@ -30,6 +30,10 @@
class StrictJsonSchema(GenerateJsonSchema):
+ """A JSON schema generator that raises exceptions instead of emitting warnings.
+
+ This is used to detect non-serializable types during schema generation.
+ """
def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/utilities/func_metadata.py |
Add structured docstrings to improve clarity |
import sys
from contextlib import asynccontextmanager
from io import TextIOWrapper
import anyio
import anyio.lowlevel
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from mcp import types
from mcp.shared.message import SessionMessage
@asynccontextmanager
async def stdio_server(st... | --- +++ @@ -1,3 +1,21 @@+"""Stdio Server Transport Module
+
+This module provides functionality for creating an stdio-based transport layer
+that can be used to communicate with an MCP client through standard input/output
+streams.
+
+Example:
+ ```python
+ async def run_server():
+ async with stdio_server... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/stdio.py |
Document this script properly | import base64
import binascii
import hmac
import time
from typing import Any
from urllib.parse import unquote
from starlette.requests import Request
from mcp.server.auth.provider import OAuthAuthorizationServerProvider
from mcp.shared.auth import OAuthClientInformationFull
class AuthenticationError(Exception):
... | --- +++ @@ -17,11 +17,40 @@
class ClientAuthenticator:
+ """ClientAuthenticator is a callable which validates requests from a client
+ application, used to verify /token calls.
+
+ If, during registration, the client requested to be issued a secret, the
+ authenticator asserts that /token calls must be ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/auth/middleware/client_auth.py |
Document this script properly |
from enum import Enum
from typing import Any, TypeVar, overload
import anyio
import anyio.lowlevel
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from pydantic import AnyUrl, TypeAdapter
from mcp import types
from mcp.server.experimental.session_features import ExperimentalServerS... | --- +++ @@ -1,3 +1,32 @@+"""ServerSession Module
+
+This module provides the ServerSession class, which manages communication between the
+server and client in the MCP (Model Context Protocol) framework. It is most commonly
+used in MCP servers to interact with the client.
+
+Common usage pattern:
+```
+ async def h... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/session.py |
Write docstrings for backend logic | import logging
import os
import sys
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Literal, TextIO
import anyio
import anyio.lowlevel
from anyio.abc import Process
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from anyio.streams.text import T... | --- +++ @@ -49,6 +49,9 @@
def get_default_environment() -> dict[str, str]:
+ """Returns a default environment object including only environment variables deemed
+ safe to inherit.
+ """
env: dict[str, str] = {}
for key in DEFAULT_INHERITED_ENV_VARS:
@@ -100,6 +103,9 @@
@asynccontextmanager
a... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/client/stdio.py |
Generate missing documentation strings | import json
import time
from typing import Any
from pydantic import AnyHttpUrl
from starlette.authentication import AuthCredentials, AuthenticationBackend, SimpleUser
from starlette.requests import HTTPConnection
from starlette.types import Receive, Scope, Send
from mcp.server.auth.provider import AccessToken, TokenV... | --- +++ @@ -11,6 +11,7 @@
class AuthenticatedUser(SimpleUser):
+ """User with authentication info."""
def __init__(self, auth_info: AccessToken):
super().__init__(auth_info.client_id)
@@ -19,6 +20,7 @@
class BearerAuthBackend(AuthenticationBackend):
+ """Authentication backend that validat... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/auth/middleware/bearer_auth.py |
Add docstrings to clarify complex logic |
import base64
from pathlib import Path
from mcp.types import AudioContent, ImageContent
class Image:
def __init__(
self,
path: str | Path | None = None,
data: bytes | None = None,
format: str | None = None,
):
if path is None and data is None: # pragma: no cover
... | --- +++ @@ -1,3 +1,4 @@+"""Common types used across MCPServer."""
import base64
from pathlib import Path
@@ -6,6 +7,7 @@
class Image:
+ """Helper class for returning images from tools."""
def __init__(
self,
@@ -24,6 +26,7 @@ self._mime_type = self._get_mime_type()
def _get_mim... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/utilities/types.py |
Generate docstrings for this script | from dataclasses import dataclass
from typing import Generic, Literal, Protocol, TypeVar
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
from pydantic import AnyUrl, BaseModel
from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
class AuthorizationParams(BaseModel):
state: str |... | --- +++ @@ -90,8 +90,10 @@
class TokenVerifier(Protocol):
+ """Protocol for verifying bearer tokens."""
async def verify_token(self, token: str) -> AccessToken | None:
+ """Verify a bearer token and return access info if valid."""
# NOTE: MCPServer doesn't render any of these types in the user... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/auth/provider.py |
Add docstrings to incomplete code |
from __future__ import annotations
import base64
import inspect
import json
import re
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from typing import Any, Generic, Literal, TypeVar, overload
import anyio
imp... | --- +++ @@ -1,3 +1,4 @@+"""MCPServer - A more ergonomic interface for MCP servers."""
from __future__ import annotations
@@ -77,6 +78,11 @@
class Settings(BaseSettings, Generic[LifespanResultT]):
+ """MCPServer settings.
+
+ All settings can be configured via environment variables with the prefix MCP_.
+... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/server.py |
Create simple docstrings for beginners |
from __future__ import annotations
import contextlib
import logging
from collections.abc import AsyncIterator
from http import HTTPStatus
from typing import TYPE_CHECKING, Any
from uuid import uuid4
import anyio
from anyio.abc import TaskStatus
from starlette.requests import Request
from starlette.responses import R... | --- +++ @@ -1,3 +1,4 @@+"""StreamableHTTP Session Manager for MCP servers."""
from __future__ import annotations
@@ -29,6 +30,38 @@
class StreamableHTTPSessionManager:
+ """Manages StreamableHTTP sessions with optional resumability via event store.
+
+ This class abstracts away the complexity of session ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/streamable_http_manager.py |
Document classes and their methods |
from __future__ import annotations
import inspect
import re
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
from urllib.parse import unquote
from pydantic import BaseModel, Field, validate_call
from mcp.server.mcpserver.resources.types import FunctionResource, Resource
from mcp.server.mcp... | --- +++ @@ -1,3 +1,4 @@+"""Resource template functionality."""
from __future__ import annotations
@@ -20,6 +21,7 @@
class ResourceTemplate(BaseModel):
+ """A template for dynamically creating resources."""
uri_template: str = Field(description="URI template with parameters (e.g. weather://{city}/curr... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/resources/templates.py |
Add docstrings with type hints explained |
import logging
from contextlib import asynccontextmanager
from typing import Any
from urllib.parse import quote
from uuid import UUID, uuid4
import anyio
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from pydantic import ValidationError
from sse_starlette import EventSourceRespons... | --- +++ @@ -1,3 +1,40 @@+"""SSE Server Transport Module
+
+This module implements a Server-Sent Events (SSE) transport layer for MCP servers.
+
+Example:
+ ```python
+ # Create an SSE transport at an endpoint
+ sse = SseServerTransport("/messages/")
+
+ # Create Starlette routes for SSE and message handling... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/sse.py |
Help me add docstrings to my project |
import logging
import re
from abc import ABC, abstractmethod
from collections.abc import AsyncGenerator, Awaitable, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass
from http import HTTPStatus
from typing import Any
import anyio
import pydantic_core
from anyio.streams.memory impor... | --- +++ @@ -1,3 +1,10 @@+"""StreamableHTTP Server Transport Module
+
+This module implements an HTTP transport layer with Streamable HTTP.
+
+The transport handles bidirectional communication using HTTP requests and
+responses, with streaming support for long-running operations.
+"""
import logging
import re
@@ -61... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/streamable_http.py |
Can you add docstrings to this Python file? |
import logging
from typing import Literal
def get_logger(name: str) -> logging.Logger:
return logging.getLogger(name)
def configure_logging(
level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO",
) -> None:
handlers: list[logging.Handler] = []
try:
from rich.console impor... | --- +++ @@ -1,15 +1,29 @@+"""Logging utilities for MCPServer."""
import logging
from typing import Literal
def get_logger(name: str) -> logging.Logger:
+ """Get a logger nested under MCP namespace.
+
+ Args:
+ name: The name of the logger.
+
+ Returns:
+ A configured logger instance.
+ ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/utilities/logging.py |
Add docstrings for internal functions |
from typing import Generic, TypeVar, cast
import anyio
T = TypeVar("T")
class Resolver(Generic[T]):
def __init__(self) -> None:
self._event = anyio.Event()
self._value: T | None = None
self._exception: BaseException | None = None
def set_result(self, value: T) -> None:
if ... | --- +++ @@ -1,3 +1,8 @@+"""Resolver - An anyio-compatible future-like object for async result passing.
+
+This provides a simple way to pass a result (or exception) from one coroutine
+to another without depending on asyncio.Future.
+"""
from typing import Generic, TypeVar, cast
@@ -7,6 +12,19 @@
class Resolve... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/resolver.py |
Write clean docstrings for readability |
import abc
from typing import Any
from pydantic import (
BaseModel,
ConfigDict,
Field,
ValidationInfo,
field_validator,
)
from mcp.types import Annotations, Icon
class Resource(BaseModel, abc.ABC):
model_config = ConfigDict(validate_default=True)
uri: str = Field(default=..., descript... | --- +++ @@ -1,3 +1,4 @@+"""Base classes and interfaces for MCPServer resources."""
import abc
from typing import Any
@@ -14,6 +15,7 @@
class Resource(BaseModel, abc.ABC):
+ """Base class for all resources."""
model_config = ConfigDict(validate_default=True)
@@ -29,6 +31,7 @@ @field_validator("na... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/resources/base.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
import types
from collections.abc import Sequence
from typing import Generic, Literal, TypeVar, Union, get_args, get_origin
from pydantic import BaseModel
from mcp.server.session import ServerSession
from mcp.types import RequestId
ElicitSchemaModelT = TypeVar("ElicitSchemaModelT... | --- +++ @@ -1,3 +1,4 @@+"""Elicitation utilities for MCP servers."""
from __future__ import annotations
@@ -14,17 +15,20 @@
class AcceptedElicitation(BaseModel, Generic[ElicitSchemaModelT]):
+ """Result when user accepts the elicitation."""
action: Literal["accept"] = "accept"
data: ElicitSchema... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/elicitation.py |
Generate docstrings for this script |
from collections.abc import AsyncIterator, Awaitable, Callable
import anyio
from mcp.shared.experimental.tasks.helpers import is_terminal
from mcp.types import GetTaskResult
async def poll_until_terminal(
get_task: Callable[[str], Awaitable[GetTaskResult]],
task_id: str,
default_interval_ms: int = 500,... | --- +++ @@ -1,3 +1,10 @@+"""Shared polling utilities for task operations.
+
+This module provides generic polling logic that works for both client→server
+and server→client task polling.
+
+WARNING: These APIs are experimental and may change without notice.
+"""
from collections.abc import AsyncIterator, Awaitable, ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/polling.py |
Generate missing documentation strings |
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from uuid import uuid4
from mcp.shared.exceptions import MCPError
from mcp.shared.experimental.tasks.context import TaskContext
from mcp.shared.experimental.tasks.store import TaskStore
from mc... | --- +++ @@ -1,3 +1,8 @@+"""Helper functions for pure task management.
+
+These helpers work with pure TaskContext and don't require server dependencies.
+For server-integrated task helpers, use mcp.server.experimental.
+"""
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
@@ -29,... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/helpers.py |
Add docstrings to improve readability |
from typing import Any, Protocol
from mcp.types import ErrorData, RequestId
class ResponseRouter(Protocol):
def route_response(self, request_id: RequestId, response: dict[str, Any]) -> bool:
... # pragma: no cover
def route_error(self, request_id: RequestId, error: ErrorData) -> bool:
...... | --- +++ @@ -1,3 +1,17 @@+"""ResponseRouter - Protocol for pluggable response routing.
+
+This module defines a protocol for routing JSON-RPC responses to alternative
+handlers before falling back to the default response stream mechanism.
+
+The primary use case is task-augmented requests: when a TaskSession enqueues
+a... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/response_router.py |
Generate consistent docstrings |
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
import anyio
from mcp.shared.experimental.tasks.helpers import create_task_state, is_terminal
from mcp.shared.experimental.tasks.store import TaskStore
from mcp.types import Result, Task, TaskMetadata, TaskStatus
@dataclass... | --- +++ @@ -1,3 +1,11 @@+"""In-memory implementation of TaskStore for demonstration purposes.
+
+This implementation stores all tasks in memory and provides automatic cleanup
+based on the TTL duration specified in the task metadata using lazy expiration.
+
+Note: This is not suitable for production use as all data is ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/in_memory_task_store.py |
Can you add docstrings to this Python file? | import contextvars
from starlette.types import ASGIApp, Receive, Scope, Send
from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
from mcp.server.auth.provider import AccessToken
# Create a contextvar to store the authenticated user
# The default is None, indicating no authenticated user is present
a... | --- +++ @@ -11,11 +11,23 @@
def get_access_token() -> AccessToken | None:
+ """Get the access token from the current context.
+
+ Returns:
+ The access token if an authenticated user is available, None otherwise.
+ """
auth_user = auth_context_var.get()
return auth_user.access_token if aut... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/auth/middleware/auth_context.py |
Generate descriptive docstrings automatically | from collections.abc import Awaitable, Callable
from typing import Any
from urllib.parse import urlparse
from pydantic import AnyHttpUrl
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route, request_resp... | --- +++ @@ -22,6 +22,14 @@
def validate_issuer_url(url: AnyHttpUrl):
+ """Validate that the issuer URL meets OAuth 2.0 requirements.
+
+ Args:
+ url: The issuer URL to validate.
+
+ Raises:
+ ValueError: If the issuer URL is invalid.
+ """
# RFC 8414 requires HTTPS, but we allow loo... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/auth/routes.py |
Create docstrings for reusable components |
import inspect
import json
from collections.abc import Callable
from pathlib import Path
from typing import Any
import anyio
import anyio.to_thread
import httpx
import pydantic
import pydantic_core
from pydantic import Field, ValidationInfo, validate_call
from mcp.server.mcpserver.resources.base import Resource
from... | --- +++ @@ -1,3 +1,4 @@+"""Concrete resource implementations."""
import inspect
import json
@@ -17,26 +18,42 @@
class TextResource(Resource):
+ """A resource that reads from a string."""
text: str = Field(description="Text content of the resource")
async def read(self) -> str:
+ """Read ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/resources/types.py |
Help me write clear docstrings |
from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
from pydantic import AnyUrl
from mcp.server.mcpserver.resources.base import Resource
from mcp.server.mcpserver.resources.templates import ResourceTemplate
from mcp.server.mcpserver.utilities.logging import ... | --- +++ @@ -1,3 +1,4 @@+"""Resource manager functionality."""
from __future__ import annotations
@@ -19,6 +20,7 @@
class ResourceManager:
+ """Manages MCPServer resources."""
def __init__(self, warn_on_duplicate_resources: bool = True):
self._resources: dict[str, Resource] = {}
@@ -26,6 +28,... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/server/mcpserver/resources/resource_manager.py |
Generate docstrings for exported functions | # babyagi/dashboard/__init__.py
from flask import Blueprint, render_template, g, send_from_directory
import logging
import os
logger = logging.getLogger(__name__)
def create_dashboard(func_instance, dashboard_route):
if func_instance is None:
raise ValueError("func_instance cannot be None")
if dashbo... | --- +++ @@ -21,6 +21,7 @@
@dashboard.before_request
def before_request():
+ """Set up the necessary context before each request."""
g.functionz = func_instance
g.dashboard_route = dashboard_route
logger.debug("Set g.functionz and g.dashboard_route for the request context.")
... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/dashboard/__init__.py |
Add docstrings to clarify complex logic |
from mcp.shared.experimental.tasks.store import TaskStore
from mcp.types import TASK_STATUS_COMPLETED, TASK_STATUS_FAILED, Result, Task
class TaskContext:
def __init__(self, task: Task, store: TaskStore):
self._task = task
self._store = store
self._cancelled = False
@property
de... | --- +++ @@ -1,9 +1,35 @@+"""TaskContext - Pure task state management.
+
+This module provides TaskContext, which manages task state without any
+server/session dependencies. It can be used standalone for distributed
+workers or wrapped by ServerTaskContext for full server integration.
+"""
from mcp.shared.experiment... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/experimental/tasks/context.py |
Add structured docstrings to improve clarity | # babyagi/__init__.py
from flask import Flask, g
from .functionz.core.framework import Functionz
from .dashboard import create_dashboard
from .api import create_api_blueprint
import os
import importlib.util
import traceback
import sys
# Singleton instance of the functionz framework
_func_instance = Functionz()
def ... | --- +++ @@ -80,6 +80,13 @@
def use_blueprints(app, dashboard_route='/dashboard'):
+ """
+ Registers the babyagi blueprints with the provided Flask app.
+
+ Args:
+ app (Flask): The Flask application instance.
+ dashboard_route (str): The route prefix for the dashboard.
+ """
# Remove ... | https://raw.githubusercontent.com/yoheinakajima/babyagi/HEAD/babyagi/__init__.py |
Expand my code with proper documentation strings |
from __future__ import annotations
import logging
import re
from dataclasses import dataclass, field
logger = logging.getLogger(__name__)
# Regular expression for valid tool names according to SEP-986 specification
TOOL_NAME_REGEX = re.compile(r"^[A-Za-z0-9._-]{1,128}$")
# SEP reference URL for warning messages
SE... | --- +++ @@ -1,3 +1,13 @@+"""Tool name validation utilities according to SEP-986.
+
+Tool names SHOULD be between 1 and 128 characters in length (inclusive).
+Tool names are case-sensitive.
+Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z),
+digits (0-9), underscore (_), dash (-), and dot (.).
+Tool ... | https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/HEAD/src/mcp/shared/tool_name_validation.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.