mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-18 23:21:45 +08:00
refactor mcp server for v5
This commit is contained in:
4
.github/workflows/lint-openbb-platform.yml
vendored
4
.github/workflows/lint-openbb-platform.yml
vendored
@@ -59,6 +59,10 @@ jobs:
|
||||
pip install ./openbb_platform/extensions/devtools
|
||||
- name: Install openbb-core (so ty can resolve runtime deps)
|
||||
run: pip install -e "./openbb_platform/core[pandas]" numpy
|
||||
- name: Install openbb-platform-api (so ty can resolve deepdiff/aiohttp)
|
||||
run: pip install -e ./openbb_platform/extensions/platform_api
|
||||
- name: Install openbb-mcp-server (so ty can resolve fastmcp)
|
||||
run: pip install -e ./openbb_platform/extensions/mcp_server
|
||||
- run: codespell --ignore-words=.codespell.ignore --skip="$(tr '\n' ',' < .codespell.skip | sed 's/,$//')" --quiet-level=2
|
||||
- run: |
|
||||
# Run linters for openbb_platform
|
||||
|
||||
12
README.md
vendored
12
README.md
vendored
@@ -3,17 +3,7 @@
|
||||
<img src="https://github.com/OpenBB-finance/OpenBB/blob/develop/images/odp-dark.svg?raw=true#gh-dark-mode-only" alt="Open Data Platform by OpenBB logo" width="600">
|
||||
<br />
|
||||
<br />
|
||||
|
||||
[](https://x.com/openbb_finance)
|
||||
[](https://discord.com/invite/xPHTuHCmuV)
|
||||
[](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/OpenBB-finance/OpenBB)
|
||||
<a href="https://codespaces.new/OpenBB-finance/OpenBB">
|
||||
<img src="https://github.com/codespaces/badge.svg" height="20" />
|
||||
</a>
|
||||
<a target="_blank" href="https://colab.research.google.com/github/OpenBB-finance/OpenBB/blob/develop/examples/googleColab.ipynb">
|
||||
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
|
||||
</a>
|
||||
[](https://pypi.org/project/openbb/)
|
||||
[](https://pypi.org/project/openbb-cli/)
|
||||
|
||||
Open Data Platform by OpenBB (ODP) is the open-source toolset that helps data engineers integrate proprietary, licensed, and public data sources into downstream applications like AI copilots and research dashboards.
|
||||
|
||||
|
||||
@@ -9,67 +9,92 @@ from openbb_core.app.model.example import APIEx, PythonEx
|
||||
from openbb_core.app.model.obbject import OBBject
|
||||
from openbb_core.app.router import Router
|
||||
from openbb_core.provider.abstract.data import Data
|
||||
from pydantic import BaseModel, PositiveInt, model_serializer
|
||||
from pydantic import BaseModel, Field, PositiveInt
|
||||
|
||||
router = Router(prefix="", description="Econometrics analysis tools.")
|
||||
|
||||
|
||||
class OLSRegressionResults(BaseModel):
|
||||
"""OLS Regression Results that serializes statsmodels objects."""
|
||||
"""OLS regression results extracted from a statsmodels fit.
|
||||
|
||||
model: Any
|
||||
results: Any
|
||||
Field shapes mirror the keys produced by the previous custom serializer
|
||||
so OpenAPI consumers (the platform CLI's ``--describe``, generated SDKs,
|
||||
docs) see the actual response surface instead of an opaque
|
||||
``additionalProperties: true`` stub.
|
||||
"""
|
||||
|
||||
class Config:
|
||||
"""Pydantic config."""
|
||||
params: dict[str, float] = Field(
|
||||
description="Estimated coefficient for each regressor (including the constant)."
|
||||
)
|
||||
rsquared: float = Field(description="Coefficient of determination R-squared.")
|
||||
rsquared_adj: float = Field(description="Adjusted R-squared.")
|
||||
fvalue: float | None = Field(
|
||||
default=None, description="F-statistic for the joint significance test."
|
||||
)
|
||||
f_pvalue: float | None = Field(
|
||||
default=None, description="P-value associated with the F-statistic."
|
||||
)
|
||||
aic: float = Field(description="Akaike information criterion.")
|
||||
bic: float = Field(description="Bayesian information criterion.")
|
||||
llf: float = Field(description="Log-likelihood of the fitted model.")
|
||||
nobs: int = Field(description="Number of observations used in the fit.")
|
||||
df_model: float = Field(description="Model degrees of freedom.")
|
||||
df_resid: float = Field(description="Residual degrees of freedom.")
|
||||
pvalues: dict[str, float] = Field(
|
||||
description="Two-tailed p-value for each coefficient."
|
||||
)
|
||||
tvalues: dict[str, float] = Field(description="T-statistic for each coefficient.")
|
||||
bse: dict[str, float] = Field(
|
||||
description="Standard error for each coefficient estimate."
|
||||
)
|
||||
conf_int: dict[str, dict[str, float]] = Field(
|
||||
description="Confidence interval bounds keyed by coefficient name."
|
||||
)
|
||||
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
@model_serializer
|
||||
def serialize_model(self) -> dict:
|
||||
"""Serialize statsmodels objects to a dictionary."""
|
||||
results = self.results
|
||||
@classmethod
|
||||
def from_statsmodels(cls, results: Any) -> "OLSRegressionResults":
|
||||
"""Build the response model from a fitted statsmodels regression result."""
|
||||
conf_int = results.conf_int()
|
||||
conf_int_dict = (
|
||||
conf_int.to_dict()
|
||||
if hasattr(conf_int, "to_dict")
|
||||
else conf_int.to_dict("index")
|
||||
)
|
||||
return {
|
||||
"params": (
|
||||
return cls(
|
||||
params=(
|
||||
results.params.to_dict()
|
||||
if hasattr(results.params, "to_dict")
|
||||
else dict(results.params)
|
||||
),
|
||||
"rsquared": float(results.rsquared),
|
||||
"rsquared_adj": float(results.rsquared_adj),
|
||||
"fvalue": float(results.fvalue) if results.fvalue is not None else None,
|
||||
"f_pvalue": (
|
||||
rsquared=float(results.rsquared),
|
||||
rsquared_adj=float(results.rsquared_adj),
|
||||
fvalue=float(results.fvalue) if results.fvalue is not None else None,
|
||||
f_pvalue=(
|
||||
float(results.f_pvalue) if results.f_pvalue is not None else None
|
||||
),
|
||||
"aic": float(results.aic),
|
||||
"bic": float(results.bic),
|
||||
"llf": float(results.llf),
|
||||
"nobs": int(results.nobs),
|
||||
"df_model": float(results.df_model),
|
||||
"df_resid": float(results.df_resid),
|
||||
"pvalues": (
|
||||
aic=float(results.aic),
|
||||
bic=float(results.bic),
|
||||
llf=float(results.llf),
|
||||
nobs=int(results.nobs),
|
||||
df_model=float(results.df_model),
|
||||
df_resid=float(results.df_resid),
|
||||
pvalues=(
|
||||
results.pvalues.to_dict()
|
||||
if hasattr(results.pvalues, "to_dict")
|
||||
else dict(results.pvalues)
|
||||
),
|
||||
"tvalues": (
|
||||
tvalues=(
|
||||
results.tvalues.to_dict()
|
||||
if hasattr(results.tvalues, "to_dict")
|
||||
else dict(results.tvalues)
|
||||
),
|
||||
"bse": (
|
||||
bse=(
|
||||
results.bse.to_dict()
|
||||
if hasattr(results.bse, "to_dict")
|
||||
else dict(results.bse)
|
||||
),
|
||||
"conf_int": conf_int_dict,
|
||||
}
|
||||
conf_int=conf_int_dict,
|
||||
)
|
||||
|
||||
|
||||
@router.command(
|
||||
@@ -192,7 +217,7 @@ def ols_regression(
|
||||
y = get_target_column(basemodel_to_df(data), y_column)
|
||||
model = sm.OLS(y, X)
|
||||
results = model.fit()
|
||||
return OBBject(results=OLSRegressionResults(model=model, results=results))
|
||||
return OBBject(results=OLSRegressionResults.from_statsmodels(results))
|
||||
|
||||
|
||||
@router.command(
|
||||
|
||||
@@ -1 +1,38 @@
|
||||
"""OpenBB MCP Server App Module."""
|
||||
"""MCP server boot subpackage.
|
||||
|
||||
* ``args`` — command-line argument parsing for the ``openbb-mcp``
|
||||
launcher.
|
||||
* ``bootstrap`` — pluggable FastAPI app loading (``import_app``).
|
||||
* ``cli_tools`` — registers ``openbb-cli`` dispatcher tools when the
|
||||
optional ``[cli]`` extra is installed.
|
||||
* ``config`` — layered TOML cascade + ``[env]`` injection bootstrap.
|
||||
* ``middleware`` — auth + HTTP middleware hook resolver.
|
||||
* ``spec`` — synthesize a FastAPI proxy app from an ``openbb-cli``
|
||||
generated ``.spec`` file.
|
||||
* ``app`` — the launcher entry point. Holds ``create_mcp_server`` and
|
||||
``launch_mcp``.
|
||||
|
||||
Submodules are imported here (rather than via the dotted ``from
|
||||
openbb_mcp_server.app.X import …`` form) so they're explicitly bound
|
||||
as attributes on this package — ``mock.patch`` resolution stays
|
||||
reliable across CPython 3.10's namespace-package quirk and any test
|
||||
ordering that re-imports cached parents.
|
||||
"""
|
||||
|
||||
from openbb_mcp_server.app import (
|
||||
args,
|
||||
bootstrap,
|
||||
cli_tools,
|
||||
config,
|
||||
middleware,
|
||||
spec,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"args",
|
||||
"bootstrap",
|
||||
"cli_tools",
|
||||
"config",
|
||||
"middleware",
|
||||
"spec",
|
||||
]
|
||||
|
||||
@@ -45,6 +45,8 @@ from starlette.middleware import Middleware
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
from openbb_mcp_server.app.args import parse_args
|
||||
from openbb_mcp_server.app.cli_tools import register_cli_tools
|
||||
from openbb_mcp_server.models.category_index import CategoryIndex
|
||||
from openbb_mcp_server.models.mcp_config import (
|
||||
ArgumentDefinitionModel,
|
||||
@@ -54,7 +56,6 @@ from openbb_mcp_server.models.prompts import StaticPrompt
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
from openbb_mcp_server.models.tools import CategoryInfo, SubcategoryInfo, ToolInfo
|
||||
from openbb_mcp_server.service.mcp_service import MCPService
|
||||
from openbb_mcp_server.utils.app_import import parse_args
|
||||
from openbb_mcp_server.utils.fastapi import (
|
||||
get_api_prefix,
|
||||
process_fastapi_routes_for_mcp,
|
||||
@@ -729,8 +730,7 @@ def create_mcp_server(
|
||||
await ctx.enable_components(names=names)
|
||||
scope = f"'{category}'" + (f"/'{subcategory}'" if subcategory else "")
|
||||
return (
|
||||
f"Activated {len(names)} tools in {scope}"
|
||||
f": {', '.join(sorted(names))}"
|
||||
f"Activated {len(names)} tools in {scope}: {', '.join(sorted(names))}"
|
||||
)
|
||||
|
||||
# Expose prompts and resources as tools via transforms so that
|
||||
@@ -738,6 +738,11 @@ def create_mcp_server(
|
||||
mcp.add_transform(PromptsAsTools(mcp))
|
||||
mcp.add_transform(ResourcesAsTools(mcp))
|
||||
|
||||
# Register first-class openbb-cli dispatcher tools when the
|
||||
# optional ``[cli]`` extra is installed. No-op otherwise.
|
||||
if settings.enable_cli_tools:
|
||||
register_cli_tools(mcp)
|
||||
|
||||
@mcp.tool(tags={"resource", "admin"})
|
||||
async def install_skill(
|
||||
skill_name: Annotated[
|
||||
@@ -834,12 +839,14 @@ def create_mcp_server(
|
||||
file_path.write_text(content, encoding="utf-8")
|
||||
written_files.append(filename)
|
||||
|
||||
# Register the new skill with the provider
|
||||
# Register the new skill with the provider. ``getattr`` (not the
|
||||
# ``hasattr`` + private-attr access) keeps ty happy — the
|
||||
# generic ``providers`` iterable is typed ``object``, so direct
|
||||
# ``p._skill_path.name`` reads as an unresolved-attribute error.
|
||||
already_loaded = {
|
||||
p._skill_path.name # noqa: SLF001
|
||||
for p in target_provider.providers
|
||||
if hasattr(p, "_skill_path")
|
||||
}
|
||||
getattr(getattr(p, "_skill_path", None), "name", None)
|
||||
for p in target_provider.providers # noqa: SLF001
|
||||
} - {None}
|
||||
|
||||
if skill_name not in already_loaded:
|
||||
new_skill_provider = SkillProvider(skill_path=skill_dir)
|
||||
@@ -949,60 +956,61 @@ async def stdio_main(mcp_server):
|
||||
await loop.run_in_executor(None, mcp_server.run, "stdio")
|
||||
|
||||
|
||||
def main():
|
||||
"""Start the OpenBB MCP server with enhanced FastAPI app import capabilities."""
|
||||
args = parse_args()
|
||||
def launch_mcp() -> None:
|
||||
"""Launch the OpenBB MCP server.
|
||||
|
||||
Reads parsed CLI args (already overlaid with the layered TOML
|
||||
cascade in ``parse_args``), loads ``MCPSettings`` with the merged
|
||||
overrides, and runs the FastMCP server with the requested
|
||||
transport.
|
||||
|
||||
Called by ``openbb_mcp_server.main:main`` after the lightweight
|
||||
``bootstrap_launcher_config`` phase has applied any ``[env]``
|
||||
table.
|
||||
"""
|
||||
parsed = parse_args()
|
||||
target_app = parsed["app"] if parsed["app"] is not None else app
|
||||
transport = parsed["transport"]
|
||||
|
||||
mcp_service = MCPService()
|
||||
# Collect all command-line overrides from parsed args
|
||||
cli_overrides = args.uvicorn_config.copy()
|
||||
# Add MCP-specific CLI arguments if they exist
|
||||
if hasattr(args, "allowed_categories") and args.allowed_categories:
|
||||
cli_overrides["allowed_categories"] = args.allowed_categories
|
||||
cli_overrides: dict = dict(parsed["uvicorn_overrides"])
|
||||
cli_overrides.update(parsed["mcp_overrides"])
|
||||
|
||||
if hasattr(args, "default_categories") and args.default_categories:
|
||||
cli_overrides["default_categories"] = args.default_categories
|
||||
|
||||
if hasattr(args, "tool_discovery") and args.tool_discovery:
|
||||
cli_overrides["tool_discovery"] = args.tool_discovery
|
||||
|
||||
if hasattr(args, "system_prompt") and args.system_prompt:
|
||||
cli_overrides["system_prompt"] = args.system_prompt
|
||||
|
||||
if hasattr(args, "server_prompts") and args.server_prompts:
|
||||
cli_overrides["server_prompts"] = args.server_prompts
|
||||
|
||||
# Load settings with proper priority order (CLI > env > config file > defaults)
|
||||
settings = mcp_service.load_with_overrides(**cli_overrides)
|
||||
|
||||
try:
|
||||
# Use imported app if provided, otherwise default OpenBB app
|
||||
target_app = args.imported_app if args.imported_app else app
|
||||
|
||||
# Extract runtime configuration from settings
|
||||
http_run_kwargs = settings.get_http_run_kwargs()
|
||||
httpx_kwargs = settings.get_httpx_kwargs()
|
||||
|
||||
# Create MCP server with comprehensive configuration
|
||||
mcp_server = create_mcp_server(
|
||||
settings, target_app, httpx_kwargs, auth=settings.server_auth
|
||||
)
|
||||
|
||||
if args.transport == "stdio":
|
||||
if transport == "stdio":
|
||||
asyncio.run(stdio_main(mcp_server))
|
||||
else:
|
||||
cors_middleware = _build_runtime_middleware()
|
||||
|
||||
# Start building arguments mcp.run
|
||||
run_kwargs = {
|
||||
"transport": args.transport,
|
||||
"middleware": cors_middleware,
|
||||
# Auth + middleware hooks from the layered TOML cascade,
|
||||
# spliced between CORS (outermost) and the SSE shutdown
|
||||
# wrapper (innermost). Within the hook list, auth runs
|
||||
# before general middleware.
|
||||
from openbb_mcp_server.app.config import get_bootstrapped_config
|
||||
from openbb_mcp_server.app.middleware import build_hook_middleware
|
||||
|
||||
mcp_table = get_bootstrapped_config().get("mcp") or {}
|
||||
hook_middleware = build_hook_middleware(
|
||||
auth_hooks=(mcp_table.get("auth") or {}).get("hooks"),
|
||||
middleware_hooks=(mcp_table.get("middleware") or {}).get("hooks"),
|
||||
)
|
||||
|
||||
run_kwargs: dict = {
|
||||
"transport": transport,
|
||||
}
|
||||
|
||||
# Extract uvicorn settings
|
||||
if http_run_kwargs.get("uvicorn_config"):
|
||||
uvicorn_config = http_run_kwargs["uvicorn_config"].copy()
|
||||
|
||||
# Pop host and port to pass them as top-level args
|
||||
if "host" in uvicorn_config:
|
||||
run_kwargs["host"] = uvicorn_config.pop("host")
|
||||
|
||||
@@ -1010,13 +1018,12 @@ def main():
|
||||
port = uvicorn_config.pop("port")
|
||||
run_kwargs["port"] = int(port) if isinstance(port, str) else port
|
||||
|
||||
# Pass the rest of the config in the nested dict.
|
||||
if uvicorn_config:
|
||||
run_kwargs["uvicorn_config"] = uvicorn_config
|
||||
|
||||
# Add SSE shutdown handling to middleware stack
|
||||
cors_middleware.append(Middleware(SSEShutdownWrapper))
|
||||
run_kwargs["middleware"] = cors_middleware
|
||||
run_kwargs["middleware"] = (
|
||||
cors_middleware + hook_middleware + [Middleware(SSEShutdownWrapper)]
|
||||
)
|
||||
|
||||
mcp_server.run(**run_kwargs)
|
||||
|
||||
@@ -1028,5 +1035,16 @@ def main():
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Back-compat alias — the old ``[tool.poetry.scripts]`` entry pointed
|
||||
# at ``openbb_mcp_server.app.app:main``. The Hatchling pyproject now
|
||||
# uses ``openbb_mcp_server.main:main``, but external scripts that
|
||||
# directly imported ``main`` from here keep working.
|
||||
def main() -> None:
|
||||
"""Back-compat shim — delegates to ``openbb_mcp_server.main:main``."""
|
||||
from openbb_mcp_server.main import main as _main
|
||||
|
||||
_main()
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover — script entry
|
||||
main()
|
||||
|
||||
@@ -6,7 +6,11 @@ import secrets
|
||||
|
||||
from fastapi import HTTPException
|
||||
from fastmcp.server.auth import AuthProvider
|
||||
from mcp.server.auth.provider import AccessToken
|
||||
|
||||
# Use fastmcp's ``AccessToken`` (which subclasses ``mcp.server.auth.provider.AccessToken``
|
||||
# with extra JWT-claim fields) so our ``verify_token`` override matches
|
||||
# ``AuthProvider.verify_token``'s signature exactly — Liskov-safe.
|
||||
from fastmcp.server.auth.auth import AccessToken
|
||||
from starlette.requests import Request
|
||||
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
|
||||
@@ -1 +1,20 @@
|
||||
"""OpenBB MCP Server Models."""
|
||||
"""Pydantic models + indexes for ``openbb-mcp``.
|
||||
|
||||
Submodules bound explicitly for ``mock.patch`` reliability.
|
||||
"""
|
||||
|
||||
from openbb_mcp_server.models import (
|
||||
category_index,
|
||||
mcp_config,
|
||||
prompts,
|
||||
settings,
|
||||
tools,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"category_index",
|
||||
"mcp_config",
|
||||
"prompts",
|
||||
"settings",
|
||||
"tools",
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import Any
|
||||
|
||||
from fastmcp.exceptions import PromptError
|
||||
from fastmcp.prompts import Prompt
|
||||
from mcp.types import PromptMessage, TextContent
|
||||
from fastmcp.prompts.base import Message
|
||||
|
||||
|
||||
class StaticPrompt(Prompt):
|
||||
@@ -16,8 +16,16 @@ class StaticPrompt(Prompt):
|
||||
async def render(
|
||||
self,
|
||||
arguments: dict[str, Any] | None = None,
|
||||
) -> list[PromptMessage]:
|
||||
"""Render the prompt with arguments."""
|
||||
) -> list[Message | str]:
|
||||
"""Render the prompt with arguments.
|
||||
|
||||
Return type matches an element of ``Prompt.render``'s union
|
||||
(``str | list[Message | str] | PromptResult``) exactly —
|
||||
``list`` is invariant in Python's type system, so a tighter
|
||||
``list[Message]`` annotation would still trip the parent's
|
||||
Liskov check even though every value we produce is a
|
||||
``Message``.
|
||||
"""
|
||||
# Start with stored defaults, then overlay caller-supplied values
|
||||
args = {**self.argument_defaults, **(arguments or {})}
|
||||
|
||||
@@ -33,10 +41,6 @@ class StaticPrompt(Prompt):
|
||||
rendered_content = (
|
||||
self.content.format(**args) if self.arguments or args else self.content
|
||||
)
|
||||
return [
|
||||
PromptMessage(
|
||||
role="user", content=TextContent(type="text", text=rendered_content)
|
||||
)
|
||||
]
|
||||
return [Message(rendered_content, role="user")]
|
||||
except KeyError as e:
|
||||
raise PromptError(f"Missing argument for formatting: {e}") from e
|
||||
|
||||
@@ -182,6 +182,18 @@ the exact same operations available to REST clients.""",
|
||||
description="If True, show deprecation warnings in the console.",
|
||||
)
|
||||
|
||||
enable_cli_tools: bool = Field(
|
||||
default=True,
|
||||
description=(
|
||||
"If True (default) and ``openbb-cli`` is installed, register"
|
||||
" first-class MCP tools (``openbb_dispatch``, ``openbb_batch_dispatch``,"
|
||||
" ``openbb_describe_command``) that wrap the CLI's"
|
||||
" LocalDispatcher / HttpDispatcher protocol. Set to False to"
|
||||
" suppress registration even when openbb-cli is available."
|
||||
),
|
||||
alias="OPENBB_MCP_ENABLE_CLI_TOOLS",
|
||||
)
|
||||
|
||||
# ===== HTTP Transport Configuration =====
|
||||
|
||||
# Uvicorn server configuration
|
||||
|
||||
@@ -1 +1,8 @@
|
||||
"""MCP Service Module."""
|
||||
"""MCP service layer.
|
||||
|
||||
Submodule bound explicitly for ``mock.patch`` reliability.
|
||||
"""
|
||||
|
||||
from openbb_mcp_server.service import mcp_service
|
||||
|
||||
__all__ = ["mcp_service"]
|
||||
|
||||
@@ -1 +1,12 @@
|
||||
"""Utility functions for MCP server."""
|
||||
"""Utility helpers for ``openbb-mcp``.
|
||||
|
||||
Submodules bound explicitly so ``mock.patch`` finds them as
|
||||
attributes on this package (CPython 3.10 namespace-package quirk).
|
||||
"""
|
||||
|
||||
from openbb_mcp_server.utils import app_import, fastapi
|
||||
|
||||
__all__ = [
|
||||
"app_import",
|
||||
"fastapi",
|
||||
]
|
||||
|
||||
@@ -1,255 +1,43 @@
|
||||
"""App import utilities for MCP Server."""
|
||||
"""Backwards-compatibility shim.
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
The launcher's helpers were split across purpose-specific modules in
|
||||
the V5 layout reorganization:
|
||||
|
||||
from fastapi import FastAPI
|
||||
* ``import_app`` moved to ``openbb_mcp_server.app.bootstrap``.
|
||||
* ``parse_args`` moved to ``openbb_mcp_server.app.args``.
|
||||
|
||||
|
||||
def import_app(app_path: str, name: str = "app", factory: bool = False) -> FastAPI:
|
||||
"""Import the FastAPI app instance from a local file or module."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from importlib import import_module, util
|
||||
|
||||
def _is_module_colon_notation(app_path: str) -> bool:
|
||||
"""Check if the path uses module:name notation vs a Windows path."""
|
||||
if ":" not in app_path:
|
||||
return False
|
||||
# Windows absolute path check (e.g., C:\path or D:/path)
|
||||
if len(app_path) >= 2 and app_path[1] == ":" and app_path[0].isalpha():
|
||||
# Could still have colon notation: C:\path\file.py:app
|
||||
parts = app_path.split(":")
|
||||
return len(parts) > 2 # More than just drive letter colon
|
||||
return True
|
||||
|
||||
def _load_module_from_file_path(file_path: str):
|
||||
"""Load a Python module from a file path."""
|
||||
spec_name = os.path.basename(file_path).split(".")[0]
|
||||
spec = util.spec_from_file_location(spec_name, file_path)
|
||||
|
||||
if spec is None:
|
||||
raise RuntimeError(f"Failed to load the file specs for '{file_path}'")
|
||||
|
||||
module = util.module_from_spec(spec) # type: ignore
|
||||
sys.modules[spec_name] = module # type: ignore
|
||||
spec.loader.exec_module(module) # type: ignore
|
||||
return module
|
||||
|
||||
# Case 1: Module path with colon notation (e.g., "my_app.main:app" or "main:app")
|
||||
if _is_module_colon_notation(app_path):
|
||||
module_path, name = app_path.rsplit(":", 1)
|
||||
try: # First try to import as a module
|
||||
module = import_module(module_path)
|
||||
except ImportError: # If module import fails, try to load as a local file
|
||||
if not module_path.endswith(".py"):
|
||||
module_path += ".py"
|
||||
|
||||
if not Path(module_path).is_absolute():
|
||||
cwd = Path.cwd()
|
||||
file_path = str(cwd.joinpath(module_path).resolve())
|
||||
else:
|
||||
file_path = module_path
|
||||
|
||||
if not Path(file_path).exists():
|
||||
raise FileNotFoundError( # pylint: disable=raise-missing-from
|
||||
f"Error: Neither module '{module_path}' could be imported nor file '{file_path}' exists"
|
||||
)
|
||||
|
||||
module = _load_module_from_file_path(file_path)
|
||||
|
||||
# Case 2: File path (e.g., "main.py" or "my_app/main.py")
|
||||
else:
|
||||
if not Path(app_path).is_absolute():
|
||||
cwd = Path.cwd()
|
||||
app_path = str(cwd.joinpath(app_path).resolve())
|
||||
|
||||
if not Path(app_path).exists():
|
||||
raise FileNotFoundError(f"Error: The app file '{app_path}' does not exist")
|
||||
|
||||
module = _load_module_from_file_path(app_path)
|
||||
|
||||
if not hasattr(module, name):
|
||||
raise AttributeError(
|
||||
f"Error: The app file '{app_path}' does not contain an '{name}' instance"
|
||||
)
|
||||
|
||||
app_or_factory = getattr(module, name)
|
||||
|
||||
# Here we use the same approach as uvicorn to handle factory functions.
|
||||
# This prevents us from relying on explicit type annotations.
|
||||
# See: https://github.com/encode/uvicorn/blob/master/uvicorn/config.py
|
||||
try:
|
||||
app = app_or_factory()
|
||||
if not factory:
|
||||
print( # noqa: T201
|
||||
"\n\n[WARNING] "
|
||||
"App factory detected. Using it, but please consider setting the --factory flag explicitly.\n"
|
||||
)
|
||||
except TypeError:
|
||||
if factory:
|
||||
raise TypeError( # pylint: disable=raise-missing-from
|
||||
f"Error: The {name} instance in '{app_path}' appears not to be a callable factory function"
|
||||
)
|
||||
app = app_or_factory
|
||||
|
||||
if not isinstance(app, FastAPI):
|
||||
raise TypeError(
|
||||
f"Error: The {name} instance in '{app_path}' is not an instance of FastAPI"
|
||||
)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
cl_doc = """OpenBB MCP Server
|
||||
|
||||
Usage:
|
||||
>>> python -m openbb_mcp_server [OPTIONS]
|
||||
|
||||
>>> openbb-mcp --app ./some_app.py --host 0.0.0.0 --port 8005
|
||||
|
||||
Description:
|
||||
The OpenBB MCP Server is a component of the OpenBB Platform that provides
|
||||
a server for the Model-Context-Protocol. REST endpoints are converted into
|
||||
tools and made available to connected clients.
|
||||
|
||||
Settings can be defined in the configuration file, `~/.openbb_platform/mcp_settings.json`.
|
||||
|
||||
Alternatively, they can be defined as environment variables, with key values prefaced with `OPENBB_MCP_`
|
||||
|
||||
Options:
|
||||
--help
|
||||
Show this help message and exit.
|
||||
|
||||
--app <app_path>
|
||||
The path to the FastAPI app instance. This can be in the format
|
||||
'module.path:app_instance' or a file path 'path/to/app.py'.
|
||||
If not provided, the server will run with the default built-in app.
|
||||
|
||||
--name <name>
|
||||
The name of the FastAPI app instance or factory function in the app file.
|
||||
Defaults to 'app'.
|
||||
|
||||
--factory
|
||||
If set, the app is treated as a factory function that will be called
|
||||
to create the FastAPI app instance.
|
||||
|
||||
--host <host>
|
||||
The host to bind the server to. Defaults to '127.0.0.1'.
|
||||
This is a uvicorn argument.
|
||||
|
||||
--port <port>
|
||||
The port to bind the server to. Defaults to 8000.
|
||||
This is a uvicorn argument.
|
||||
|
||||
--transport <transport>
|
||||
The transport mechanism to use for the MCP server.
|
||||
Defaults to 'streamable-http'.
|
||||
|
||||
--allowed-categories <categories>
|
||||
A comma-separated list of tool categories to allow.
|
||||
If not provided, all categories are allowed.
|
||||
|
||||
--default-categories <categories>
|
||||
A comma-separated list of tool categories to be enabled by default.
|
||||
Defaults to 'all'.
|
||||
|
||||
--tool-discovery
|
||||
If set, tool discovery will be enabled.
|
||||
|
||||
--system-prompt <path>
|
||||
Path to a TXT file with the system prompt.
|
||||
|
||||
--server-prompts <path>
|
||||
Path to a JSON file with a list of server prompts.
|
||||
|
||||
All other arguments are passed through as MCPSettings.
|
||||
Every symbol is resolved lazily through ``__getattr__`` so the shim
|
||||
always reflects the current source-module state — important when test
|
||||
helpers (or hot-reload loops) pop the source module from
|
||||
``sys.modules`` and re-import it.
|
||||
"""
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
def parse_args():
|
||||
"""Parse command line arguments."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from openbb_core.env import Env
|
||||
#: ``shim_attr -> (source_module, source_attr)`` mapping.
|
||||
_LAZY_TARGETS: dict[str, tuple[str, str]] = {
|
||||
"import_app": ("openbb_mcp_server.app.bootstrap", "import_app"),
|
||||
"parse_args": ("openbb_mcp_server.app.args", "parse_args"),
|
||||
"cl_doc": ("openbb_mcp_server.app.args", "LAUNCH_SCRIPT_DESCRIPTION"),
|
||||
}
|
||||
|
||||
_ = Env()
|
||||
|
||||
args = sys.argv[1:].copy()
|
||||
_kwargs: dict = {}
|
||||
def __getattr__(name):
|
||||
"""Resolve a legacy name against its current source module."""
|
||||
target = _LAZY_TARGETS.get(name)
|
||||
if target is None:
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
module_path, attr = target
|
||||
return getattr(import_module(module_path), attr)
|
||||
|
||||
# Parse all command line arguments into kwargs
|
||||
for i, arg in enumerate(args):
|
||||
if arg == "--help":
|
||||
print(cl_doc) # noqa: T201
|
||||
sys.exit(0)
|
||||
if arg.startswith("--"):
|
||||
key = arg[2:].replace("-", "_")
|
||||
if key in ["no_use_colors", "use_colors"]:
|
||||
_kwargs["use_colors"] = key == "use_colors"
|
||||
elif i + 1 < len(args) and not args[i + 1].startswith("--"):
|
||||
value = args[i + 1]
|
||||
if isinstance(value, str) and value.lower() in ["false", "true"]:
|
||||
_kwargs[key] = value.lower() == "true"
|
||||
else:
|
||||
try:
|
||||
if (value.startswith("{") and value.endswith("}")) or (
|
||||
value.startswith("[") and value.endswith("]")
|
||||
):
|
||||
_kwargs[key] = json.loads(value)
|
||||
elif (
|
||||
key != "app"
|
||||
and ":" in value
|
||||
and all(":" in part for part in value.split(","))
|
||||
):
|
||||
_kwargs[key] = {
|
||||
k.strip(): v.strip()
|
||||
for k, v in (p.split(":", 1) for p in value.split(","))
|
||||
}
|
||||
else:
|
||||
_kwargs[key] = value
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
_kwargs[key] = value
|
||||
else:
|
||||
_kwargs[key] = True
|
||||
|
||||
# Extract and handle app import arguments
|
||||
_app_path = _kwargs.pop("app", None)
|
||||
_name = _kwargs.pop("name", "app")
|
||||
_factory = _kwargs.pop("factory", False)
|
||||
def __dir__() -> list[str]:
|
||||
"""Surface the lazy names for ``dir()`` and IDE autocomplete."""
|
||||
return sorted(_LAZY_TARGETS)
|
||||
|
||||
imported_app = None
|
||||
if _app_path:
|
||||
if ":" in _app_path:
|
||||
_app_instance_name = _app_path.split(":")[-1]
|
||||
_name = _app_instance_name if _app_instance_name else _name
|
||||
|
||||
if _factory and not _name:
|
||||
raise ValueError(
|
||||
"Error: The factory function name must be provided to the --name parameter when the factory flag is set."
|
||||
)
|
||||
imported_app = import_app(_app_path, _name, _factory)
|
||||
|
||||
# Extract MCP-specific arguments
|
||||
transport = _kwargs.pop("transport", "streamable-http")
|
||||
allowed_categories = _kwargs.pop("allowed_categories", None)
|
||||
default_categories = _kwargs.pop("default_categories", "all")
|
||||
tool_discovery = _kwargs.pop("tool_discovery", False)
|
||||
system_prompt = _kwargs.pop("system_prompt", None)
|
||||
server_prompts = _kwargs.pop("server_prompts", None)
|
||||
|
||||
class Args:
|
||||
"""Container for parsed command line arguments."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the Args container."""
|
||||
self.imported_app = imported_app
|
||||
self.transport = transport
|
||||
self.allowed_categories = allowed_categories
|
||||
self.default_categories = default_categories
|
||||
self.tool_discovery = tool_discovery
|
||||
self.system_prompt = system_prompt
|
||||
self.server_prompts = server_prompts
|
||||
self.uvicorn_config = _kwargs # All remaining kwargs go to uvicorn
|
||||
|
||||
return Args()
|
||||
__all__ = [ # noqa: F822
|
||||
"cl_doc",
|
||||
"import_app",
|
||||
"parse_args",
|
||||
]
|
||||
|
||||
150
openbb_platform/extensions/mcp_server/pyproject.toml
vendored
150
openbb_platform/extensions/mcp_server/pyproject.toml
vendored
@@ -1,24 +1,138 @@
|
||||
[tool.poetry]
|
||||
[project]
|
||||
name = "openbb-mcp-server"
|
||||
version = "1.4.0"
|
||||
description = "OpenBB Platform MCP Server"
|
||||
authors = ["OpenBB <hello@openbb.co>"]
|
||||
license = "AGPL-3.0-only"
|
||||
version = "2.0.0"
|
||||
description = "OpenBB Platform MCP Server: Model-Context-Protocol bridge for the Open Data Platform by OpenBB."
|
||||
authors = [{ name = "OpenBB Team", email = "hello@openbb.co" }]
|
||||
license = { text = "AGPL-3.0-only" }
|
||||
readme = "README.md"
|
||||
homepage = "https://openbb.co"
|
||||
repository = "https://github.com/openbb-finance/openbb"
|
||||
documentation = "https://docs.openbb.co"
|
||||
packages = [{ include = "openbb_mcp_server" }]
|
||||
include = ["openbb_mcp_server/skills/**/*"]
|
||||
requires-python = ">=3.10,<4"
|
||||
dependencies = [
|
||||
"openbb-core>=2.0.0",
|
||||
"fastmcp>=3.2.0",
|
||||
# Backport of stdlib ``tomllib`` for py3.10.
|
||||
"tomli>=2.0;python_version<'3.11'",
|
||||
]
|
||||
|
||||
[tool.poetry.scripts]
|
||||
openbb-mcp = "openbb_mcp_server.app.app:main"
|
||||
[project.optional-dependencies]
|
||||
# ``cli`` pulls openbb-cli in so its dispatchers (HttpDispatcher /
|
||||
# LocalDispatcher / runtime helpers) can be exposed as first-class
|
||||
# MCP tools. Optional because container deployments that only need
|
||||
# the REST→MCP bridge don't require the CLI surface.
|
||||
cli = ["openbb-cli>=2.0.0"]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.10,<4"
|
||||
openbb-core = "^1.6.7"
|
||||
fastmcp = ">=3.2.0"
|
||||
[project.scripts]
|
||||
openbb-mcp = "openbb_mcp_server.main:main"
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://openbb.co"
|
||||
Repository = "https://github.com/OpenBB-finance/OpenBB"
|
||||
Documentation = "https://docs.openbb.co/odp/python/extensions/interface/openbb-mcp"
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"openbb-devtools>=2.0.0",
|
||||
"httpx>=0.28.0,<1.0.0",
|
||||
"openbb-cli>=2.0.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core>=1.0.0"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["openbb_mcp_server"]
|
||||
|
||||
[tool.hatch.build.targets.sdist]
|
||||
include = [
|
||||
"openbb_mcp_server",
|
||||
"README.md",
|
||||
"pyproject.toml",
|
||||
]
|
||||
|
||||
# Sibling packages are path-sourced because v5 hasn't been published.
|
||||
[tool.uv.sources]
|
||||
openbb-core = { path = "../../core", editable = true }
|
||||
openbb-cli = { path = "../../../cli", editable = true }
|
||||
openbb-devtools = { path = "../devtools", editable = true }
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 88
|
||||
target-version = "py310"
|
||||
fix = true
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = [
|
||||
"D",
|
||||
"E",
|
||||
"W",
|
||||
"F",
|
||||
"S",
|
||||
"UP",
|
||||
"I",
|
||||
"PLC",
|
||||
"PLE",
|
||||
"PLR",
|
||||
"PLW",
|
||||
"SIM",
|
||||
"T20",
|
||||
]
|
||||
ignore = [
|
||||
"PLR2004",
|
||||
"PLR0913",
|
||||
"PLR0915",
|
||||
"PLC0415",
|
||||
"E402",
|
||||
"E501",
|
||||
"D202",
|
||||
"D203",
|
||||
"D205",
|
||||
"D206",
|
||||
"D210",
|
||||
"D212",
|
||||
"D213",
|
||||
"D214",
|
||||
"D215",
|
||||
"D300",
|
||||
"D400",
|
||||
"D404",
|
||||
"D405",
|
||||
"D406",
|
||||
"D407",
|
||||
"D408",
|
||||
"D409",
|
||||
"D410",
|
||||
"D411",
|
||||
"D413",
|
||||
"D415",
|
||||
"D416",
|
||||
"D417",
|
||||
]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"tests/**" = ["S101", "S108", "D", "SIM105", "SIM117"]
|
||||
"integration/**" = ["S101", "S108", "D", "SIM105", "SIM117"]
|
||||
"**/__init__.py" = ["F401"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
combine-as-imports = true
|
||||
force-wrap-aliases = true
|
||||
|
||||
[tool.ruff.lint.pylint]
|
||||
max-args = 8
|
||||
max-branches = 26
|
||||
max-returns = 9
|
||||
max-statements = 30
|
||||
|
||||
[tool.ruff.lint.pydocstyle]
|
||||
convention = "numpy"
|
||||
|
||||
[tool.ty]
|
||||
[tool.ty.environment]
|
||||
python-version = "3.10"
|
||||
|
||||
[tool.ty.src]
|
||||
include = ["openbb_mcp_server"]
|
||||
exclude = ["openbb_mcp_server/skills", "tests", "integration"]
|
||||
|
||||
[tool.ty.rules]
|
||||
unresolved-import = "warn"
|
||||
|
||||
@@ -7,6 +7,7 @@ from fastapi import FastAPI
|
||||
from fastapi.routing import APIRoute
|
||||
from fastmcp.server.providers.openapi import OpenAPITool
|
||||
from fastmcp.utilities.openapi import HTTPRoute
|
||||
|
||||
from openbb_mcp_server.app.app import (
|
||||
_extract_brief_description,
|
||||
_get_mcp_config_from_route,
|
||||
@@ -19,8 +20,9 @@ from openbb_mcp_server.models.settings import MCPSettings
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_transforms():
|
||||
with patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()), patch(
|
||||
"openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()
|
||||
with (
|
||||
patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()),
|
||||
patch("openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@@ -4,11 +4,12 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from openbb_mcp_server.app.auth import TokenAuthProvider, get_auth_provider
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
from starlette.datastructures import Headers
|
||||
from starlette.requests import Request
|
||||
|
||||
from openbb_mcp_server.app.auth import TokenAuthProvider, get_auth_provider
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
|
||||
# pylint: disable=W0621
|
||||
|
||||
|
||||
@@ -139,3 +140,63 @@ def test_get_auth_provider(mock_settings):
|
||||
provider = get_auth_provider(mock_settings)
|
||||
assert isinstance(provider, TokenAuthProvider)
|
||||
assert provider.server_auth == ("testuser", "testpass")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_authorize_invalid_base64_token_raises_401(
|
||||
mock_settings, mock_request_with_auth
|
||||
):
|
||||
"""``Bearer notbase64`` → base64 decode fails → 401."""
|
||||
auth_provider = TokenAuthProvider(mock_settings)
|
||||
request = Request(
|
||||
scope={
|
||||
"type": "http",
|
||||
"headers": Headers({"authorization": "Bearer not%base64$"}).raw,
|
||||
}
|
||||
)
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
await auth_provider.authorize(request)
|
||||
assert excinfo.value.status_code == 401
|
||||
assert "base64" in str(excinfo.value.detail).lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_verify_token_returns_none_when_no_auth(mock_settings_no_auth):
|
||||
"""No server_auth configured → verify_token short-circuits to None."""
|
||||
auth_provider = TokenAuthProvider(mock_settings_no_auth)
|
||||
assert await auth_provider.verify_token("anything") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_verify_token_returns_none_for_bad_base64(mock_settings):
|
||||
"""A non-base64 token → verify_token swallows the exception."""
|
||||
auth_provider = TokenAuthProvider(mock_settings)
|
||||
assert await auth_provider.verify_token("not%base64$") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("openbb_mcp_server.app.auth.base64")
|
||||
@patch("openbb_mcp_server.app.auth.secrets")
|
||||
async def test_verify_token_swallows_outer_exception(
|
||||
mock_secrets, mock_base64, mock_settings
|
||||
):
|
||||
"""Outer ``except (ValueError, HTTPException)`` swallows surprise errors."""
|
||||
mock_base64.b64decode.return_value.decode.return_value = "testuser:testpass"
|
||||
mock_secrets.compare_digest.side_effect = ValueError("simulated")
|
||||
auth_provider = TokenAuthProvider(mock_settings)
|
||||
assert await auth_provider.verify_token("anything") is None
|
||||
|
||||
|
||||
def test_token_auth_provider_uses_https_when_ssl_configured():
|
||||
"""``ssl_keyfile`` + ``ssl_certfile`` flips the scheme to https."""
|
||||
settings = MCPSettings(
|
||||
uvicorn_config={
|
||||
"host": "0.0.0.0", # noqa: S104
|
||||
"port": "443",
|
||||
"ssl_keyfile": "/etc/ssl/key.pem",
|
||||
"ssl_certfile": "/etc/ssl/cert.pem",
|
||||
},
|
||||
server_auth=("u", "p"),
|
||||
)
|
||||
provider = TokenAuthProvider(settings)
|
||||
assert provider.resource_server_url.startswith("https://")
|
||||
|
||||
@@ -7,14 +7,16 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
|
||||
from openbb_mcp_server.app.app import create_mcp_server
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_transforms():
|
||||
with patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()), patch(
|
||||
"openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()
|
||||
with (
|
||||
patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()),
|
||||
patch("openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()),
|
||||
):
|
||||
yield
|
||||
|
||||
@@ -45,7 +47,9 @@ def test_load_prompts_from_json(
|
||||
prompts_file = tmp_path / "prompts.json"
|
||||
prompts_file.write_text(json.dumps(prompts_data))
|
||||
|
||||
settings = MCPSettings(server_prompts_file=str(prompts_file), default_skills_dir=None) # type: ignore
|
||||
settings = MCPSettings(
|
||||
server_prompts_file=str(prompts_file), default_skills_dir=None
|
||||
) # type: ignore
|
||||
fastapi_app = FastAPI()
|
||||
|
||||
mock_processed_data = MagicMock()
|
||||
@@ -92,7 +96,9 @@ def test_skip_invalid_prompts(
|
||||
prompts_file = tmp_path / "prompts.json"
|
||||
prompts_file.write_text(json.dumps(prompts_data))
|
||||
|
||||
settings = MCPSettings(server_prompts_file=str(prompts_file), default_skills_dir=None) # type: ignore
|
||||
settings = MCPSettings(
|
||||
server_prompts_file=str(prompts_file), default_skills_dir=None
|
||||
) # type: ignore
|
||||
fastapi_app = FastAPI()
|
||||
|
||||
mock_processed_data = MagicMock()
|
||||
@@ -136,7 +142,9 @@ def test_skip_invalid_arguments_in_prompts(
|
||||
prompts_file = tmp_path / "prompts.json"
|
||||
prompts_file.write_text(json.dumps(prompts_data))
|
||||
|
||||
settings = MCPSettings(server_prompts_file=str(prompts_file), default_skills_dir=None) # type: ignore
|
||||
settings = MCPSettings(
|
||||
server_prompts_file=str(prompts_file), default_skills_dir=None
|
||||
) # type: ignore
|
||||
fastapi_app = FastAPI()
|
||||
|
||||
mock_processed_data = MagicMock()
|
||||
@@ -187,7 +195,9 @@ async def test_prompts_as_tools_transform_and_defaults(
|
||||
prompts_file = tmp_path / "prompts.json"
|
||||
prompts_file.write_text(json.dumps(prompts_data))
|
||||
|
||||
settings = MCPSettings(server_prompts_file=str(prompts_file), default_skills_dir=None) # type: ignore
|
||||
settings = MCPSettings(
|
||||
server_prompts_file=str(prompts_file), default_skills_dir=None
|
||||
) # type: ignore
|
||||
fastapi_app = FastAPI()
|
||||
|
||||
mock_processed_data = MagicMock()
|
||||
@@ -217,6 +227,7 @@ async def test_prompts_as_tools_transform_and_defaults(
|
||||
async def test_static_prompt_render_applies_defaults():
|
||||
"""Test that StaticPrompt.render() applies argument_defaults when caller omits them."""
|
||||
from fastmcp.prompts import PromptArgument
|
||||
|
||||
from openbb_mcp_server.models.prompts import StaticPrompt
|
||||
|
||||
prompt = StaticPrompt(
|
||||
|
||||
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastmcp.prompts.function_prompt import FunctionPrompt
|
||||
|
||||
from openbb_mcp_server.app.app import _VENDOR_SKILLS_PROVIDERS, create_mcp_server
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
|
||||
@@ -40,8 +41,9 @@ def _make_mocks(mock_from_fastapi, mock_category_index, mock_process_routes):
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_transforms():
|
||||
with patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()), patch(
|
||||
"openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()
|
||||
with (
|
||||
patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()),
|
||||
patch("openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()),
|
||||
):
|
||||
yield
|
||||
|
||||
@@ -178,7 +180,9 @@ def test_multiple_vendor_providers_added(
|
||||
CursorSkillsProvider,
|
||||
)
|
||||
|
||||
settings = MCPSettings(default_skills_dir=None, skills_providers=["claude", "cursor"]) # type: ignore
|
||||
settings = MCPSettings(
|
||||
default_skills_dir=None, skills_providers=["claude", "cursor"]
|
||||
) # type: ignore
|
||||
mock_mcp = _make_mocks(mock_from_fastapi, mock_category_index, mock_process_routes)
|
||||
|
||||
create_mcp_server(settings, FastAPI())
|
||||
@@ -198,7 +202,9 @@ def test_unknown_vendor_provider_logs_warning(
|
||||
mock_from_fastapi, mock_category_index, mock_process_routes, mock_logger
|
||||
):
|
||||
"""Unknown provider names log a warning and do not crash."""
|
||||
settings = MCPSettings(default_skills_dir=None, skills_providers=["unknown_provider"]) # type: ignore
|
||||
settings = MCPSettings(
|
||||
default_skills_dir=None, skills_providers=["unknown_provider"]
|
||||
) # type: ignore
|
||||
mock_mcp = _make_mocks(mock_from_fastapi, mock_category_index, mock_process_routes)
|
||||
|
||||
create_mcp_server(settings, FastAPI())
|
||||
@@ -219,7 +225,9 @@ def test_skills_reload_passed_to_vendor_providers(
|
||||
"""skills_reload=True is forwarded to vendor providers."""
|
||||
from fastmcp.server.providers.skills import ClaudeSkillsProvider
|
||||
|
||||
settings = MCPSettings(default_skills_dir=None, skills_providers=["claude"], skills_reload=True) # type: ignore
|
||||
settings = MCPSettings(
|
||||
default_skills_dir=None, skills_providers=["claude"], skills_reload=True
|
||||
) # type: ignore
|
||||
mock_mcp = _make_mocks(mock_from_fastapi, mock_category_index, mock_process_routes)
|
||||
|
||||
create_mcp_server(settings, FastAPI())
|
||||
|
||||
@@ -14,6 +14,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from mcp.types import TextContent
|
||||
|
||||
from openbb_mcp_server.app.app import create_mcp_server
|
||||
from openbb_mcp_server.models.category_index import CategoryIndex
|
||||
from openbb_mcp_server.models.prompts import StaticPrompt
|
||||
@@ -92,8 +93,9 @@ def _build_server(
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_transforms():
|
||||
with patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()), patch(
|
||||
"openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()
|
||||
with (
|
||||
patch("openbb_mcp_server.app.app.PromptsAsTools", new=MagicMock()),
|
||||
patch("openbb_mcp_server.app.app.ResourcesAsTools", new=MagicMock()),
|
||||
):
|
||||
yield
|
||||
|
||||
@@ -706,9 +708,9 @@ class TestBundledSkillRendering:
|
||||
if not in_frontmatter and line.startswith("#"):
|
||||
heading = line.lstrip("# ").strip()
|
||||
break
|
||||
assert (
|
||||
heading == expected_heading
|
||||
), f"Skill '{skill_name}' heading mismatch: got '{heading}', expected '{expected_heading}'"
|
||||
assert heading == expected_heading, (
|
||||
f"Skill '{skill_name}' heading mismatch: got '{heading}', expected '{expected_heading}'"
|
||||
)
|
||||
|
||||
|
||||
# ===================================================================
|
||||
@@ -765,9 +767,9 @@ class TestSkillsIntegration:
|
||||
skill_file = SKILLS_DIR / skill_name / "SKILL.md"
|
||||
assert skill_file.exists(), f"Missing: {skill_file}"
|
||||
content = skill_file.read_text(encoding="utf-8")
|
||||
assert (
|
||||
len(content) > 500
|
||||
), f"Skill '{skill_name}' SKILL.md is suspiciously short ({len(content)} chars)"
|
||||
assert len(content) > 500, (
|
||||
f"Skill '{skill_name}' SKILL.md is suspiciously short ({len(content)} chars)"
|
||||
)
|
||||
|
||||
@patch("openbb_mcp_server.app.app.process_fastapi_routes_for_mcp")
|
||||
@patch("openbb_mcp_server.app.app.CategoryIndex")
|
||||
@@ -798,6 +800,6 @@ class TestSkillsIntegration:
|
||||
for c in mock_mcp_instance.add_prompt.call_args_list
|
||||
if hasattr(c[0][0], "tags") and "skill" in c[0][0].tags
|
||||
]
|
||||
assert (
|
||||
skill_prompt_calls == []
|
||||
), "Skills should not be registered as prompts in FastMCP v3 — use add_provider instead"
|
||||
assert skill_prompt_calls == [], (
|
||||
"Skills should not be registered as prompts in FastMCP v3 — use add_provider instead"
|
||||
)
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from openbb_mcp_server.models.mcp_config import (
|
||||
ArgumentDefinitionModel,
|
||||
HTTPMethod,
|
||||
@@ -11,7 +13,6 @@ from openbb_mcp_server.models.mcp_config import (
|
||||
is_valid_mcp_config,
|
||||
validate_mcp_config,
|
||||
)
|
||||
from pydantic import ValidationError
|
||||
|
||||
|
||||
def test_argument_definition_model():
|
||||
|
||||
@@ -3,10 +3,29 @@
|
||||
import pytest
|
||||
from fastmcp.exceptions import PromptError
|
||||
from fastmcp.prompts import PromptArgument
|
||||
from mcp.types import PromptMessage, TextContent
|
||||
from fastmcp.prompts.base import Message
|
||||
from mcp.types import TextContent
|
||||
|
||||
from openbb_mcp_server.models.prompts import StaticPrompt
|
||||
|
||||
|
||||
def _assert_user_message(rendered, text: str) -> None:
|
||||
"""Assert ``rendered`` is a single fastmcp ``Message`` with ``text``.
|
||||
|
||||
``StaticPrompt.render`` returns ``list[Message | str]`` (the same
|
||||
union ``Prompt.render`` accepts). Verify the shape rather than
|
||||
construct a comparison object — fastmcp's ``Message`` doesn't
|
||||
implement structural equality, so an ``==`` check between two
|
||||
instances would always fail.
|
||||
"""
|
||||
assert len(rendered) == 1
|
||||
msg = rendered[0]
|
||||
assert isinstance(msg, Message)
|
||||
assert msg.role == "user"
|
||||
assert isinstance(msg.content, TextContent)
|
||||
assert msg.content.text == text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_static_prompt_render_success():
|
||||
"""Test successful rendering of StaticPrompt."""
|
||||
@@ -16,11 +35,7 @@ async def test_static_prompt_render_success():
|
||||
arguments=[PromptArgument(name="name", required=True)],
|
||||
)
|
||||
rendered = await prompt.render(arguments={"name": "World"})
|
||||
assert rendered == [
|
||||
PromptMessage(
|
||||
role="user", content=TextContent(type="text", text="Hello, World!")
|
||||
)
|
||||
]
|
||||
_assert_user_message(rendered, "Hello, World!")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -48,11 +63,7 @@ async def test_static_prompt_render_no_arguments():
|
||||
"""Test rendering StaticPrompt with no arguments."""
|
||||
prompt = StaticPrompt(name="test_prompt", content="Hello, World!")
|
||||
rendered = await prompt.render()
|
||||
assert rendered == [
|
||||
PromptMessage(
|
||||
role="user", content=TextContent(type="text", text="Hello, World!")
|
||||
)
|
||||
]
|
||||
_assert_user_message(rendered, "Hello, World!")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -64,11 +75,7 @@ async def test_static_prompt_render_optional_argument():
|
||||
arguments=[PromptArgument(name="name", required=False)],
|
||||
)
|
||||
rendered = await prompt.render(arguments={"name": "Optional"})
|
||||
assert rendered == [
|
||||
PromptMessage(
|
||||
role="user", content=TextContent(type="text", text="Hello, Optional!")
|
||||
)
|
||||
]
|
||||
_assert_user_message(rendered, "Hello, Optional!")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -83,12 +90,7 @@ async def test_static_prompt_render_multiple_arguments():
|
||||
],
|
||||
)
|
||||
rendered = await prompt.render(arguments={"name": "User", "place": "OpenBB"})
|
||||
assert rendered == [
|
||||
PromptMessage(
|
||||
role="user",
|
||||
content=TextContent(type="text", text="Hello, User! Welcome to OpenBB."),
|
||||
)
|
||||
]
|
||||
_assert_user_message(rendered, "Hello, User! Welcome to OpenBB.")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -96,8 +98,4 @@ async def test_static_prompt_render_with_none_arguments_in_prompt():
|
||||
"""Test rendering StaticPrompt when arguments attribute is None."""
|
||||
prompt = StaticPrompt(name="test_prompt", content="Hello, World!", arguments=None)
|
||||
rendered = await prompt.render()
|
||||
assert rendered == [
|
||||
PromptMessage(
|
||||
role="user", content=TextContent(type="text", text="Hello, World!")
|
||||
)
|
||||
]
|
||||
_assert_user_message(rendered, "Hello, World!")
|
||||
|
||||
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
from openbb_mcp_server.service.mcp_service import MCPService
|
||||
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
"""Unit tests for the app_import module."""
|
||||
"""Unit tests for the ``openbb_mcp_server.utils.app_import`` shim.
|
||||
|
||||
The shim re-exports ``import_app`` and ``parse_args`` from the V5
|
||||
locations under ``openbb_mcp_server.app.bootstrap`` /
|
||||
``.app.args``. These tests verify both the lazy ``__getattr__``
|
||||
re-export (so external scripts that imported from the legacy path
|
||||
keep working) AND the underlying behavior of the new modules.
|
||||
"""
|
||||
|
||||
# pylint: disable=W0621
|
||||
|
||||
@@ -8,6 +15,7 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
|
||||
from openbb_mcp_server.utils.app_import import import_app, parse_args
|
||||
|
||||
|
||||
@@ -32,6 +40,62 @@ def not_a_factory():
|
||||
return app_file
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compat-shim wiring
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_shim_lazy_resolution_matches_source():
|
||||
"""``utils.app_import.import_app`` re-exports
|
||||
``app.bootstrap.import_app`` via lazy ``__getattr__``.
|
||||
"""
|
||||
from openbb_mcp_server.app import bootstrap as bootstrap_mod
|
||||
from openbb_mcp_server.utils import app_import as shim
|
||||
|
||||
assert shim.import_app is bootstrap_mod.import_app
|
||||
|
||||
|
||||
def test_shim_parse_args_matches_source():
|
||||
"""``utils.app_import.parse_args`` re-exports ``app.args.parse_args``."""
|
||||
from openbb_mcp_server.app import args as args_mod
|
||||
from openbb_mcp_server.utils import app_import as shim
|
||||
|
||||
assert shim.parse_args is args_mod.parse_args
|
||||
|
||||
|
||||
def test_shim_unknown_attribute_raises():
|
||||
"""Unknown shim attribute access raises a clean ``AttributeError``."""
|
||||
from openbb_mcp_server.utils import app_import as shim
|
||||
|
||||
with pytest.raises(AttributeError, match="no attribute 'no_such_thing'"):
|
||||
_ = shim.no_such_thing
|
||||
|
||||
|
||||
def test_shim_dir_lists_lazy_targets():
|
||||
"""``dir(shim)`` surfaces the lazy re-exported names."""
|
||||
from openbb_mcp_server.utils import app_import as shim
|
||||
|
||||
listed = dir(shim)
|
||||
for name in ("import_app", "parse_args", "cl_doc"):
|
||||
assert name in listed
|
||||
assert listed == sorted(listed)
|
||||
|
||||
|
||||
def test_shim_cl_doc_proxies_launch_script_description():
|
||||
"""The legacy ``cl_doc`` name maps to the new
|
||||
``LAUNCH_SCRIPT_DESCRIPTION`` constant on ``app.args``.
|
||||
"""
|
||||
from openbb_mcp_server.app import args as args_mod
|
||||
from openbb_mcp_server.utils import app_import as shim
|
||||
|
||||
assert shim.cl_doc is args_mod.LAUNCH_SCRIPT_DESCRIPTION
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# import_app behavior
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_import_app_from_module_colon_notation(dummy_app_file: Path):
|
||||
"""Test importing an app from a module path with colon notation."""
|
||||
sys.path.insert(0, str(dummy_app_file.parent))
|
||||
@@ -73,6 +137,16 @@ def test_import_app_factory_not_callable(dummy_app_file: Path):
|
||||
import_app(f"{dummy_app_file}:app", factory=True)
|
||||
|
||||
|
||||
def test_import_app_factory_warning_when_flag_omitted(dummy_app_file: Path, capsys):
|
||||
"""Without ``factory=True``, a callable is still invoked but a soft
|
||||
warning is emitted to stdout — mirrors uvicorn's behavior.
|
||||
"""
|
||||
app = import_app(f"{dummy_app_file}:create_app")
|
||||
assert isinstance(app, FastAPI)
|
||||
captured = capsys.readouterr()
|
||||
assert "App factory detected" in captured.out
|
||||
|
||||
|
||||
def test_import_app_not_fastapi_instance(dummy_app_file: Path):
|
||||
"""Test that a TypeError is raised when the imported object is not a FastAPI instance."""
|
||||
with pytest.raises(TypeError, match="is not an instance of FastAPI"):
|
||||
@@ -91,10 +165,52 @@ def test_import_app_attribute_not_found(dummy_app_file: Path):
|
||||
import_app(f"{dummy_app_file}:invalid_app")
|
||||
|
||||
|
||||
def test_import_app_module_colon_with_failed_import_falls_back_to_file(
|
||||
tmp_path: Path, monkeypatch
|
||||
):
|
||||
"""``some.module:app`` where ``some.module`` isn't importable falls
|
||||
back to treating the prefix as a file path (with ``.py`` appended).
|
||||
"""
|
||||
app_content = """
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI(title="Fallback App")
|
||||
"""
|
||||
fallback = tmp_path / "fallback_app.py"
|
||||
fallback.write_text(app_content)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
try:
|
||||
# ``fallback_app:app`` — there's no module named ``fallback_app``
|
||||
# importable from any sys.path entry, so the loader falls back
|
||||
# to ``fallback_app.py`` in the current directory.
|
||||
app = import_app("fallback_app:app")
|
||||
assert isinstance(app, FastAPI)
|
||||
assert app.title == "Fallback App"
|
||||
finally:
|
||||
sys.modules.pop("fallback_app", None)
|
||||
|
||||
|
||||
def test_import_app_module_colon_with_failed_import_raises_when_file_missing(
|
||||
tmp_path: Path, monkeypatch
|
||||
):
|
||||
"""If both the module import fails AND the file doesn't exist, the
|
||||
error message names both attempts.
|
||||
"""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
with pytest.raises(FileNotFoundError, match="Neither module"):
|
||||
import_app("does_not_exist:app")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# parse_args behavior — new dict-shaped API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_args_simple():
|
||||
"""Test parsing of simple command-line arguments."""
|
||||
"""Default-flag parse run produces the expected dict shape."""
|
||||
test_args = [
|
||||
"mcp_server",
|
||||
"openbb-mcp",
|
||||
"--transport",
|
||||
"test_transport",
|
||||
"--allowed_categories",
|
||||
@@ -103,51 +219,56 @@ def test_parse_args_simple():
|
||||
"true",
|
||||
]
|
||||
with patch.object(sys, "argv", test_args):
|
||||
args = parse_args()
|
||||
assert args.transport == "test_transport"
|
||||
assert args.allowed_categories == "cat1,cat2"
|
||||
assert args.tool_discovery is True
|
||||
assert args.imported_app is None
|
||||
result = parse_args()
|
||||
assert result["transport"] == "test_transport"
|
||||
assert result["mcp_overrides"]["allowed_categories"] == "cat1,cat2"
|
||||
assert result["mcp_overrides"]["tool_discovery"] is True
|
||||
assert result["app"] is None
|
||||
|
||||
|
||||
def test_parse_args_with_app(dummy_app_file: Path):
|
||||
"""Test parsing arguments when an app path is provided."""
|
||||
test_args = ["mcp_server", "--app", f"{dummy_app_file}:app"]
|
||||
"""``--app PATH`` resolves to a FastAPI instance under ``app``."""
|
||||
test_args = ["openbb-mcp", "--app", f"{dummy_app_file}:app"]
|
||||
with patch.object(sys, "argv", test_args):
|
||||
args = parse_args()
|
||||
assert isinstance(args.imported_app, FastAPI)
|
||||
assert args.imported_app.title == "Dummy App"
|
||||
result = parse_args()
|
||||
assert isinstance(result["app"], FastAPI)
|
||||
assert result["app"].title == "Dummy App"
|
||||
|
||||
|
||||
def test_parse_args_with_factory_app(dummy_app_file: Path):
|
||||
"""Test parsing arguments with an app factory."""
|
||||
"""``--factory true`` invokes the named callable to produce the app."""
|
||||
test_args = [
|
||||
"mcp_server",
|
||||
"openbb-mcp",
|
||||
"--app",
|
||||
f"{dummy_app_file}:create_app",
|
||||
"--factory",
|
||||
"true",
|
||||
]
|
||||
with patch.object(sys, "argv", test_args):
|
||||
args = parse_args()
|
||||
assert isinstance(args.imported_app, FastAPI)
|
||||
assert args.imported_app.title == "Dummy Factory App"
|
||||
result = parse_args()
|
||||
assert isinstance(result["app"], FastAPI)
|
||||
assert result["app"].title == "Dummy Factory App"
|
||||
|
||||
|
||||
def test_parse_args_help():
|
||||
"""Test the --help argument."""
|
||||
with patch.object(sys, "argv", ["mcp_server", "--help"]):
|
||||
"""The --help flag exits 0 after printing the launch description."""
|
||||
with patch.object(sys, "argv", ["openbb-mcp", "--help"]):
|
||||
with pytest.raises(SystemExit) as excinfo:
|
||||
parse_args()
|
||||
assert excinfo.value.code == 0
|
||||
|
||||
|
||||
def test_parse_args_factory_no_name_error():
|
||||
"""Test ValueError when factory is true but no app name is provided."""
|
||||
def test_parse_args_factory_no_name_error(tmp_path: Path):
|
||||
"""``--factory true --name ""`` for a path without a colon raises."""
|
||||
# Use a real file to bypass the import_app file-existence check; the
|
||||
# ValueError fires on the name check before import_app runs.
|
||||
app_file = tmp_path / "some_app.py"
|
||||
app_file.write_text("from fastapi import FastAPI\napp = FastAPI()\n")
|
||||
|
||||
test_args = [
|
||||
"mcp_server",
|
||||
"openbb-mcp",
|
||||
"--app",
|
||||
"some_app.py",
|
||||
str(app_file),
|
||||
"--factory",
|
||||
"true",
|
||||
"--name",
|
||||
@@ -163,6 +284,61 @@ def test_parse_args_factory_no_name_error():
|
||||
parse_args()
|
||||
|
||||
|
||||
def test_parse_args_uvicorn_passthrough():
|
||||
"""Unrecognized launcher flags land in ``uvicorn_overrides``."""
|
||||
with patch.object( # noqa: S104
|
||||
sys,
|
||||
"argv",
|
||||
["openbb-mcp", "--host", "0.0.0.0", "--port", "9000"], # noqa: S104
|
||||
):
|
||||
result = parse_args()
|
||||
assert result["uvicorn_overrides"]["host"] == "0.0.0.0" # noqa: S104
|
||||
assert result["uvicorn_overrides"]["port"] == "9000"
|
||||
|
||||
|
||||
def test_parse_args_use_colors_flag():
|
||||
"""``--use-colors`` / ``--no-use-colors`` map to the same kwarg."""
|
||||
with patch.object(sys, "argv", ["openbb-mcp", "--no-use-colors"]):
|
||||
result = parse_args()
|
||||
assert result["uvicorn_overrides"].get("use_colors") is False
|
||||
with patch.object(sys, "argv", ["openbb-mcp", "--use-colors"]):
|
||||
result = parse_args()
|
||||
assert result["uvicorn_overrides"].get("use_colors") is True
|
||||
|
||||
|
||||
def test_parse_args_json_value_decodes():
|
||||
"""JSON-shaped values (``[...]`` / ``{...}``) get decoded."""
|
||||
with patch.object(
|
||||
sys, "argv", ["openbb-mcp", "--default_categories", '["equity","crypto"]']
|
||||
):
|
||||
result = parse_args()
|
||||
assert result["mcp_overrides"]["default_categories"] == ["equity", "crypto"]
|
||||
|
||||
|
||||
def test_parse_args_bare_flag_is_true():
|
||||
"""A flag with no following value parses as ``True``."""
|
||||
with patch.object(sys, "argv", ["openbb-mcp", "--debug"]):
|
||||
result = parse_args()
|
||||
assert result["uvicorn_overrides"].get("debug") is True
|
||||
|
||||
|
||||
def test_parse_args_spec_and_app_mutually_exclusive(tmp_path: Path):
|
||||
"""Supplying both ``--spec`` and ``--app`` raises a clear error."""
|
||||
spec_file = tmp_path / "x.spec"
|
||||
spec_file.write_text("{}")
|
||||
app_file = tmp_path / "a.py"
|
||||
app_file.write_text("from fastapi import FastAPI\napp = FastAPI()\n")
|
||||
with (
|
||||
patch.object(
|
||||
sys,
|
||||
"argv",
|
||||
["openbb-mcp", "--spec", str(spec_file), "--app", str(app_file)],
|
||||
),
|
||||
pytest.raises(ValueError, match="--spec and --app are mutually exclusive"),
|
||||
):
|
||||
parse_args()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Path Handling Tests - Cross-Platform Compatibility
|
||||
# =============================================================================
|
||||
@@ -283,15 +459,13 @@ custom_app = FastAPI(title="Custom Named App")
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
|
||||
def test_windows_absolute_path(self, app_file: Path):
|
||||
"""Test Windows-style absolute paths"""
|
||||
# On Windows, tmp_path will have a drive letter (e.g., C:\...)
|
||||
"""Test Windows-style absolute paths."""
|
||||
app = import_app(str(app_file), "app", False)
|
||||
assert isinstance(app, FastAPI)
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
|
||||
def test_windows_path_with_colon_notation(self, app_file: Path):
|
||||
"""Test Windows path with colon notation."""
|
||||
# Windows path with colon notation: C:\path\app.py:app
|
||||
app = import_app(f"{app_file}:app", "app", False)
|
||||
assert isinstance(app, FastAPI)
|
||||
|
||||
@@ -299,13 +473,14 @@ custom_app = FastAPI(title="Custom Named App")
|
||||
class TestPathDetectionHelpers:
|
||||
"""Test path detection logic for cross-platform compatibility."""
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="Unix-specific test")
|
||||
@pytest.mark.skipif(
|
||||
sys.platform == "win32",
|
||||
reason="Unix-style absolute paths only — '/home/...' is relative on Windows",
|
||||
)
|
||||
def test_is_absolute_path_detection_unix(self):
|
||||
"""Test absolute path detection for Unix paths."""
|
||||
# Unix absolute paths
|
||||
assert Path("/home/user/app.py").is_absolute() is True
|
||||
assert Path("/app.py").is_absolute() is True
|
||||
# Relative paths
|
||||
assert Path("app.py").is_absolute() is False
|
||||
assert Path("./app.py").is_absolute() is False
|
||||
assert Path("subdir/app.py").is_absolute() is False
|
||||
@@ -313,16 +488,13 @@ class TestPathDetectionHelpers:
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
|
||||
def test_is_absolute_path_detection_windows(self):
|
||||
"""Test absolute path detection for Windows paths."""
|
||||
# Windows absolute paths
|
||||
assert Path("C:\\Users\\app.py").is_absolute() is True
|
||||
assert Path("D:/Projects/app.py").is_absolute() is True
|
||||
# Relative paths
|
||||
assert Path("app.py").is_absolute() is False
|
||||
assert Path(".\\app.py").is_absolute() is False
|
||||
|
||||
def test_colon_notation_vs_windows_drive(self):
|
||||
"""Test distinguishing module:name notation from Windows drive letters."""
|
||||
# These should be recognized as module:name notation
|
||||
module_notations = [
|
||||
"module:app",
|
||||
"package.module:app",
|
||||
@@ -330,16 +502,13 @@ class TestPathDetectionHelpers:
|
||||
]
|
||||
|
||||
for notation in module_notations:
|
||||
# Has colon and is not a Windows drive letter pattern
|
||||
assert ":" in notation
|
||||
# First char before colon is not a single letter (drive)
|
||||
parts = notation.split(":")
|
||||
assert len(parts[0]) > 1 or not parts[0].isalpha()
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test")
|
||||
def test_windows_drive_letter_detection(self):
|
||||
"""Test detection of Windows drive letters vs colon notation."""
|
||||
# Windows paths with drive letters
|
||||
windows_paths = [
|
||||
"C:\\app.py",
|
||||
"D:/Projects/app.py",
|
||||
@@ -348,14 +517,10 @@ class TestPathDetectionHelpers:
|
||||
|
||||
for path_str in windows_paths:
|
||||
path = Path(path_str)
|
||||
# Should be detected as absolute (has drive)
|
||||
assert path.is_absolute()
|
||||
# Drive should be detected
|
||||
assert path.drive != ""
|
||||
|
||||
# Windows path WITH colon notation (e.g., C:\path\app.py:myapp)
|
||||
complex_path = "C:\\Projects\\app.py:myapp"
|
||||
# This has multiple colons - drive colon + notation colon
|
||||
assert complex_path.count(":") == 2
|
||||
|
||||
|
||||
@@ -364,9 +529,6 @@ class TestModuleColonNotationHelper:
|
||||
|
||||
def test_simple_module_notation(self):
|
||||
"""Test simple module:name notation is detected correctly."""
|
||||
# These should be recognized as module colon notation
|
||||
# We test the behavior indirectly through import_app
|
||||
# Module notation without file should try import first
|
||||
with pytest.raises((ImportError, FileNotFoundError)):
|
||||
import_app("nonexistent_module:app")
|
||||
|
||||
@@ -386,7 +548,6 @@ app = FastAPI(title="No Colon App")
|
||||
|
||||
def test_dotted_module_path_notation(self, tmp_path: Path):
|
||||
"""Test dotted module paths like 'package.subpackage.module:app'."""
|
||||
# Create a package structure
|
||||
pkg_dir = tmp_path / "mypkg"
|
||||
pkg_dir.mkdir()
|
||||
(pkg_dir / "__init__.py").write_text("")
|
||||
@@ -409,7 +570,6 @@ app = FastAPI(title="Dotted Module App")
|
||||
assert app.title == "Dotted Module App"
|
||||
finally:
|
||||
sys.path.pop(0)
|
||||
# Clean up sys.modules
|
||||
for mod in list(sys.modules.keys()):
|
||||
if mod.startswith("mypkg"):
|
||||
del sys.modules[mod]
|
||||
|
||||
@@ -9,6 +9,7 @@ import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.routing import APIRoute
|
||||
from fastmcp.server.providers.openapi import MCPType
|
||||
|
||||
from openbb_mcp_server.models.settings import MCPSettings
|
||||
from openbb_mcp_server.utils.fastapi import (
|
||||
_create_prompt_definitions_for_route,
|
||||
|
||||
@@ -75,7 +75,7 @@ def filter_eps(eps: EntryPoints | dict, group: str) -> tuple[EntryPoint, ...]:
|
||||
|
||||
|
||||
def list_openbb_extensions() -> tuple[set[str], set[str], set[str]]:
|
||||
"""list installed openbb extensions and providers.
|
||||
"""List installed openbb extensions and providers.
|
||||
|
||||
Returns
|
||||
-------
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Generate API integration tests."""
|
||||
|
||||
import argparse
|
||||
import inspect as _inspect
|
||||
import os
|
||||
from pathlib import Path
|
||||
import inspect as _inspect
|
||||
from typing import Literal
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Integration test generator."""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path, PosixPath
|
||||
import inspect as _inspect
|
||||
from pathlib import Path, PosixPath
|
||||
from typing import (
|
||||
Any,
|
||||
Literal,
|
||||
|
||||
@@ -520,7 +520,7 @@ def parse_agency_from_urn(code_urn: str) -> str | None:
|
||||
try:
|
||||
# Extract everything after the "=" and before the last ":"
|
||||
# Example: "ISORA:CL_RAFIT_LABELS(1.0+.0).CL_TOPIC_1"
|
||||
after_equals = code_urn.split("=")[-1]
|
||||
after_equals = code_urn.rsplit("=", maxsplit=1)[-1]
|
||||
# Split by ":" to get agency (first part) and codelist info (second part)
|
||||
parts = after_equals.split(":")
|
||||
if len(parts) >= 2:
|
||||
@@ -543,7 +543,7 @@ def parse_indicator_code_from_urn(code_urn: str) -> str | None:
|
||||
"""
|
||||
if not code_urn or "." not in code_urn:
|
||||
return None
|
||||
return code_urn.split(".")[-1]
|
||||
return code_urn.rsplit(".", maxsplit=1)[-1]
|
||||
|
||||
|
||||
def parse_codelist_id_from_urn(code_urn: str) -> str | None:
|
||||
@@ -559,7 +559,7 @@ def parse_codelist_id_from_urn(code_urn: str) -> str | None:
|
||||
return None
|
||||
try:
|
||||
# Extract everything after the last colon
|
||||
after_colon = code_urn.split(":")[-1]
|
||||
after_colon = code_urn.rsplit(":", maxsplit=1)[-1]
|
||||
# Extract everything before the opening parenthesis
|
||||
codelist_id = after_colon.split("(")[0]
|
||||
return codelist_id
|
||||
@@ -714,7 +714,7 @@ def parse_codelist_urn(urn: str) -> str | None:
|
||||
return None
|
||||
|
||||
try:
|
||||
parts = urn.split("=")[-1]
|
||||
parts = urn.rsplit("=", maxsplit=1)[-1]
|
||||
codelist_with_version = parts.split(":")[-1]
|
||||
codelist_id = codelist_with_version.split("(")[0]
|
||||
return codelist_id
|
||||
|
||||
@@ -955,7 +955,7 @@ class ImfMetadata:
|
||||
|
||||
if is_country_dim and dataflow_id:
|
||||
# Try dataflow-specific ISO country codelist first
|
||||
base_dataflow = dataflow_id.split("_")[0]
|
||||
base_dataflow = dataflow_id.split("_", maxsplit=1)[0]
|
||||
add_candidate(f"CL_{base_dataflow}_ISO_COUNTRY")
|
||||
add_candidate(f"CL_{dataflow_id}_COUNTRY")
|
||||
add_candidate(f"CL_{base_dataflow}_COUNTRY")
|
||||
@@ -968,7 +968,7 @@ class ImfMetadata:
|
||||
add_candidate(f"CL_{dataflow_id}_COUNTRY")
|
||||
add_candidate(f"CL_{dataflow_id}_COUNTRY_PUB")
|
||||
if "_" in dataflow_id:
|
||||
base_dataflow = dataflow_id.split("_")[0]
|
||||
base_dataflow = dataflow_id.split("_", maxsplit=1)[0]
|
||||
add_candidate(f"CL_{base_dataflow}_{dim_id}")
|
||||
add_candidate(f"CL_{base_dataflow}_{dim_id}_PUB")
|
||||
|
||||
|
||||
@@ -123,7 +123,7 @@ class TEEconomicCalendarQueryParams(EconomicCalendarQueryParams):
|
||||
def importance_to_number(cls, v):
|
||||
"""Convert importance to number."""
|
||||
string_to_value = {"low": 1, "medium": 2, "high": 3}
|
||||
return string_to_value.get(v.lower(), None) if v else None
|
||||
return string_to_value.get(v.lower()) if v else None
|
||||
|
||||
|
||||
class TEEconomicCalendarData(EconomicCalendarData):
|
||||
|
||||
@@ -220,8 +220,8 @@ async def get_defined_screener(
|
||||
|
||||
def get_expiration_month(symbol: str) -> str:
|
||||
"""Get the expiration month for a given symbol."""
|
||||
month = symbol.split(".")[0][-3]
|
||||
year = "20" + symbol.split(".")[0][-2:]
|
||||
month = symbol.split(".", maxsplit=1)[0][-3]
|
||||
year = "20" + symbol.split(".", maxsplit=1)[0][-2:]
|
||||
return f"{year}-{MONTH_MAP[month]}"
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"""Test yfinance helpers."""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from openbb_yfinance.utils.helpers import (
|
||||
df_transform_numbers,
|
||||
get_futures_data,
|
||||
get_custom_screener,
|
||||
get_defined_screener,
|
||||
get_futures_data,
|
||||
get_futures_symbols,
|
||||
yf_download,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user