instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add docstrings including usage examples |
from abc import ABC, abstractmethod
class CrossEncoderClient(ABC):
@abstractmethod
async def rank(self, query: str, passages: list[str]) -> list[tuple[str, float]]:
pass | --- +++ @@ -1,9 +1,40 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/cross_encoder/client.py |
Help me add docstrings to my project |
from __future__ import annotations
def domain_name_1(url: str) -> str:
full_domain_name = url.split("//")[-1]
actual_domain = full_domain_name.split(".")
if len(actual_domain) > 2:
return actual_domain[1]
return actual_domain[0]
def domain_name_2(url: str) -> str:
return url.split("//")... | --- +++ @@ -1,8 +1,32 @@+"""
+Domain Name Extractor
+
+Given a URL as a string, parse out just the domain name and return it.
+Uses only the .split() built-in function without regex or urlparse.
+
+Reference: https://en.wikipedia.org/wiki/Domain_name
+
+Complexity:
+ Time: O(n) where n is the length of the URL
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/domain_extractor.py |
Please document this code using docstrings |
import asyncio
import datetime
import logging
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from falkordb import Graph as FalkorGraph
from falkordb.asyncio import FalkorDB
else:
try:
from falkordb import Graph as FalkorGraph
from falkordb.asyncio import FalkorDB
except Import... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/falkordb_driver.py |
Create docstrings for API functions |
import asyncio
import os
import re
from collections.abc import Coroutine
from datetime import datetime
from typing import Any
import numpy as np
from dotenv import load_dotenv
from neo4j import time as neo4j_time
from numpy._typing import NDArray
from pydantic import BaseModel
from graphiti_core.driver.driver import... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/helpers.py |
Write docstrings for utility functions |
import asyncio
import datetime
import logging
from collections.abc import Coroutine
from typing import Any
import boto3
from langchain_aws.graphs import NeptuneAnalyticsGraph, NeptuneGraph
from opensearchpy import OpenSearch, Urllib3AWSV4SignerAuth, Urllib3HttpConnection, helpers
from graphiti_core.driver.driver imp... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/neptune_driver.py |
Document classes and their methods |
from collections.abc import Iterable
from openai import AsyncAzureOpenAI, AsyncOpenAI
from openai.types import EmbeddingModel
from .client import EmbedderClient, EmbedderConfig
DEFAULT_EMBEDDING_MODEL = 'text-embedding-3-small'
class OpenAIEmbedderConfig(EmbedderConfig):
embedding_model: EmbeddingModel | str ... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/embedder/openai.py |
Add docstrings explaining edge cases |
import logging
from collections.abc import Iterable
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from google import genai
from google.genai import types
else:
try:
from google import genai
from google.genai import types
except ImportError:
raise ImportError(
'... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/embedder/gemini.py |
Generate helpful docstrings for debugging |
from typing import Any
from pydantic import BaseModel
class SearchInterface(BaseModel):
async def edge_fulltext_search(
self,
driver: Any,
query: str,
search_filter: Any,
group_ids: list[str] | None = None,
limit: int = 100,
) -> list[Any]:
raise NotI... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/search_interface/search_interface.py |
Add docstrings to improve readability |
import logging
from typing import Any
from openai import AsyncAzureOpenAI, AsyncOpenAI
from .client import EmbedderClient
logger = logging.getLogger(__name__)
class AzureOpenAIEmbedderClient(EmbedderClient):
def __init__(
self,
azure_client: AsyncAzureOpenAI | AsyncOpenAI,
model: str ... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/embedder/azure_openai.py |
Turn comments into proper docstrings |
from abc import ABC, abstractmethod
from typing import Any
class Transaction(ABC):
@abstractmethod
async def run(self, query: str, **kwargs: Any) -> Any: ...
class QueryExecutor(ABC):
@abstractmethod
async def execute_query(self, cypher_query_: str, **kwargs: Any) -> Any: ... | --- +++ @@ -1,15 +1,41 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicab... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/query_executor.py |
Add docstrings for better understanding |
from typing import Any
from pydantic import BaseModel
class GraphOperationsInterface(BaseModel):
# -----------------
# Node: Save/Delete
# -----------------
async def node_save(self, node: Any, driver: Any) -> None:
raise NotImplementedError
async def node_delete(self, node: Any, driv... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/graph_operations/graph_operations.py |
Write docstrings describing functionality |
from __future__ import annotations
def first_unique_char(text: str) -> int:
if len(text) == 1:
return 0
banned: list[str] = []
for index in range(len(text)):
if (
all(text[index] != text[other] for other in range(index + 1, len(text)))
and text[index] not in banned... | --- +++ @@ -1,8 +1,32 @@+"""
+First Unique Character in a String
+
+Given a string, find the first non-repeating character and return its index.
+If no unique character exists, return -1.
+
+Reference: https://leetcode.com/problems/first-unique-character-in-a-string/
+
+Complexity:
+ Time: O(n^2) worst case due to ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/first_unique_char.py |
Generate consistent documentation across files |
class GraphitiError(Exception):
class EdgeNotFoundError(GraphitiError):
def __init__(self, uuid: str):
self.message = f'edge {uuid} not found'
super().__init__(self.message)
class EdgesNotFoundError(GraphitiError):
def __init__(self, uuids: list[str]):
self.message = f'None of th... | --- +++ @@ -1,9 +1,26 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/errors.py |
Annotate my code with docstrings |
from __future__ import annotations
class Node:
def __init__(self, x: int) -> None:
self.val = x
self.next: Node | None = None
def delete_node(node: Node | None) -> None:
if node is None or node.next is None:
raise ValueError
node.val = node.next.val
node.next = node.next.nex... | --- +++ @@ -1,3 +1,15 @@+"""
+Delete Node in a Linked List
+
+Given only access to a node (not the tail) in a singly linked list, delete
+that node by copying the next node's value and skipping over it.
+
+Reference: https://leetcode.com/problems/delete-node-in-a-linked-list/
+
+Complexity:
+ Time: O(1)
+ Space:... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/delete_node.py |
Provide clean and structured docstrings |
def lowest_common_ancestor(root, p, q):
while root:
if p.val > root.val < q.val:
root = root.right
elif p.val < root.val > q.val:
root = root.left
else:
return root | --- +++ @@ -1,10 +1,37 @@+"""
+Given a binary search tree (BST),
+find the lowest common ancestor (LCA) of two given nodes in the BST.
+
+According to the definition of LCA on Wikipedia:
+ “The lowest common ancestor is defined between two
+ nodes v and w as the lowest node in T that has both v and w
+ as desc... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/bst_lowest_common_ancestor.py |
Add docstrings to clarify complex logic |
import json
import logging
from abc import ABC, abstractmethod
from datetime import datetime
from enum import Enum
from time import time
from typing import Any
from uuid import uuid4
from pydantic import BaseModel, ConfigDict, Field, field_validator
from typing_extensions import LiteralString
from graphiti_core.driv... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/nodes.py |
Write beginner-friendly docstrings |
from graphiti_core.driver.driver import GraphDriver
from graphiti_core.driver.operations.community_edge_ops import CommunityEdgeOperations
from graphiti_core.driver.operations.entity_edge_ops import EntityEdgeOperations
from graphiti_core.driver.operations.episodic_edge_ops import EpisodicEdgeOperations
from graphiti_... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/namespaces/edges.py |
Write docstrings describing each step |
from datetime import datetime
from graphiti_core.driver.driver import GraphDriver
from graphiti_core.driver.operations.community_node_ops import CommunityNodeOperations
from graphiti_core.driver.operations.entity_node_ops import EntityNodeOperations
from graphiti_core.driver.operations.episode_node_ops import Episode... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/namespaces/nodes.py |
Expand my code with proper documentation strings |
import json
import logging
import os
import typing
from json import JSONDecodeError
from typing import TYPE_CHECKING, Literal
from pydantic import BaseModel, ValidationError
from ..prompts.models import Message
from .client import LLMClient
from .config import DEFAULT_MAX_TOKENS, LLMConfig, ModelSize
from .errors im... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/anthropic_client.py |
Document functions with clear intent |
import json
import logging
from typing import Any, ClassVar
from openai import AsyncAzureOpenAI, AsyncOpenAI
from openai.types.chat import ChatCompletionMessageParam
from pydantic import BaseModel
from .config import DEFAULT_MAX_TOKENS, LLMConfig
from .openai_base_client import BaseOpenAIClient
logger = logging.get... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/azure_openai_client.py |
Help me comply with documentation standards |
import hashlib
import json
import logging
import typing
from abc import ABC, abstractmethod
import httpx
from pydantic import BaseModel
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_random_exponential
from ..prompts.models import Message
from ..tracer import NoOpTracer, Tracer
from .cache ... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/client.py |
Add docstrings to improve code quality |
import contextlib
import os
import platform
import sys
import uuid
from pathlib import Path
from typing import Any
# PostHog configuration
# Note: This is a public API key intended for client-side use and safe to commit
# PostHog public keys are designed to be exposed in client applications
POSTHOG_API_KEY = 'phc_UG6... | --- +++ @@ -1,3 +1,8 @@+"""
+Telemetry client for Graphiti.
+
+Collects anonymous usage statistics to help improve the product.
+"""
import contextlib
import os
@@ -22,6 +27,7 @@
def is_telemetry_enabled() -> bool:
+ """Check if telemetry is enabled."""
# Disable during pytest runs
if 'pytest' in s... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/telemetry/telemetry.py |
Add verbose docstrings with examples |
from enum import Enum
DEFAULT_MAX_TOKENS = 16384
DEFAULT_TEMPERATURE = 1
class ModelSize(Enum):
small = 'small'
medium = 'medium'
class LLMConfig:
def __init__(
self,
api_key: str | None = None,
model: str | None = None,
base_url: str | None = None,
temperature... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/config.py |
Create docstrings for all classes and functions |
import contextlib
import json
import logging
import os
import sqlite3
import typing
logger = logging.getLogger(__name__)
class LLMCache:
def __init__(self, directory: str):
os.makedirs(directory, exist_ok=True)
db_path = os.path.join(directory, 'cache.db')
self._conn = sqlite3.connect(d... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/cache.py |
Add docstrings to improve code quality |
import logging
from datetime import datetime
from typing_extensions import LiteralString
from graphiti_core.driver.driver import GraphDriver, GraphProvider
from graphiti_core.models.nodes.node_db_queries import (
EPISODIC_NODE_RETURN,
EPISODIC_NODE_RETURN_NEPTUNE,
)
from graphiti_core.nodes import EpisodeTyp... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/maintenance/graph_data_operations.py |
Generate descriptive docstrings automatically |
from abc import ABC, abstractmethod
from collections.abc import Generator
from contextlib import AbstractContextManager, contextmanager, suppress
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from opentelemetry.trace import Span, StatusCode
try:
from opentelemetry.trace import Span, StatusCode
... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/tracer.py |
Add docstrings to improve collaboration |
import ast
import asyncio
import json
import logging
import re
import typing
from time import perf_counter
from typing import TYPE_CHECKING
from pydantic import BaseModel
from ..prompts.models import Message
from .client import LLMClient
from .config import DEFAULT_MAX_TOKENS, LLMConfig, ModelSize
from .errors impor... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/gliner2_client.py |
Improve my code by adding docstrings |
class RateLimitError(Exception):
def __init__(self, message='Rate limit exceeded. Please try again later.'):
self.message = message
super().__init__(self.message)
class RefusalError(Exception):
def __init__(self, message: str):
self.message = message
super().__init__(self.m... | --- +++ @@ -1,6 +1,22 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/errors.py |
Create docstrings for each class method |
from graphiti_core.edges import EntityEdge
from graphiti_core.prompts.prompt_helpers import to_prompt_json
from graphiti_core.search.search_config import SearchResults
def format_edge_date_range(edge: EntityEdge) -> str:
# return f"{datetime(edge.valid_at).strftime('%Y-%m-%d %H:%M:%S') if edge.valid_at else 'dat... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/search/search_helpers.py |
Fill in missing docstrings in my code |
import logging
from collections.abc import Awaitable, Callable
from time import time
from typing import Any
from pydantic import BaseModel
from graphiti_core.edges import EntityEdge
from graphiti_core.graphiti_types import GraphitiClients
from graphiti_core.helpers import semaphore_gather
from graphiti_core.llm_clie... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/maintenance/node_operations.py |
Add docstrings for utility scripts |
import json
from typing import Any
DO_NOT_ESCAPE_UNICODE = '\nDo not escape unicode characters.\n'
def to_prompt_json(data: Any, ensure_ascii: bool = False, indent: int | None = None) -> str:
return json.dumps(data, ensure_ascii=ensure_ascii, indent=indent) | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/prompts/prompt_helpers.py |
Add minimal docstrings for each function |
import json
import logging
import re
import typing
from typing import TYPE_CHECKING, ClassVar
from pydantic import BaseModel
from ..prompts.models import Message
from .client import LLMClient, get_extraction_language_instruction
from .config import LLMConfig, ModelSize
from .errors import RateLimitError
if TYPE_CHE... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/gemini_client.py |
Provide clean and structured docstrings |
from __future__ import annotations
import math
import re
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass, field
from functools import lru_cache
from hashlib import blake2b
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from graphiti_core.nodes import... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/maintenance/dedup_helpers.py |
Generate missing documentation strings |
import typing
from openai import AsyncOpenAI
from openai.types.chat import ChatCompletionMessageParam
from pydantic import BaseModel
from .config import DEFAULT_MAX_TOKENS, LLMConfig
from .openai_base_client import DEFAULT_REASONING, DEFAULT_VERBOSITY, BaseOpenAIClient
class OpenAIClient(BaseOpenAIClient):
de... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/openai_client.py |
Generate NumPy-style docstrings |
import logging
from datetime import datetime
from time import time
from pydantic import BaseModel
from typing_extensions import LiteralString
from graphiti_core.driver.driver import GraphDriver, GraphProvider
from graphiti_core.edges import (
CommunityEdge,
EntityEdge,
EpisodicEdge,
create_entity_edg... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/maintenance/edge_operations.py |
Generate consistent documentation across files |
from dataclasses import dataclass
from threading import Lock
@dataclass
class TokenUsage:
input_tokens: int = 0
output_tokens: int = 0
@property
def total_tokens(self) -> int:
return self.input_tokens + self.output_tokens
@dataclass
class PromptTokenUsage:
prompt_name: str
call_c... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/token_tracker.py |
Add clean documentation to messy code |
import re
# Maximum length for entity/node summaries
MAX_SUMMARY_CHARS = 500
def truncate_at_sentence(text: str, max_chars: int) -> str:
if not text or len(text) <= max_chars:
return text
# Find all sentence boundaries (., !, ?) up to max_chars
truncated = text[:max_chars]
# Look for sente... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/text_utils.py |
Insert docstrings into my code |
import json
import logging
import typing
from typing import Any, ClassVar
import openai
from openai import AsyncOpenAI
from openai.types.chat import ChatCompletionMessageParam
from pydantic import BaseModel
from ..prompts.models import Message
from .client import LLMClient, get_extraction_language_instruction
from .... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/openai_generic_client.py |
Add docstrings to incomplete code |
import json
import logging
import typing
from datetime import datetime
import numpy as np
from pydantic import BaseModel, Field
from typing_extensions import Any
from graphiti_core.driver.driver import (
GraphDriver,
GraphDriverSession,
GraphProvider,
)
from graphiti_core.edges import Edge, EntityEdge, E... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/bulk_utils.py |
Create simple docstrings for beginners |
from enum import Enum
from pydantic import BaseModel, Field
from graphiti_core.edges import EntityEdge
from graphiti_core.nodes import CommunityNode, EntityNode, EpisodicNode
from graphiti_core.search.search_utils import (
DEFAULT_MIN_SCORE,
DEFAULT_MMR_LAMBDA,
MAX_SEARCH_DEPTH,
)
DEFAULT_SEARCH_LIMIT =... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/search/search_config.py |
Write docstrings for backend logic |
import logging
from collections import defaultdict
from time import time
from typing import Any
import numpy as np
from numpy._typing import NDArray
from typing_extensions import LiteralString
from graphiti_core.driver.driver import (
GraphDriver,
GraphProvider,
)
from graphiti_core.edges import EntityEdge, ... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/search/search_utils.py |
Generate missing documentation strings |
import json
import logging
import typing
from abc import abstractmethod
from typing import Any, ClassVar
import openai
from openai.types.chat import ChatCompletionMessageParam
from pydantic import BaseModel
from ..prompts.models import Message
from .client import LLMClient, get_extraction_language_instruction
from .... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/llm_client/openai_base_client.py |
Add docstrings that explain purpose and usage |
from typing import Any
from graphiti_core.edges import EntityEdge
from graphiti_core.nodes import EntityNode
def format_node_result(node: EntityNode) -> dict[str, Any]:
result = node.model_dump(
mode='json',
exclude={
'name_embedding',
},
)
# Remove any embedding that... | --- +++ @@ -1,3 +1,4 @@+"""Formatting utilities for Graphiti MCP Server."""
from typing import Any
@@ -6,6 +7,17 @@
def format_node_result(node: EntityNode) -> dict[str, Any]:
+ """Format an entity node into a readable result.
+
+ Since EntityNode is a Pydantic BaseModel, we can use its built-in serializ... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/mcp_server/src/utils/formatting.py |
Add docstrings following best practices |
import json
import logging
import random
import re
from itertools import combinations
from math import comb
from typing import TypeVar
from graphiti_core.helpers import (
CHUNK_DENSITY_THRESHOLD,
CHUNK_MIN_TOKENS,
CHUNK_OVERLAP_TOKENS,
CHUNK_TOKEN_SIZE,
)
from graphiti_core.nodes import EpisodeType
l... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/content_chunking.py |
Document this module using docstrings |
from collections.abc import Callable
def create_azure_credential_token_provider() -> Callable[[], str]:
try:
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
except ImportError:
raise ImportError(
'azure-identity is required for Azure AD authentication.... | --- +++ @@ -1,8 +1,17 @@+"""Utility functions for Graphiti MCP Server."""
from collections.abc import Callable
def create_azure_credential_token_provider() -> Callable[[], str]:
+ """
+ Create Azure credential token provider for managed identity authentication.
+
+ Requires azure-identity package. Inst... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/mcp_server/src/utils/utils.py |
Document my Python code with docstrings |
from datetime import datetime, timezone
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def ensure_utc(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is None:
# If datetime is naive, assume it's UTC
return dt.replace(tzinfo=timezon... | --- +++ @@ -1,12 +1,34 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicab... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/utils/datetime_utils.py |
Provide docstrings following PEP 257 | #!/usr/bin/env python3
import argparse
import asyncio
import logging
import os
import sys
from pathlib import Path
from typing import Any, Optional
from dotenv import load_dotenv
from graphiti_core import Graphiti
from graphiti_core.edges import EntityEdge
from graphiti_core.nodes import EpisodeType, EpisodicNode
fro... | --- +++ @@ -1,4 +1,7 @@ #!/usr/bin/env python3
+"""
+Graphiti MCP Server - Exposes Graphiti functionality through the Model Context Protocol (MCP)
+"""
import argparse
import asyncio
@@ -93,6 +96,7 @@
# Patch uvicorn's logging config to use our format
def configure_uvicorn_logging():
+ """Configure uvicorn lo... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/mcp_server/src/graphiti_mcp_server.py |
Generate docstrings for this script |
import asyncio
import logging
from collections.abc import Awaitable, Callable
from datetime import datetime, timezone
from typing import Any
logger = logging.getLogger(__name__)
class QueueService:
def __init__(self):
# Dictionary to store queues for each group_id
self._episode_queues: dict[str... | --- +++ @@ -1,3 +1,4 @@+"""Queue service for managing episode processing."""
import asyncio
import logging
@@ -9,8 +10,10 @@
class QueueService:
+ """Service for managing sequential episode processing queues by group_id."""
def __init__(self):
+ """Initialize the queue service."""
# Di... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/mcp_server/src/services/queue_service.py |
Create documentation strings for testing functions |
import os
from pathlib import Path
from typing import Any
import yaml
from pydantic import BaseModel, Field
from pydantic_settings import (
BaseSettings,
PydanticBaseSettingsSource,
SettingsConfigDict,
)
class YamlSettingsSource(PydanticBaseSettingsSource):
def __init__(self, settings_cls: type[Bas... | --- +++ @@ -1,3 +1,4 @@+"""Configuration schemas with pydantic-settings and YAML support."""
import os
from pathlib import Path
@@ -13,12 +14,14 @@
class YamlSettingsSource(PydanticBaseSettingsSource):
+ """Custom settings source for loading from YAML files."""
def __init__(self, settings_cls: type[Ba... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/mcp_server/src/config/schema.py |
Write docstrings for utility functions |
from pydantic import BaseModel, Field
class Requirement(BaseModel):
project_name: str = Field(
...,
description='The name of the project to which the requirement belongs.',
)
description: str = Field(
...,
description='Description of the requirement. Only use information ... | --- +++ @@ -1,8 +1,25 @@+"""Entity type definitions for Graphiti MCP Server."""
from pydantic import BaseModel, Field
class Requirement(BaseModel):
+ """A Requirement represents a specific need, feature, or functionality that a product or service must fulfill.
+
+ Always ensure an edge is created between ... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/mcp_server/src/models/entity_types.py |
Generate missing documentation strings |
from config.schema import (
DatabaseConfig,
EmbedderConfig,
LLMConfig,
)
# Try to import FalkorDriver if available
try:
from graphiti_core.driver.falkordb_driver import FalkorDriver # noqa: F401
HAS_FALKOR = True
except ImportError:
HAS_FALKOR = False
# Kuzu support removed - FalkorDB is no... | --- +++ @@ -1,3 +1,4 @@+"""Factory classes for creating LLM, Embedder, and Database clients."""
from config.schema import (
DatabaseConfig,
@@ -70,6 +71,19 @@
def _validate_api_key(provider_name: str, api_key: str | None, logger) -> str:
+ """Validate API key is present.
+
+ Args:
+ provider_na... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/mcp_server/src/services/factories.py |
Create structured documentation for my script | import abc
import contextlib
import datetime
from collections.abc import AsyncIterator
from typing import Literal, TypeVar
import httpx
import mcp.types
from mcp import ClientSession
from mcp.client.session import (
ElicitationFnT,
ListRootsFnT,
LoggingFnT,
MessageHandlerFnT,
SamplingFnT,
)
from ty... | --- +++ @@ -21,6 +21,7 @@
class SessionKwargs(TypedDict, total=False):
+ """Keyword arguments for the MCP ClientSession constructor."""
read_timeout_seconds: datetime.timedelta | None
sampling_callback: SamplingFnT | None
@@ -33,12 +34,35 @@
class ClientTransport(abc.ABC):
+ """
+ Abstract ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/transports/base.py |
Fully document this Python code with docstrings |
from __future__ import annotations
import functools
import inspect
import warnings
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar, runtime_checkable
from mcp.types import Annotations, Icon
from pydantic import AnyUrl
fro... | --- +++ @@ -1,3 +1,4 @@+"""Standalone @resource decorator for FastMCP."""
from __future__ import annotations
@@ -37,6 +38,7 @@
@runtime_checkable
class DecoratedResource(Protocol):
+ """Protocol for functions decorated with @resource."""
__fastmcp__: ResourceMeta
@@ -45,6 +47,7 @@
@dataclass(froze... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/resources/function_resource.py |
Add docstrings to make code maintainable |
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from mcp.server.auth.handlers.authorize import (
AuthorizationHandler as SDKAuthorizationHandler,
)
from pydantic import AnyHttpUrl
from starlette.requests import Request
from starlette.responses import Response
from fastmcp.utiliti... | --- +++ @@ -1,3 +1,15 @@+"""Enhanced authorization handler with improved error responses.
+
+This module provides an enhanced authorization handler that wraps the MCP SDK's
+AuthorizationHandler to provide better error messages when clients attempt to
+authorize with unregistered client IDs.
+
+The enhancement adds:
+-... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/handlers/authorize.py |
Generate documentation strings for clarity |
import asyncio
import sys
from typing import Annotated
import cyclopts
from rich.console import Console
from fastmcp.utilities.cli import load_and_merge_config
from fastmcp.utilities.logging import get_logger
logger = get_logger("cli.tasks")
console = Console()
tasks_app = cyclopts.App(
name="tasks",
help=... | --- +++ @@ -1,3 +1,4 @@+"""FastMCP tasks CLI for Docket task management."""
import asyncio
import sys
@@ -19,6 +20,14 @@
def check_distributed_backend() -> None:
+ """Check if Docket is configured with a distributed backend.
+
+ The CLI worker runs as a separate process, so it needs Redis/Valkey
+ to c... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/tasks.py |
Add docstrings for production code | #!/usr/bin/env python
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "httpx",
# ]
# ///
import os
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import httpx
@dataclass
class Issue:
number: int
title: str
state: str
created_at: str
user_... | --- +++ @@ -5,6 +5,13 @@ # "httpx",
# ]
# ///
+"""
+Auto-close issues that need MRE (Minimal Reproducible Example).
+
+This script runs on a schedule to automatically close issues that have been
+marked as "needs MRE" and haven't received activity from the issue author
+within 7 days.
+"""
import os
from data... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/scripts/auto_close_needs_mre.py |
Write docstrings for backend logic | import asyncio
import contextlib
import os
import shutil
import sys
from collections.abc import AsyncIterator
from pathlib import Path
from typing import TextIO, cast
import anyio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from typing_extensions import Unpack
from f... | --- +++ @@ -20,6 +20,12 @@
class StdioTransport(ClientTransport):
+ """
+ Base transport for connecting to an MCP server via subprocess with stdio.
+
+ This is a base class that can be subclassed for specific command-based
+ transports like Python, Node, Uvx, etc.
+ """
def __init__(
... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/transports/stdio.py |
Add docstrings with type hints explained |
from __future__ import annotations
import uuid
import weakref
from typing import TYPE_CHECKING, Any, Literal, overload
import mcp.types
import pydantic_core
from pydantic import RootModel
if TYPE_CHECKING:
from fastmcp.client.client import Client
from fastmcp.client.tasks import PromptTask
from fastmcp.client.... | --- +++ @@ -1,3 +1,4 @@+"""Prompt-related methods for FastMCP Client."""
from __future__ import annotations
@@ -28,12 +29,26 @@
class ClientPromptsMixin:
+ """Mixin providing prompt-related methods for Client."""
# --- Prompts ---
async def list_prompts_mcp(
self: Client, *, cursor: s... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/mixins/prompts.py |
Write docstrings for backend logic |
from mcp import McpError # noqa: F401
class FastMCPError(Exception):
class ValidationError(FastMCPError):
class ResourceError(FastMCPError):
class ToolError(FastMCPError):
class PromptError(FastMCPError):
class InvalidSignature(Exception):
class ClientError(Exception):
class NotFoundError(Exception):
... | --- +++ @@ -1,32 +1,43 @@+"""Custom exceptions for FastMCP."""
from mcp import McpError # noqa: F401
class FastMCPError(Exception):
+ """Base error for FastMCP."""
class ValidationError(FastMCPError):
+ """Error in validating parameters or return values."""
class ResourceError(FastMCPError):
+ ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/exceptions.py |
Document this script properly | from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, cast
from urllib.parse import urlparse
from mcp.server.auth.handlers.token import TokenErrorResponse
from mcp.server.auth.handlers.token import TokenHandler as _SDKTokenHandler
from mcp.server.auth.json_response import PydanticJSONR... | --- +++ @@ -52,13 +52,29 @@
class AccessToken(_SDKAccessToken):
+ """AccessToken that includes all JWT claims."""
claims: dict[str, Any] = Field(default_factory=dict)
class TokenHandler(_SDKTokenHandler):
+ """TokenHandler that returns MCP-compliant error responses.
+
+ This handler addresses t... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/auth.py |
Create docstrings for each class method |
from collections.abc import Iterator, Sequence
from typing import Any
from mcp.types import CreateMessageRequestParams as SamplingParams
from mcp.types import (
CreateMessageResult,
CreateMessageResultWithTools,
ModelPreferences,
SamplingMessage,
SamplingMessageContentBlock,
StopReason,
Te... | --- +++ @@ -1,3 +1,4 @@+"""Anthropic sampling handler for FastMCP."""
from collections.abc import Iterator, Sequence
from typing import Any
@@ -43,6 +44,22 @@
class AnthropicSamplingHandler:
+ """Sampling handler that uses the Anthropic API.
+
+ Example:
+ ```python
+ from anthropic import A... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/sampling/handlers/anthropic.py |
Help me add docstrings to my project |
import json
from collections.abc import Iterator, Sequence
from typing import Any, get_args
from mcp import ClientSession, ServerSession
from mcp.shared.context import LifespanContextT, RequestContext
from mcp.types import CreateMessageRequestParams as SamplingParams
from mcp.types import (
CreateMessageResult,
... | --- +++ @@ -1,3 +1,4 @@+"""OpenAI sampling handler for FastMCP."""
import json
from collections.abc import Iterator, Sequence
@@ -42,6 +43,7 @@
class OpenAISamplingHandler:
+ """Sampling handler that uses the OpenAI API."""
def __init__(
self,
@@ -304,6 +306,7 @@
@staticmethod
def ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/sampling/handlers/openai.py |
Add structured docstrings to improve clarity |
from __future__ import annotations
import inspect
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
if TYPE_CHECKING:
from fastmcp.prompts.function_prompt import PromptMeta
from fastmcp.resources.function_resource import ResourceMeta
from fastmcp.server.tasks.config import TaskConfig
... | --- +++ @@ -1,3 +1,4 @@+"""Shared decorator utilities for FastMCP."""
from __future__ import annotations
@@ -14,16 +15,19 @@
def resolve_task_config(task: bool | TaskConfig | None) -> bool | TaskConfig:
+ """Resolve task config, defaulting None to False."""
return task if task is not None else False
... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/decorators.py |
Generate docstrings for script automation | import importlib
import json
from collections.abc import Awaitable, Callable, Sequence
from typing import Annotated, Any, Literal, Protocol
from mcp.types import TextContent
from pydantic import Field
from fastmcp.exceptions import NotFoundError
from fastmcp.server.context import Context
from fastmcp.server.transform... | --- +++ @@ -48,6 +48,11 @@
def _unwrap_tool_result(result: ToolResult) -> dict[str, Any] | str:
+ """Convert a ToolResult for use in the sandbox.
+
+ - Output schema present → structured_content dict (matches the schema)
+ - Otherwise → concatenated text content as a string
+ """
if result.structur... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/experimental/transforms/code_mode.py |
Generate NumPy-style docstrings |
from __future__ import annotations
import hashlib
from typing import Any, Final
from mcp.shared.auth import InvalidRedirectUriError, OAuthClientInformationFull
from pydantic import AnyUrl, BaseModel, Field
from fastmcp.server.auth.cimd import CIMDDocument
from fastmcp.server.auth.redirect_validation import (
ma... | --- +++ @@ -1,3 +1,7 @@+"""OAuth Proxy Models and Constants.
+
+This module contains all Pydantic models and constants used by the OAuth proxy.
+"""
from __future__ import annotations
@@ -34,6 +38,11 @@
class OAuthTransaction(BaseModel):
+ """OAuth transaction state for consent flow.
+
+ Stored server-si... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/oauth_proxy/models.py |
Help me add docstrings to my project |
import json
import sys
from pathlib import Path
from typing import Annotated
import cyclopts
import pyperclip
from rich import print
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironment
from .shared import process_common_args
logger = get... | --- +++ @@ -1,3 +1,4 @@+"""MCP configuration JSON generation for FastMCP install using Cyclopts."""
import json
import sys
@@ -29,6 +30,23 @@ with_requirements: Path | None = None,
project: Path | None = None,
) -> bool:
+ """Generate MCP configuration JSON for manual installation.
+
+ Args:
+ ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/install/mcp_json.py |
Generate descriptive docstrings automatically |
from __future__ import annotations
import functools
import inspect
import re
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, ClassVar, overload
from urllib.parse import parse_qs, unquote
import mcp.types
from mcp.types import Annotations, Icon
from pydantic.json_schema import SkipJsonSche... | --- +++ @@ -1,3 +1,4 @@+"""Resource template functionality."""
from __future__ import annotations
@@ -36,6 +37,7 @@
def extract_query_params(uri_template: str) -> set[str]:
+ """Extract query parameter names from RFC 6570 `{?param1,param2}` syntax."""
match = re.search(r"\{\?([^}]+)\}", uri_template)
... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/resources/template.py |
Annotate my code with docstrings |
import json
import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
from fastmcp.client.transports.base import ClientTransport
from fastmcp.mcp_config import (
MCPConfig,
MCPServerTypes,
RemoteMCPServer,
StdioMCPServer,
)
from fastmcp.utiliti... | --- +++ @@ -1,3 +1,11 @@+"""Discover MCP servers configured in editor config files.
+
+Scans filesystem-readable config files from editors like Claude Desktop,
+Claude Code, Cursor, Gemini CLI, and Goose, as well as project-level
+``mcp.json`` files. Each discovered server can be resolved by name
+(or ``source:name``) ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/discovery.py |
Add minimal docstrings for each function |
import re
import sys
from pathlib import Path
from typing import Annotated
from urllib.parse import quote
import cyclopts
from rich import print
from fastmcp.utilities.logging import get_logger
from .shared import open_deeplink, process_common_args
logger = get_logger(__name__)
def _slugify(name: str) -> str:
... | --- +++ @@ -1,3 +1,4 @@+"""Goose integration for FastMCP install using Cyclopts."""
import re
import sys
@@ -16,6 +17,11 @@
def _slugify(name: str) -> str:
+ """Convert a display name to a URL-safe identifier.
+
+ Lowercases, replaces non-alphanumeric runs with hyphens,
+ and strips leading/trailing hy... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/install/goose.py |
Add docstrings for utility scripts |
from __future__ import annotations as _annotations
import warnings
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, ClassVar, Literal, overload
import pydantic
import pydantic_core
if TYPE_CHECKING:
from docket import Docket
from docket.execution import Execution
from fastmcp... | --- +++ @@ -1,3 +1,4 @@+"""Base classes for FastMCP prompts."""
from __future__ import annotations as _annotations
@@ -40,6 +41,26 @@
class Message(pydantic.BaseModel):
+ """Wrapper for prompt message with auto-serialization.
+
+ Accepts any content - strings pass through, other types
+ (dict, list, B... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/prompts/base.py |
Write reusable docstrings |
from __future__ import annotations
import uuid
import weakref
from typing import TYPE_CHECKING, Any, Literal, cast, overload
import mcp.types
from pydantic import RootModel
if TYPE_CHECKING:
import datetime
from fastmcp.client.client import CallToolResult, Client
from fastmcp.client.progress import Progres... | --- +++ @@ -1,3 +1,4 @@+"""Tool-related methods for FastMCP Client."""
from __future__ import annotations
@@ -31,12 +32,26 @@
class ClientToolsMixin:
+ """Mixin providing tool-related methods for Client."""
# --- Tools ---
async def list_tools_mcp(
self: Client, *, cursor: str | None ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/mixins/tools.py |
Write docstrings that follow conventions |
from __future__ import annotations
from dataclasses import dataclass
import anyio
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.routing import Route
from uvicorn import Config, Server
from fastmcp.utilities.http import find_available_port
from fastmcp.utilities.l... | --- +++ @@ -1,3 +1,9 @@+"""
+OAuth callback server for handling authorization code flows.
+
+This module provides a reusable callback server that can handle OAuth redirects
+and display styled responses to users.
+"""
from __future__ import annotations
@@ -31,6 +37,7 @@ title: str = "FastMCP OAuth",
serve... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/oauth_callback.py |
Generate docstrings for exported functions |
import difflib
import json
import shlex
import sys
from pathlib import Path
from typing import Annotated, Any, Literal
import cyclopts
import mcp.types
from rich.console import Console
from rich.markup import escape as escape_rich_markup
from fastmcp.cli.discovery import DiscoveredServer, discover_servers, resolve_n... | --- +++ @@ -1,3 +1,4 @@+"""Client-side CLI commands for querying and invoking MCP servers."""
import difflib
import json
@@ -45,6 +46,20 @@ command: str | None = None,
transport: str | None = None,
) -> str | dict[str, Any] | ClientTransport:
+ """Turn CLI inputs into something ``Client()`` accepts.
+
... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/client.py |
Create docstrings for all classes and functions |
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, Field
UI_EXTENSION_ID = "io.modelcontextprotocol/ui"
UI_MIME_TYPE = "text/html;profile=mcp-app"
class ResourceCSP(BaseModel):
connect_domains: list[str] | None = Field(
default=None,
alias="conn... | --- +++ @@ -1,3 +1,9 @@+"""MCP Apps support — extension negotiation and typed UI metadata models.
+
+Provides constants and Pydantic models for the MCP Apps extension
+(io.modelcontextprotocol/ui), enabling tools and resources to carry
+UI metadata for clients that support interactive app rendering.
+"""
from __futu... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/apps.py |
Add detailed docstrings explaining each function |
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Annotated
import cyclopts
from rich import print
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironment
from .shared import process_common_args, validate_... | --- +++ @@ -1,3 +1,4 @@+"""Claude Code integration for FastMCP install using Cyclopts."""
import shutil
import subprocess
@@ -17,6 +18,11 @@
def find_claude_command() -> str | None:
+ """Find the Claude Code CLI command.
+
+ Checks common installation locations since 'claude' is often a shell alias
+ t... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/install/claude_code.py |
Document helper functions with docstrings |
from __future__ import annotations
import asyncio
import contextlib
import io
import json
import logging
import os
import re
import signal
import sys
import tarfile
import tempfile
import urllib.request
import webbrowser
from pathlib import Path
from typing import Any
from urllib.parse import quote
import httpcore
i... | --- +++ @@ -1,3 +1,26 @@+"""Dev server for previewing FastMCPApp UIs locally.
+
+Starts the user's MCP server on a configurable port, then starts a lightweight
+Starlette dev server that:
+
+ - Serves a Prefab-based tool picker at GET /
+ - Proxies /mcp to the user's server (avoids browser CORS restrictions)
+ - Ser... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/apps_dev.py |
Generate descriptive docstrings automatically |
import keyword
import re
import sys
import textwrap
from pathlib import Path
from typing import Annotated, Any
from urllib.parse import urlparse
import cyclopts
import mcp.types
import pydantic_core
from mcp import McpError
from rich.console import Console
from fastmcp.cli.client import _build_client, resolve_server... | --- +++ @@ -1,3 +1,4 @@+"""Generate a standalone CLI script and agent skill from an MCP server."""
import keyword
import re
@@ -29,6 +30,7 @@
def _is_simple_type(schema: dict[str, Any]) -> bool:
+ """Check if a schema represents a simple (non-complex) type."""
schema_type = schema.get("type")
if is... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/generate.py |
Write docstrings describing functionality |
from __future__ import annotations
import json
from pathlib import Path
import httpx
import pydantic.json
from anyio import Path as AsyncPath
from pydantic import Field, ValidationInfo
from typing_extensions import override
from fastmcp.exceptions import ResourceError
from fastmcp.resources.base import Resource, Re... | --- +++ @@ -1,3 +1,4 @@+"""Concrete resource implementations."""
from __future__ import annotations
@@ -18,10 +19,12 @@
class TextResource(Resource):
+ """A resource that reads from a string."""
text: str = Field(description="Text content of the resource")
async def read(self) -> ResourceResul... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/resources/types.py |
Write docstrings including parameters and return values | from typing import Any
from mcp.types import CallToolResult, TextContent
from pydantic import BaseModel, Field
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport
from fastmcp.contrib.mcp_mixin.mcp_mixin import (
_DEFAULT_SEPARATOR_TOOL,
MCPMixi... | --- +++ @@ -14,6 +14,7 @@
class CallToolRequest(BaseModel):
+ """A class to represent a request to call a tool with specific arguments."""
tool: str = Field(description="The name of the tool to call.")
arguments: dict[str, Any] = Field(
@@ -22,6 +23,10 @@
class CallToolRequestResult(CallToolResul... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/contrib/bulk_tool_caller/bulk_tool_caller.py |
Document this module using docstrings |
from __future__ import annotations
import json
from mcp.server.auth.middleware.bearer_auth import (
RequireAuthMiddleware as SDKRequireAuthMiddleware,
)
from starlette.types import Send
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
class RequireAuthMiddleware(SDKRequireAuthMi... | --- +++ @@ -1,3 +1,9 @@+"""Enhanced authentication middleware with better error messages.
+
+This module provides enhanced versions of MCP SDK authentication middleware
+that return more helpful error messages for developers troubleshooting
+authentication issues.
+"""
from __future__ import annotations
@@ -14,10 ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/middleware.py |
Add docstrings with type hints explained |
from __future__ import annotations
import contextlib
import datetime
import ssl
from collections.abc import AsyncIterator, Callable
from typing import Any, Literal, cast
import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from mcp.shared._httpx_utils import McpHtt... | --- +++ @@ -1,3 +1,4 @@+"""Streamable HTTP transport for FastMCP Client."""
from __future__ import annotations
@@ -23,6 +24,7 @@
class StreamableHttpTransport(ClientTransport):
+ """Transport implementation that connects to an MCP server via Streamable HTTP Requests."""
def __init__(
self,
@... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/transports/http.py |
Create documentation for each function signature |
from collections.abc import Sequence
from uuid import uuid4
try:
from google.genai import Client as GoogleGenaiClient
from google.genai.types import (
Candidate,
Content,
FunctionCall,
FunctionCallingConfig,
FunctionCallingConfigMode,
FunctionDeclaration,
... | --- +++ @@ -1,3 +1,4 @@+"""Google GenAI sampling handler with tool support for FastMCP 3.0."""
from collections.abc import Sequence
from uuid import uuid4
@@ -51,6 +52,24 @@
class GoogleGenaiSamplingHandler:
+ """Sampling handler that uses the Google GenAI API with tool support.
+
+ Example:
+ ```p... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/sampling/handlers/google_genai.py |
Add docstrings to improve code quality |
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import secrets
import time
from base64 import urlsafe_b64encode
from typing import TYPE_CHECKING, Any
from urllib.parse import urlencode, urlparse
from pydantic import AnyUrl
from starlette.requests import Request
from starlette.... | --- +++ @@ -1,3 +1,9 @@+"""OAuth Proxy Consent Management.
+
+This module contains consent management functionality for the OAuth proxy.
+The ConsentMixin class provides methods for handling user consent flows,
+cookie management, and consent page rendering.
+"""
from __future__ import annotations
@@ -27,8 +33,17 ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/oauth_proxy/consent.py |
Add minimal docstrings for each function |
from __future__ import annotations
from fastmcp.utilities.ui import (
BUTTON_STYLES,
DETAIL_BOX_STYLES,
DETAILS_STYLES,
INFO_BOX_STYLES,
REDIRECT_SECTION_STYLES,
TOOLTIP_STYLES,
create_logo,
create_page,
)
def create_consent_html(
client_id: str,
redirect_uri: str,
scopes... | --- +++ @@ -1,3 +1,7 @@+"""OAuth Proxy UI Generation Functions.
+
+This module contains HTML generation functions for consent and error pages.
+"""
from __future__ import annotations
@@ -29,6 +33,14 @@ is_cimd_client: bool = False,
cimd_domain: str | None = None,
) -> str:
+ """Create a styled HTML co... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/oauth_proxy/ui.py |
Write Python docstrings for this snippet |
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Annotated
import cyclopts
from rich import print
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironment
from .shared import process_common_args, validate_... | --- +++ @@ -1,3 +1,4 @@+"""Gemini CLI integration for FastMCP install using Cyclopts."""
import shutil
import subprocess
@@ -17,6 +18,7 @@
def find_gemini_command() -> str | None:
+ """Find the Gemini CLI command."""
# First try shutil.which() in case it's a real executable in PATH
gemini_in_path =... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/install/gemini_cli.py |
Help me document legacy Python code |
from __future__ import annotations
import inspect
import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, cast
from fastmcp.exceptions import AuthorizationError
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from fastmcp.server.... | --- +++ @@ -1,3 +1,30 @@+"""Authorization checks for FastMCP components.
+
+This module provides callable-based authorization for tools, resources, and prompts.
+Auth checks are functions that receive an AuthContext and return True to allow access
+or False to deny.
+
+Auth checks can also raise exceptions:
+- Authoriz... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/authorization.py |
Help me write clear docstrings |
from __future__ import annotations
import asyncio
import json
import sys
from pathlib import Path
from typing import Annotated
import cyclopts
from rich.console import Console
from fastmcp.server.auth.cimd import (
CIMDFetcher,
CIMDFetchError,
CIMDValidationError,
)
from fastmcp.utilities.logging import... | --- +++ @@ -1,3 +1,4 @@+"""CIMD (Client ID Metadata Document) CLI commands."""
from __future__ import annotations
@@ -83,6 +84,17 @@ ),
] = True,
) -> None:
+ """Generate a CIMD document for hosting.
+
+ Create a Client ID Metadata Document that you can host at an HTTPS URL.
+ The URL where ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/cimd.py |
Add docstrings to improve collaboration |
from __future__ import annotations
import functools
import inspect
import json
import warnings
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Literal,
Protocol,
TypeVar,
overload,
runtime_checkable,
)
import pydantic_... | --- +++ @@ -1,3 +1,4 @@+"""Standalone @prompt decorator for FastMCP."""
from __future__ import annotations
@@ -50,6 +51,7 @@
@runtime_checkable
class DecoratedPrompt(Protocol):
+ """Protocol for functions decorated with @prompt."""
__fastmcp__: PromptMeta
@@ -58,6 +60,7 @@
@dataclass(frozen=True, ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/prompts/function_prompt.py |
Add docstrings for internal functions | from __future__ import annotations
import asyncio
import copy
import datetime
import secrets
import ssl
import weakref
from collections.abc import Coroutine
from contextlib import AsyncExitStack, asynccontextmanager, suppress
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Gen... | --- +++ @@ -95,6 +95,11 @@
@dataclass
class ClientSessionState:
+ """Holds all session-related state for a Client instance.
+
+ This allows clean separation of configuration (which is copied) from
+ session state (which should be fresh for each new client instance).
+ """
session: ClientSession | ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/client.py |
Add docstrings to clarify complex logic |
import builtins
import shlex
import sys
from pathlib import Path
from typing import Annotated
import cyclopts
import pyperclip
from rich import print as rich_print
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.environments.uv import UVEnvironment
from .shared import pr... | --- +++ @@ -1,3 +1,4 @@+"""Stdio command generation for FastMCP install using Cyclopts."""
import builtins
import shlex
@@ -28,6 +29,21 @@ with_requirements: Path | None = None,
project: Path | None = None,
) -> bool:
+ """Generate the stdio command for running a FastMCP server.
+
+ Args:
+ f... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/install/stdio.py |
Expand my code with proper documentation strings | import contextlib
from collections.abc import AsyncIterator
import anyio
from mcp import ClientSession
from mcp.server.fastmcp import FastMCP as FastMCP1Server
from mcp.shared.memory import create_client_server_memory_streams
from typing_extensions import Unpack
from fastmcp.client.transports.base import ClientTransp... | --- +++ @@ -12,8 +12,16 @@
class FastMCPTransport(ClientTransport):
+ """In-memory transport for FastMCP servers.
+
+ This transport connects directly to a FastMCP server instance in the same
+ Python process. It works with both FastMCP 2.x servers and FastMCP 1.0
+ servers from the low-level MCP SDK. T... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/transports/memory.py |
Add detailed documentation for each class |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import mcp.types
from mcp import McpError
if TYPE_CHECKING:
from fastmcp.client.client import Client
from mcp.types import (
CancelTaskRequest,
CancelTaskRequestParams,
GetTaskPayloadRequest,
GetTaskPayloadRequestParams,
... | --- +++ @@ -1,3 +1,4 @@+"""Task management methods for FastMCP Client."""
from __future__ import annotations
@@ -27,8 +28,23 @@
class ClientTaskManagementMixin:
+ """Mixin providing task management methods for Client."""
async def get_task_status(self: Client, task_id: str) -> GetTaskResult:
+ ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/mixins/task_management.py |
Add docstrings for internal functions | from __future__ import annotations
import time
import webbrowser
from collections.abc import AsyncGenerator
from contextlib import aclosing
from typing import Any
import anyio
import httpx
from key_value.aio.adapters.pydantic import PydanticAdapter
from key_value.aio.protocols import AsyncKeyValue
from key_value.aio.... | --- +++ @@ -35,11 +35,18 @@
class ClientNotFoundError(Exception):
+ """Raised when OAuth client credentials are not found on the server."""
async def check_if_auth_required(
mcp_url: str, httpx_kwargs: dict[str, Any] | None = None
) -> bool:
+ """
+ Check if the MCP endpoint requires authenticat... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/auth/oauth.py |
Write docstrings describing functionality |
from __future__ import annotations
import contextlib
import datetime
import ssl
from collections.abc import AsyncIterator
from typing import Any, Literal, cast
import httpx
from mcp import ClientSession
from mcp.client.sse import sse_client
from mcp.shared._httpx_utils import McpHttpClientFactory
from pydantic impor... | --- +++ @@ -1,3 +1,4 @@+"""Server-Sent Events (SSE) transport for FastMCP Client."""
from __future__ import annotations
@@ -22,6 +23,7 @@
class SSETransport(ClientTransport):
+ """Transport implementation that connects to an MCP server via Server-Sent Events."""
def __init__(
self,
@@ -147,4... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/client/transports/sse.py |
Write docstrings including parameters and return values |
import importlib.metadata
import importlib.util
import json
import os
import platform
import subprocess
import sys
from contextlib import contextmanager
from pathlib import Path
from typing import Annotated, Literal
import cyclopts
import pyperclip
from cyclopts import Parameter
from rich.console import Console
from ... | --- +++ @@ -1,3 +1,4 @@+"""FastMCP CLI tools using Cyclopts."""
import importlib.metadata
import importlib.util
@@ -46,6 +47,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
... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/cli.py |
Create Google-style docstrings for my code |
from __future__ import annotations
import base64
from collections.abc import Callable
from typing import TYPE_CHECKING, Annotated, Any, ClassVar, overload
import mcp.types
if TYPE_CHECKING:
from docket import Docket
from docket.execution import Execution
from fastmcp.resources.function_resource import ... | --- +++ @@ -1,3 +1,4 @@+"""Base classes and interfaces for FastMCP resources."""
from __future__ import annotations
@@ -34,6 +35,26 @@
class ResourceContent(pydantic.BaseModel):
+ """Wrapper for resource content with optional MIME type and metadata.
+
+ Accepts any value for content - strings and bytes p... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/resources/base.py |
Add professional docstrings to my codebase |
from collections.abc import Sequence
from typing import Literal
import httpx
from key_value.aio.protocols import AsyncKeyValue
from pydantic import AnyHttpUrl, BaseModel, model_validator
from typing_extensions import Self
from fastmcp.server.auth import TokenVerifier
from fastmcp.server.auth.oauth_proxy import OAuth... | --- +++ @@ -1,3 +1,13 @@+"""OIDC Proxy Provider for FastMCP.
+
+This provider acts as a transparent proxy to an upstream OIDC compliant Authorization
+Server. It leverages the OAuthProxy class to handle Dynamic Client Registration and
+forwarding of all OAuth flows.
+
+This implementation is based on:
+ OpenID Conne... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/auth/oidc_proxy.py |
Add standardized docstrings across the file |
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from urllib.parse import urlparse
from dotenv import dotenv_values
from pydantic import ValidationError
from rich import print
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config import MCPServ... | --- +++ @@ -1,3 +1,4 @@+"""Shared utilities for install commands."""
import json
import os
@@ -25,6 +26,10 @@
def validate_server_name(name: str) -> str:
+ """Validate that a server name is safe for use as a subprocess argument.
+
+ Raises SystemExit if the name contains shell metacharacters.
+ """
... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/cli/install/shared.py |
Write beginner-friendly docstrings | #!/usr/bin/env python
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "httpx",
# ]
# ///
import os
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import httpx
@dataclass
class Issue:
number: int
title: str
state: str
created_at: str
user_... | --- +++ @@ -5,6 +5,12 @@ # "httpx",
# ]
# ///
+"""
+Auto-close duplicate GitHub issues.
+
+This script runs on a schedule to automatically close issues that have been
+marked as duplicates and haven't received any preventing activity.
+"""
import os
from dataclasses import dataclass
@@ -15,6 +21,7 @@
@datac... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/scripts/auto_close_duplicates.py |
Add well-formatted docstrings |
import inspect
import warnings
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
import fastmcp
from fastmcp.prompts.base import Prompt
from fastmcp.resources.base import Resource
from fastmcp.tools.base import Tool
from fastmcp.utilities.types import get_fn_name
if TYPE_CHECKING:
from f... | --- +++ @@ -1,3 +1,4 @@+"""Provides a base mixin class and decorators for easy registration of class methods with FastMCP."""
import inspect
import warnings
@@ -47,6 +48,23 @@ enabled: bool | None = None,
**kwargs: Any,
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
+ """Decorator to mark a m... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.