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
- Variables
- func CalculateOverallScore(scores map[string]int, weights map[string]float64) int
- func DistanceBiasedScore(baseScore int, distance, maxDistance float64, maxScore float64) int
- func DoWithRetry(ctx context.Context, req *http.Request, client *http.Client) (*http.Response, error)
- func FetchMapTile(ctx context.Context, x, y, zoom int) ([]byte, error)
- func GetTileResourceManager() *cache.TileResourceManager
- func InitTileCache()
- func InitTileResourceManager(logger *slog.Logger)
- func LatLonToTile(lat, lon float64, zoom int) (x, y int)
- func NormalizedWeightedScore(counts map[string]int, weights []ScoreWeight, maxScore float64, ...) int
- func ParseCoords(req mcp.CallToolRequest, latKey, lonKey string) (float64, float64, error)
- func ParseCoordsAndRadius(req mcp.CallToolRequest, latKey, lonKey, radiusKey string, ...) (lat, lon, radius float64, err error)
- func ParseCoordsAndRadiusWithLog(req mcp.CallToolRequest, logger *slog.Logger, latKey, lonKey, radiusKey string, ...) (lat, lon, radius float64, err error)
- func ParseCoordsWithLog(req mcp.CallToolRequest, logger *slog.Logger, latKey, lonKey string) (float64, float64, error)
- func ParseRadius(req mcp.CallToolRequest, key string, defaultRadius, maxRadius float64) (float64, error)
- func ParseRadiusWithLog(req mcp.CallToolRequest, logger *slog.Logger, key string, ...) (float64, error)
- func SanitizeString(s string) string
- func ThresholdScores(scores map[string]int, thresholds map[string][]int) map[string]string
- func TileToLatLon(x, y, zoom int) (lat, lon float64)
- func ValidateCoords(lat, lon float64) error
- func ValidateNumericRange(n float64, min, max float64) error
- func ValidateRadius(radius, maxRadius float64) error
- func ValidateStringLength(s string, min, max int) error
- func WeightedScore(counts map[string]int, weights []ScoreWeight, maxScore float64) int
- func WithRetry(ctx context.Context, req *http.Request, client *http.Client, ...) (*http.Response, error)
- func WithRetryFactory(ctx context.Context, factory RequestFactory, client *http.Client, ...) (*http.Response, error)
- type ElementFilter
- type ErrorCode
- type LocationRadius
- type MCPError
- type OSRMLeg
- type OSRMManeuver
- type OSRMOptions
- type OSRMResult
- type OSRMRoute
- type OSRMStep
- type OSRMWaypoint
- type OverpassBuilder
- func (b *OverpassBuilder) Build() string
- func (b *OverpassBuilder) WithBoundingBox(minLat, minLon, maxLat, maxLon float64) *OverpassBuilder
- func (b *OverpassBuilder) WithCenter(lat, lon, radius float64) *OverpassBuilder
- func (b *OverpassBuilder) WithExcludeTag(key string, values ...string) *OverpassBuilder
- func (b *OverpassBuilder) WithNode(tags ...TagFilter) *OverpassBuilder
- func (b *OverpassBuilder) WithOutputFormat(format string) *OverpassBuilder
- func (b *OverpassBuilder) WithRelation(tags ...TagFilter) *OverpassBuilder
- func (b *OverpassBuilder) WithTag(key string, values ...string) *OverpassBuilder
- func (b *OverpassBuilder) WithTimeout(seconds int) *OverpassBuilder
- func (b *OverpassBuilder) WithWay(tags ...TagFilter) *OverpassBuilder
- type Point
- type RequestFactory
- type RetryOptions
- type ScoreWeight
- type SimpleRoute
- type TagFilter
- type TileInfo
- type ToolFactory
- func (f *ToolFactory) CreateBasicTool(name, description string) mcp.Tool
- func (f *ToolFactory) CreateLocationTool(name, description string, defaultRadius, maxRadius float64) mcp.Tool
- func (f *ToolFactory) CreateRouteTool(name, description string) mcp.Tool
- func (f *ToolFactory) CreateSearchTool(name, description string, defaultRadius, maxRadius float64, ...) mcp.Tool
- type ValidationError
Constants ¶
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 ¶
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
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 ¶
CalculateOverallScore calculates an overall score as a weighted average of component scores
func DistanceBiasedScore ¶
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 ¶
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 InitTileResourceManager ¶ added in v0.1.2
InitTileResourceManager initializes the tile resource manager
func LatLonToTile ¶
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 ¶
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 ¶
SanitizeString removes potentially dangerous characters from a string
func ThresholdScores ¶
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 ¶
TileToLatLon converts tile coordinates to latitude, longitude
func ValidateCoords ¶
ValidateCoords validates latitude and longitude coordinates
func ValidateNumericRange ¶
ValidateNumericRange checks if a number is within acceptable bounds
func ValidateRadius ¶
ValidateRadius validates a search radius
func ValidateStringLength ¶
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 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 ¶
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 NewValidationError ¶
NewValidationError creates an error for validation failures
func ServiceError ¶
ServiceError creates an error for external service failures
func (*MCPError) ToMCPResult ¶
func (e *MCPError) ToMCPResult() *mcp.CallToolResult
ToMCPResult converts the error to an MCP tool result
func (*MCPError) WithGuidance ¶
WithGuidance adds guidance information to the error
func (*MCPError) WithSuggestions ¶
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 RequestFactory ¶
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 ¶
GetSimpleRoute is a convenience wrapper that returns a simplified route
type TagFilter ¶
TagFilter represents a tag filter for Overpass queries
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 ¶
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 (*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 ¶
ValidationError represents a validation error with a specific code and message
func (ValidationError) Error ¶
func (e ValidationError) Error() string