Skip to content

Commit

Permalink
Merge pull request #40 from jlowin/baseurl
Browse files Browse the repository at this point in the history
Remove BaseURL reference and use AnyURL
  • Loading branch information
jlowin authored Dec 2, 2024
2 parents 16ee0e5 + 73b06f8 commit 0f2b5a3
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions src/fastmcp/resources/base.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,26 @@
"""Base classes and interfaces for FastMCP resources."""

import abc
from typing import Annotated, Union
from typing import Union

from pydantic import (
AnyUrl,
BaseModel,
BeforeValidator,
ConfigDict,
Field,
FileUrl,
ValidationInfo,
field_validator,
)
from pydantic.networks import _BaseUrl # TODO: remove this once pydantic is updated


def maybe_cast_str_to_any_url(x) -> AnyUrl:
if isinstance(x, FileUrl):
return x
elif isinstance(x, AnyUrl):
return x
elif isinstance(x, str):
if x.startswith("file://"):
return FileUrl(x)
return AnyUrl(x)
raise ValueError(f"Expected str or AnyUrl, got {type(x)}")


LaxAnyUrl = Annotated[_BaseUrl | str, BeforeValidator(maybe_cast_str_to_any_url)]


class Resource(BaseModel, abc.ABC):
"""Base class for all resources."""

model_config = ConfigDict(validate_default=True)

uri: LaxAnyUrl = Field(default=..., description="URI of the resource")
# uri: Annotated[AnyUrl, BeforeValidator(maybe_cast_str_to_any_url)] = Field(
uri: AnyUrl = Field(default=..., description="URI of the resource")
name: str | None = Field(description="Name of the resource", default=None)
description: str | None = Field(
description="Description of the resource", default=None
Expand All @@ -47,6 +31,15 @@ class Resource(BaseModel, abc.ABC):
pattern=r"^[a-zA-Z0-9]+/[a-zA-Z0-9\-+.]+$",
)

@field_validator("uri", mode="before")
def validate_uri(cls, uri: AnyUrl | str) -> AnyUrl:
if isinstance(uri, str):
# AnyUrl doesn't support triple-slashes, but files do ("file:///absolute/path")
if uri.startswith("file://"):
return FileUrl(uri)
return AnyUrl(uri)
return uri

@field_validator("name", mode="before")
@classmethod
def set_default_name(cls, name: str | None, info: ValidationInfo) -> str:
Expand Down

0 comments on commit 0f2b5a3

Please sign in to comment.