Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion mcp_server/paddleocr_mcp/inference/shared/input_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from __future__ import annotations

import os
import tempfile
from contextlib import contextmanager
from enum import Enum
Expand Down Expand Up @@ -75,6 +76,11 @@ def looks_like_file_path(value: str) -> bool:
return Path(value).suffix.lower() in _INPUT_EXTENSIONS


def _is_existing_absolute_path(value: str) -> bool:
path = os.path.expanduser(value)
return os.path.isabs(path) and os.path.exists(path)


def classify_input(value: str) -> InputKind:
if is_url(value):
return InputKind.URL
Expand All @@ -83,6 +89,10 @@ def classify_input(value: str) -> InputKind:
if not is_base64(payload):
raise ValueError("Invalid data URL: payload is not valid Base64.")
return InputKind.DATA_URL
# Base64 and POSIX paths share the "/" character, so an existing absolute
# path such as "/etc/passwd" may also pass the Base64 check.
if _is_existing_absolute_path(value):
return InputKind.ABSOLUTE_PATH
if is_base64(value):
return InputKind.BASE64
if looks_like_file_path(value):
Expand Down Expand Up @@ -121,9 +131,12 @@ def validate_external_contract(input_data: str) -> InputKind:
data = decode_base64_payload(payload)
file_type = infer_file_type_from_bytes(data)
if file_type not in ("image", "pdf"):
hint = ""
if kind is InputKind.BASE64 and value.startswith("/"):
hint = f" If {value!r} is a file path, the file does not exist."
raise ValueError(
"Unsupported Base64 content type. Only image and PDF inputs are "
"supported."
f"supported.{hint}"
)

return kind
Expand Down
14 changes: 12 additions & 2 deletions mcp_server/paddleocr_mcp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from __future__ import annotations

import base64
import binascii
import re
from typing import Optional
from urllib.parse import urlparse
Expand All @@ -32,7 +33,13 @@ def is_url(value: str) -> bool:

def is_base64(value: str) -> bool:
pattern = r"^[A-Za-z0-9+/]+={0,2}$"
return bool(re.fullmatch(pattern, value))
if len(value) % 4 != 0 or not re.fullmatch(pattern, value):
return False
try:
base64.b64decode(value, validate=True)
except (binascii.Error, ValueError):
return False
return True


def extract_base64_payload(input_data: str) -> str:
Expand All @@ -56,7 +63,10 @@ def decode_base64_payload(payload: str) -> bytes:
def infer_file_type_from_bytes(data: bytes) -> Optional[str]:
import puremagic

mime = puremagic.from_string(data, mime=True)
try:
mime = puremagic.from_string(data, mime=True)
except puremagic.PureError:
return None
if mime.startswith("image/"):
return "image"
if mime == "application/pdf":
Expand Down
90 changes: 90 additions & 0 deletions tests/unit/test_mcp_input_contract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for MCP input classification of file paths vs. Base64 (issue #18412)."""

import base64
import io
import os

import pytest

pytest.importorskip("fastmcp")
pytest.importorskip("puremagic")

from paddleocr_mcp.inference.shared.input_contract import ( # noqa: E402
InputKind,
classify_input,
validate_external_contract,
)
from paddleocr_mcp.utils import is_base64 # noqa: E402

pytestmark = pytest.mark.py38_incompatible


def _png_base64() -> str:
from PIL import Image

buf = io.BytesIO()
Image.new("RGB", (8, 8)).save(buf, format="PNG")
return base64.b64encode(buf.getvalue()).decode()


@pytest.mark.parametrize(
"value, expected",
[
("aGVsbG8=", True),
("aGVsbG8gd29ybGQ=", True),
("/9j/4AAQ", True), # JPEG prefix starts with "/"
("aGVsbG8", False), # length not a multiple of 4
("/etc/passwd", False), # length 11
("aGVs=G8=", False), # padding in the middle
("aGVsbG8*", False), # character outside the alphabet
("", False),
],
)
def test_is_base64(value, expected):
assert is_base64(value) is expected


# Existing absolute paths made only of Base64-alphabet characters.
# "/usr/bin/env" is 12 characters long, so it is also decodable Base64.
@pytest.mark.parametrize("path", ["/etc/passwd", "/usr/bin/env", "/bin/sh"])
def test_existing_alphabet_only_path_is_classified_as_path(path):
if not os.path.exists(path):
pytest.skip(f"{path} does not exist on this platform")
assert classify_input(path) is InputKind.ABSOLUTE_PATH
assert validate_external_contract(path) is InputKind.ABSOLUTE_PATH


def test_raw_base64_is_still_classified_as_base64():
value = _png_base64()
assert classify_input(value) is InputKind.BASE64
assert validate_external_contract(value) is InputKind.BASE64


def test_base64_starting_with_slash_is_still_base64():
# JPEG data encodes to a string starting with "/9j/", which also looks
# like an absolute path; it must not be treated as one unless it exists.
value = base64.b64encode(b"\xff\xd8\xff\xe0" + b"\x00" * 32).decode()
assert value.startswith("/9j/")
assert classify_input(value) is InputKind.BASE64


def test_missing_alphabet_only_path_error_mentions_path():
# 32 Base64-alphabet characters: decodable, but not an image or PDF.
missing = "/nonexistent0dir/uploads/receipt"
assert not os.path.exists(missing)
with pytest.raises(ValueError, match="the file does not exist"):
validate_external_contract(missing)