MCP-Based .NET Micro-Weather Wisdom SMS Service Using Twilio & OpenAI
Time to read:
MCP-Based .NET Micro-Weather Wisdom SMS Service Using Twilio & OpenAI
This tutorial walks you step-by-step through building a production-minded but lightweight service that delivers personalized, actionable weather tips over SMS. Imagine users waking up to a short, friendly message like: “Good morning! 19°C and light rain in New York. Bring a light waterproof jacket and leave 10 mins early for your commute.”
That’s what you’ll build: a system that fetches weather forecasts through the MCP pattern, for easy data integration between different service providers and for testing. Then, the application asks OpenAI to craft crisp human-friendly advice, suggesting clothing, commute, and activities. It then delivers the advice via Twilio SMS, either on a schedule or on demand when somebody texts your number.
Prerequisites
- .NET 9 SDK installed (verify: dotnet --version and expect 9.x).
- An OpenAI API key (or equivalent LLM API).
- A Twilio account and phone number (trial accounts require verified recipient numbers).
- A Meteomatics account (username + password) or another weather API and credentials.
- ngrok (or any tunnel) for exposing local HTTP to the public internet.
Building the Application
Setting up the Working Environment
Start by initializing and creating the project structure. Run the command below to fire up the process.
These commands create a clean, organized project structure following .NET conventions. The dotnet new web
command creates a minimal web API template, perfect for webhook endpoints.
Next, install the required packages. To do so, copy and paste the commands below in your terminal and run them.
These packages provide essential functionality: Twilio SDK for SMS operations, JSON serialization for API responses, HTTP client for external API calls, and OpenAPI for intelligent operations.
Before you dive into the coding bit, you need to set up your configuration file with API credentials. Update your appsettings.json as shown below.
This configuration file stores all your API credentials securely. Replace the placeholder values with your actual API keys. The structure follows .NET's configuration conventions, making it easy to inject these values into your services.
Data Models Definition
Now start coding by defining your data models. These represent the structure of our weather data and user preferences.
Create Models/WeatherData.cs and update it with the code below:
These models define the structure for weather data you'll receive from the Meteomatics API and user preferences for personalized experiences. The WeatherData
class contains all essential weather metrics, while UserPreferences
allows customization of when and what type of weather insights users want to receive.
Weather Service Implementation
Now, implement the weather service that fetches real-time weather data and provides fallback mock data.
Create Services/WeatherService.cs then update it with the code below.
The WeatherService
implements a robust pattern for fetching weather data. It attempts to get real data from the Meteomatics API using Basic Authentication, but gracefully falls back to mock data if the API is unavailable. This ensures your service works even during development without API keys. The service uses dependency injection for the HTTP client and configuration, following .NET best practices.
This demo is hardcoded to use New York City as the default location, to avoid needing to make dynamic location requests. To use your own locale: change the coordinates
variable inside GetCurrentWeatherAsync
to your city’s latitude and longitude in lat, lon format (decimal degrees, no spaces) before running the app. Take for example 1.2921,36.8219 for Nairobi.
Intelligent Operations Service
Next, create the OpenAI service that transforms raw weather data into actionable insights.
Create Services/OpenAIService.cs then update it with the code below.
The OpenAIService
takes raw weather data and transforms it into personalized, actionable advice. It sends a carefully crafted prompt to OpenAI's GPT-3.5 model, requesting concise advice suitable for SMS. The service includes intelligent fallback logic that creates basic but useful weather insights even when the AI API is unavailable, ensuring reliability. Feel free to swap with any LLM provider.
SMS Communication Service
Now proceed to implement the Twilio service for sending and receiving SMS messages.
Create Services/TwilioService.cs then update it with the code below.
The TwilioService
handles all SMS communication using Twilio's REST API. It initializes the Twilio client with your credentials and provides methods to send weather insights via SMS. The service includes helpful simulation mode when credentials aren't configured, logging messages to the console instead of sending SMS, which is perfect for development and testing.
Background Scheduling Service
Finally, create the service that will handle scheduled daily weather updates for users.
Create Services/WeatherSchedulerService.cs and update it with the code below.
The WeatherSchedulerService
runs continuously in the background, checking every minute for users who should receive their daily weather update. When it finds a user whose preferred time matches the current time, it generates a personalized weather insight and sends it via SMS. This service demonstrates how to implement background tasks in .NET applications and includes proper error handling to maintain reliability.
Webhook Controller Implementation
Next, create the webhook controller that handles incoming SMS messages from Twilio.
Create Controllers/WebhookController.cs and update it with the code below.
The WebhookController
is the heart of the SMS interaction system. When someone sends an SMS to your Twilio number, Twilio forwards that message to this webhook endpoint. The controller analyzes the message content to understand what the user is asking about. It then generates a personalized weather response and sends it back. The controller returns proper TwiML XML responses that Twilio expects, ensuring reliable communication.
Main Application Setup
Finally, let's create the main application entry point that ties everything together.
Replace Program.cs with the code below.
The Program.cs file is the application's entry point. It configures dependency injection for all your services, sets up the web server with routing, and starts the background scheduler service. The application listens on port 5000 and provides helpful console output showing important URLs. This setup follows modern .NET patterns and ensures all services are properly initialized and connected.
Running and Testing the Application
Start Your Application
To fire up your application, run this command.
The application will start and display URLs in the console.
To expose your local server, open a new terminal window and run ngrok:
Copy the HTTPS URL provided (e.g., https://example123.ngrok.io). What this does: ngrok creates a secure tunnel from the internet to your local development server. This is necessary because Twilio needs a publicly accessible URL to send webhook requests to your application.
Configure Twilio Webhook
- Go to the Twilio Console (https://console.twilio.com/)
- Navigate to Phone Numbers → Manage → Active numbers
- Click on your Twilio phone number
- In the Messaging section, set the webhook URL to: https://example123.ngrok.io/webhook/sms
- Set HTTP method to POST
- Save the configuration
Simple use flow: SMS → Twilio → Webhook → Your Local App → AI Response → SMS Back
This tells Twilio where to forward incoming SMS messages. When someone texts your Twilio number, Twilio will send the message data to your webhook endpoint.
Testing Your Service
Send an SMS to your Twilio virtual phone number from a verified number. You can use a phone you have access to, or the Twilio Virtual phone. Try messages like:
- "What should I wear today?"
- "How's the weather for my commute?"
- "Good day for outdoor activities?"
See the screenshots below on how the service responds to the requests.


See below in the screenshot how the service responds. Feel free to try other organic queries to test the application's potential and limitations.


The application works as intended. You can now take this service further as discussed in the next steps.
Troubleshooting Steps
If you run into any errors getting the application running as described, there are a few troubleshooting steps that you can take:
- Credentials & config
- Confirm appsettings.json contains your real values (not placeholders) and that they’re in E.164 format for phone numbers (e.g. +14155554321).
- Verify Twilio:AccountSid and Twilio:AuthToken are correct.
- Confirm OpenAI:ApiKey and any weather API credentials are present and valid.
- Twilio trial / verified numbers
- If you’re on a Twilio trial, you can only send SMS to numbers you’ve verified in the Console (trial restriction). Upgrade the account to remove this limit.
- If your number is registered in the US, automated SMS may be restricted to verified 10DLC or verified toll-free numbers only.
- Webhook & tunnelling
- Confirm your ngrok (or other tunnel) URL matches what you entered in Twilio’s phone-number Messaging webhook, and that the webhook path is /webhook/sms (POST).
- Monitor OpenAI usage/quotas in your OpenAI Console (if the AI call fails or you’re on a limited trial, AI responses will fall back).
- Inspect Twilio MessageResource responses (Sid, Status, ErrorCode) — log them for postmortem analysis.
How to debug quickly
- Re-run locally with
dotnet run
and trigger a send; watch console logs for Twilio SDK errors. - Check Twilio Console → Messaging → Logs (and TrustHub / Regulatory Compliance) for deliverability errors and status codes.
Next Steps and Enhancements
Now that you have a working weather SMS service, consider these improvements:
- Database Integration: Replace the in-memory user list with a proper database
- User Management: Add SMS commands for users to update their preferences
- Multiple Locations: Allow users to set custom locations
- Rich Messaging: Add emojis and better formatting to responses
- Analytics: Track usage patterns and popular request types
Your Micro-Weather Wisdom SMS service is now ready to provide personalized weather insights to users via SMS! The service demonstrates proper webhook handling, API integration, background processing, and follows Twilio's best practices for SMS applications.
Additional Resources for Continued Learning
- AI Agent for Sending Emails Through WhatsApp Voice Notes Using Twilio, Sendgrid, .NET
- Build a Voice‑Driven WhatsApp Ticket Booking App with AI, Twilio & .NET
Jacob Snipes is a seasoned AI Engineer who transforms complex communication challenges into seamless, intelligent solutions. With a strong foundation in full-stack development and a keen eye for innovation, he crafts applications that enhance user experiences and streamline operations. Jacob's work bridges the gap between cutting-edge technology and real-world applications, delivering impactful results across various industries.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.