core

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 31, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package core provides shared utilities for the OpenStreetMap MCP tools.

Package core provides shared utilities for the OpenStreetMap MCP tools.

Package core provides shared utilities for the OpenStreetMap MCP tools.

Package core provides shared utilities for the OpenStreetMap MCP tools.

Package core provides shared utilities for the OpenStreetMap MCP tools.

Package core provides shared utilities for the OpenStreetMap MCP tools.

Package core provides shared utilities for the OpenStreetMap MCP tools.

Package core provides shared utilities for the OpenStreetMap MCP tools.

Index

Constants

View Source
const (
	// DefaultTileProvider is the default OSM tile server
	DefaultTileProvider = "https://tile.openstreetmap.org"

	// DefaultTileSize is the size of OSM tiles in pixels
	DefaultTileSize = 256

	// TileCacheTTL is how long to cache tiles
	TileCacheTTL = 24 * time.Hour
)

Variables

View Source
var DefaultClient = &http.Client{
	Timeout: 30 * time.Second,
	Transport: &http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 10,
		IdleConnTimeout:     90 * time.Second,
		TLSHandshakeTimeout: 10 * time.Second,
	},
}

DefaultClient provides a pre-configured HTTP client with secure defaults

View Source
var DefaultRetryOptions = RetryOptions{
	MaxAttempts:  3,
	InitialDelay: 500 * time.Millisecond,
	MaxDelay:     10 * time.Second,
	Multiplier:   2.0,
}

DefaultRetryOptions provides sensible defaults for retries

Functions

func CalculateOverallScore

func CalculateOverallScore(scores map[string]int, weights map[string]float64) int

CalculateOverallScore calculates an overall score as a weighted average of component scores

func DistanceBiasedScore

func DistanceBiasedScore(baseScore int, distance, maxDistance float64, maxScore float64) int

DistanceBiasedScore adjusts a base score based on distance The score decreases as distance increases

func DoWithRetry

func DoWithRetry(ctx context.Context, req *http.Request, client *http.Client) (*http.Response, error)

DoWithRetry performs an HTTP request with default retry options

func FetchMapTile

func FetchMapTile(ctx context.Context, x, y, zoom int) ([]byte, error)

FetchMapTile retrieves a map tile with caching and resource management

func GetTileResourceManager added in v0.1.2

func GetTileResourceManager() *cache.TileResourceManager

GetTileResourceManager returns the global tile resource manager

func InitTileCache

func InitTileCache()

InitTileCache initializes the tile cache

func InitTileResourceManager added in v0.1.2

func InitTileResourceManager(logger *slog.Logger)

InitTileResourceManager initializes the tile resource manager

func LatLonToTile

func LatLonToTile(lat, lon float64, zoom int) (x, y int)

LatLonToTile converts latitude, longitude and zoom to tile coordinates

func NormalizedWeightedScore

func NormalizedWeightedScore(counts map[string]int, weights []ScoreWeight, maxScore float64, normalizationFactor float64) int

NormalizedWeightedScore calculates a score based on counts and weights, then normalizes it to a value between 0 and maxScore

func ParseCoords

func ParseCoords(req mcp.CallToolRequest, latKey, lonKey string) (float64, float64, error)

ParseCoords parses and validates coordinates from a request

func ParseCoordsAndRadius

func ParseCoordsAndRadius(req mcp.CallToolRequest, latKey, lonKey, radiusKey string, defaultRadius, maxRadius float64) (lat, lon, radius float64, err error)

ParseCoordsAndRadius parses and validates coordinates and radius

func ParseCoordsAndRadiusWithLog

func ParseCoordsAndRadiusWithLog(req mcp.CallToolRequest, logger *slog.Logger, latKey, lonKey, radiusKey string, defaultRadius, maxRadius float64) (lat, lon, radius float64, err error)

ParseCoordsAndRadiusWithLog parses coordinates and radius with logging

func ParseCoordsWithLog

func ParseCoordsWithLog(req mcp.CallToolRequest, logger *slog.Logger, latKey, lonKey string) (float64, float64, error)

ParseCoordsWithLog parses coordinates with logging

func ParseRadius

func ParseRadius(req mcp.CallToolRequest, key string, defaultRadius, maxRadius float64) (float64, error)

ParseRadius parses and validates a radius parameter

func ParseRadiusWithLog

func ParseRadiusWithLog(req mcp.CallToolRequest, logger *slog.Logger, key string, defaultRadius, maxRadius float64) (float64, error)

ParseRadiusWithLog parses radius with logging

func SanitizeString

func SanitizeString(s string) string

SanitizeString removes potentially dangerous characters from a string

func ThresholdScores

func ThresholdScores(scores map[string]int, thresholds map[string][]int) map[string]string

ThresholdScores converts raw scores to categorical scores based on thresholds Example thresholds: map[string][]int{"low": {0, 30}, "medium": {31, 70}, "high": {71, 100}}

func TileToLatLon

func TileToLatLon(x, y, zoom int) (lat, lon float64)

TileToLatLon converts tile coordinates to latitude, longitude

func ValidateCoords

func ValidateCoords(lat, lon float64) error

ValidateCoords validates latitude and longitude coordinates

func ValidateNumericRange

func ValidateNumericRange(n float64, min, max float64) error

ValidateNumericRange checks if a number is within acceptable bounds

func ValidateRadius

func ValidateRadius(radius, maxRadius float64) error

ValidateRadius validates a search radius

func ValidateStringLength

func ValidateStringLength(s string, min, max int) error

ValidateStringLength checks if a string is within acceptable length bounds

func WeightedScore

func WeightedScore(counts map[string]int, weights []ScoreWeight, maxScore float64) int

WeightedScore calculates a score based on counts and weights It returns a value between 0 and maxScore

func WithRetry

func WithRetry(ctx context.Context, req *http.Request, client *http.Client, options RetryOptions) (*http.Response, error)

WithRetry performs an HTTP request with exponential backoff retry logic

func WithRetryFactory

func WithRetryFactory(ctx context.Context, factory RequestFactory, client *http.Client, options RetryOptions) (*http.Response, error)

WithRetryFactory performs HTTP requests created by a factory with retry logic

Types

type ElementFilter

type ElementFilter struct {
	ElementType string // "node", "way", "relation"
	Tags        []TagFilter
	BBox        *geo.BoundingBox // Optional bounding box
	Around      *LocationRadius  // Optional around filter
}

ElementFilter represents a filter with tags for a specific element type

type ErrorCode

type ErrorCode string

ErrorCode defines standard error codes for MCP tools

const (
	// Input validation errors
	ErrInvalidInput     ErrorCode = "INVALID_INPUT"
	ErrInvalidLatitude  ErrorCode = "INVALID_LATITUDE"
	ErrInvalidLongitude ErrorCode = "INVALID_LONGITUDE"
	ErrInvalidRadius    ErrorCode = "INVALID_RADIUS"
	ErrRadiusTooLarge   ErrorCode = "RADIUS_TOO_LARGE"
	ErrEmptyParameter   ErrorCode = "EMPTY_PARAMETER"
	ErrMissingParameter ErrorCode = "MISSING_PARAMETER"
	ErrInvalidParameter ErrorCode = "INVALID_PARAMETER"

	// Service errors
	ErrServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"
	ErrServiceTimeout     ErrorCode = "SERVICE_TIMEOUT"
	ErrRateLimit          ErrorCode = "RATE_LIMIT"
	ErrNetworkError       ErrorCode = "NETWORK_ERROR"

	// Data errors
	ErrNoResults     ErrorCode = "NO_RESULTS"
	ErrParseError    ErrorCode = "PARSE_ERROR"
	ErrInternalError ErrorCode = "INTERNAL_ERROR"
)

Standard error codes

type LocationRadius

type LocationRadius struct {
	Lat    float64
	Lon    float64
	Radius float64
}

LocationRadius represents a center point with a radius

type MCPError

type MCPError struct {
	Code        string   `json:"code"`
	Message     string   `json:"message"`
	Query       string   `json:"query,omitempty"`
	Suggestions []string `json:"suggestions,omitempty"`
	Guidance    string   `json:"guidance,omitempty"`
}

MCPError represents a detailed error structure for MCP tool responses

func NewError

func NewError(code ErrorCode, message string) *MCPError

NewError creates a new MCPError with the given code and message

func NewValidationError

func NewValidationError(code ErrorCode, message string) *MCPError

NewValidationError creates an error for validation failures

func ServiceError

func ServiceError(service string, statusCode int, message string) *MCPError

ServiceError creates an error for external service failures

func (MCPError) Error

func (e MCPError) Error() string

Error implements the error interface

func (*MCPError) ToMCPResult

func (e *MCPError) ToMCPResult() *mcp.CallToolResult

ToMCPResult converts the error to an MCP tool result

func (*MCPError) WithGuidance

func (e *MCPError) WithGuidance(guidance string) *MCPError

WithGuidance adds guidance information to the error

func (*MCPError) WithQuery

func (e *MCPError) WithQuery(query string) *MCPError

WithQuery adds query information to the error

func (*MCPError) WithSuggestions

func (e *MCPError) WithSuggestions(suggestions ...string) *MCPError

WithSuggestions adds suggestions to the error

type OSRMLeg

type OSRMLeg struct {
	Duration    float64    `json:"duration"` // Duration in seconds
	Distance    float64    `json:"distance"` // Distance in meters
	Summary     string     `json:"summary"`  // Summary of the leg
	Weight      float64    `json:"weight"`   // Weight value
	Steps       []OSRMStep `json:"steps"`    // Step-by-step instructions
	Annotations struct {
		Duration []float64 `json:"duration,omitempty"` // Duration per segment
		Distance []float64 `json:"distance,omitempty"` // Distance per segment
		Speed    []float64 `json:"speed,omitempty"`    // Speed per segment
		Weight   []float64 `json:"weight,omitempty"`   // Weight per segment
	} `json:"annotations,omitempty"`
}

OSRMLeg represents a leg of a route between two waypoints

type OSRMManeuver

type OSRMManeuver struct {
	Type        string    `json:"type"`                  // Type of maneuver
	Modifier    string    `json:"modifier,omitempty"`    // Direction modifier
	Location    []float64 `json:"location"`              // Coordinates [lon, lat]
	Instruction string    `json:"instruction,omitempty"` // Human-readable instruction
}

OSRMManeuver represents a maneuver instruction

type OSRMOptions

type OSRMOptions struct {
	// Base URL for the OSRM service
	BaseURL string

	// Profile to use (car, bike, foot)
	Profile string

	// Overview determines the geometry precision
	// "simplified", "full", "false"
	Overview string

	// Steps controls whether to return step-by-step instructions
	Steps bool

	// Annotations adds additional metadata to the route
	// "duration", "nodes", "distance", "speed", "weight", etc.
	Annotations []string

	// Alternatives controls whether to return alternative routes
	Alternatives int

	// Geometries controls the format of the returned geometry
	// "polyline", "polyline6", "geojson"
	Geometries string

	// Waypoints indices of waypoints to use (0-based)
	Waypoints []int

	// SampleInterval distance between samples in meters (if > 0, samples the route)
	SampleInterval float64

	// MaxAlternatives maximum number of alternatives to return
	MaxAlternatives int

	// Client is the HTTP client to use for requests
	Client *http.Client

	// RetryOptions controls retry behavior
	RetryOptions RetryOptions
}

OSRMOptions defines options for OSRM route requests

func DefaultOSRMOptions

func DefaultOSRMOptions() OSRMOptions

DefaultOSRMOptions returns reasonable defaults for OSRM requests

type OSRMResult

type OSRMResult struct {
	Code      string         `json:"code"`      // Status code
	Message   string         `json:"message"`   // Error message if applicable
	Routes    []OSRMRoute    `json:"routes"`    // Array of routes
	Waypoints []OSRMWaypoint `json:"waypoints"` // Array of waypoints
}

OSRMResult represents the complete response from the OSRM service

func GetRoute

func GetRoute(ctx context.Context, coordinates [][]float64, options OSRMOptions) (*OSRMResult, error)

GetRoute fetches a route from the OSRM service

type OSRMRoute

type OSRMRoute struct {
	Duration   float64   `json:"duration"`    // Duration in seconds
	Distance   float64   `json:"distance"`    // Distance in meters
	Geometry   string    `json:"geometry"`    // Encoded polyline or GeoJSON
	Weight     float64   `json:"weight"`      // Weight value (typically duration)
	WeightName string    `json:"weight_name"` // Name of the weight metric
	Legs       []OSRMLeg `json:"legs"`        // Route legs between waypoints
}

OSRMRoute represents a route returned by the OSRM service

type OSRMStep

type OSRMStep struct {
	Duration float64      `json:"duration"` // Duration in seconds
	Distance float64      `json:"distance"` // Distance in meters
	Name     string       `json:"name"`     // Road name
	Mode     string       `json:"mode"`     // Transport mode
	Geometry string       `json:"geometry"` // Encoded polyline
	Maneuver OSRMManeuver `json:"maneuver"` // Maneuver instructions
}

OSRMStep represents a single step in a route leg

type OSRMWaypoint

type OSRMWaypoint struct {
	Name     string    `json:"name"`     // Street name
	Location []float64 `json:"location"` // Coordinates [lon, lat]
	Distance float64   `json:"distance"` // Distance from requested coordinate
}

OSRMWaypoint represents a waypoint in the route

type OverpassBuilder

type OverpassBuilder struct {
	// contains filtered or unexported fields
}

OverpassBuilder provides a fluent interface for building Overpass API queries

func NewOverpassBuilder

func NewOverpassBuilder() *OverpassBuilder

NewOverpassBuilder creates a new builder with default settings

func (*OverpassBuilder) Build

func (b *OverpassBuilder) Build() string

Build generates the Overpass query string

func (*OverpassBuilder) WithBoundingBox

func (b *OverpassBuilder) WithBoundingBox(minLat, minLon, maxLat, maxLon float64) *OverpassBuilder

WithBoundingBox sets a bounding box filter

func (*OverpassBuilder) WithCenter

func (b *OverpassBuilder) WithCenter(lat, lon, radius float64) *OverpassBuilder

WithCenter sets a center point and radius

func (*OverpassBuilder) WithExcludeTag

func (b *OverpassBuilder) WithExcludeTag(key string, values ...string) *OverpassBuilder

WithExcludeTag adds a global exclude tag filter

func (*OverpassBuilder) WithNode

func (b *OverpassBuilder) WithNode(tags ...TagFilter) *OverpassBuilder

WithNode adds a node filter

func (*OverpassBuilder) WithOutputFormat

func (b *OverpassBuilder) WithOutputFormat(format string) *OverpassBuilder

WithOutputFormat sets the output format

func (*OverpassBuilder) WithRelation

func (b *OverpassBuilder) WithRelation(tags ...TagFilter) *OverpassBuilder

WithRelation adds a relation filter

func (*OverpassBuilder) WithTag

func (b *OverpassBuilder) WithTag(key string, values ...string) *OverpassBuilder

WithTag adds a global tag filter

func (*OverpassBuilder) WithTimeout

func (b *OverpassBuilder) WithTimeout(seconds int) *OverpassBuilder

WithTimeout sets the query timeout

func (*OverpassBuilder) WithWay

func (b *OverpassBuilder) WithWay(tags ...TagFilter) *OverpassBuilder

WithWay adds a way filter

type Point

type Point struct {
	Longitude float64
	Latitude  float64
}

Point represents a geographic point

type RequestFactory

type RequestFactory func() (*http.Request, error)

RequestFactory is a function that creates a new HTTP request This approach allows for retrying requests with bodies

type RetryOptions

type RetryOptions struct {
	MaxAttempts  int
	InitialDelay time.Duration
	MaxDelay     time.Duration
	Multiplier   float64
}

RetryOptions configures retry behavior for HTTP requests

type ScoreWeight

type ScoreWeight struct {
	Category string  // Name of the category
	Weight   float64 // Weight multiplier
}

ScoreWeight represents a weight for a specific category in a scoring algorithm

type SimpleRoute

type SimpleRoute struct {
	Distance     float64  `json:"distance"`               // Distance in meters
	Duration     float64  `json:"duration"`               // Duration in seconds
	Polyline     string   `json:"polyline"`               // Encoded polyline
	Points       []Point  `json:"points,omitempty"`       // Decoded points
	Summary      string   `json:"summary"`                // Route summary
	Instructions []string `json:"instructions,omitempty"` // Turn-by-turn instructions
}

SimpleRoute represents a simplified route

func GetSimpleRoute

func GetSimpleRoute(ctx context.Context, from, to []float64, mode string) (*SimpleRoute, error)

GetSimpleRoute is a convenience wrapper that returns a simplified route

type TagFilter

type TagFilter struct {
	Key     string
	Values  []string
	Exclude bool
}

TagFilter represents a tag filter for Overpass queries

func NotTag

func NotTag(key string, values ...string) TagFilter

NotTag creates an excluding TagFilter

func Tag

func Tag(key string, values ...string) TagFilter

Tag creates a TagFilter for a key with optional values

type TileInfo

type TileInfo struct {
	Zoom      int     `json:"zoom"`
	X         int     `json:"x"`
	Y         int     `json:"y"`
	CenterLat float64 `json:"center_lat"`
	CenterLon float64 `json:"center_lon"`
	NorthLat  float64 `json:"north_lat"`
	SouthLat  float64 `json:"south_lat"`
	EastLon   float64 `json:"east_lon"`
	WestLon   float64 `json:"west_lon"`
	TileURL   string  `json:"tile_url"`
	PixelSize float64 `json:"pixel_size_meters"` // Approximate meters per pixel at this zoom/latitude
	MapScale  string  `json:"map_scale"`         // Approximate map scale (e.g. "1:10000")
}

TileInfo contains information about a map tile

func GetTileInfo

func GetTileInfo(x, y, zoom int) TileInfo

GetTileInfo returns information about a tile

type ToolFactory

type ToolFactory struct {
}

ToolFactory provides a simplified way to create new tool definitions with standardized parameters

func NewToolFactory

func NewToolFactory() *ToolFactory

NewToolFactory creates a new tool factory

func (*ToolFactory) CreateBasicTool

func (f *ToolFactory) CreateBasicTool(name, description string) mcp.Tool

CreateBasicTool creates a new tool with the specified name and description

func (*ToolFactory) CreateLocationTool

func (f *ToolFactory) CreateLocationTool(name, description string, defaultRadius, maxRadius float64) mcp.Tool

CreateLocationTool creates a tool with coordinates and radius parameters

func (*ToolFactory) CreateRouteTool

func (f *ToolFactory) CreateRouteTool(name, description string) mcp.Tool

CreateRouteTool creates a tool for routing between two points

func (*ToolFactory) CreateSearchTool

func (f *ToolFactory) CreateSearchTool(name, description string, defaultRadius, maxRadius float64, defaultLimit, maxLimit int) mcp.Tool

CreateSearchTool creates a tool with coordinates, radius, category and limit parameters

type ValidationError

type ValidationError struct {
	Code    string
	Message string
}

ValidationError represents a validation error with a specific code and message

func (ValidationError) Error

func (e ValidationError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL